1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647
|
# mypy: allow-untyped-decorators
# mypy: allow-untyped-defs
import builtins
import collections
import inspect
import itertools
import math
import operator
import warnings
from collections.abc import Iterable
from enum import Enum
from functools import partial, reduce, singledispatch, wraps
from typing import (
Any,
Callable,
cast,
Dict,
List,
Optional,
overload,
Sequence,
Tuple,
Union,
)
import torch
import torch._prims as prims
import torch._prims_common as utils
import torch.utils._pytree as pytree
from torch import sym_float, sym_int
from torch._prims_common import (
BoolLike,
DeviceLikeType,
Dim,
DimsSequenceType,
DimsType,
dtype_to_type,
ELEMENTWISE_TYPE_PROMOTION_KIND,
FloatLike,
FloatWithoutSymFloat,
IntLike,
is_weakly_lesser_type,
Number,
NumberType,
RealNumberType,
REDUCTION_OUTPUT_TYPE_KIND,
ShapeType,
StrideType,
TensorLike,
TensorLikeType,
TensorOrNumberLikeType,
TensorSequenceType,
)
from torch._prims_common.wrappers import (
_maybe_convert_to_dtype,
_maybe_resize_out,
_safe_copy_out,
elementwise_type_promotion_wrapper,
elementwise_unary_scalar_wrapper,
out_wrapper,
)
# Experimental module containing prototype Python references for existing
# PyTorch operations.
__all__ = [
#
# Elementwise Unary References
#
"abs",
"acos",
"acosh",
"asinh",
"asin",
"atan",
"atanh",
"bitwise_not",
# "cbrt", # No corresponding torch operation
"ceil",
"conj_physical",
"cos",
"cosh",
"count_nonzero",
"deg2rad",
"digamma",
"erf",
"erfinv",
"erfc",
"exp",
"expm1",
"exponential",
"exp2",
"fill",
"fill_",
"floor",
"frac",
"geometric",
"index_add",
"index_copy",
"index_copy_",
"index_select",
"index_fill",
"index_fill_",
"isfinite",
"isinf",
"isposinf",
"isneginf",
"isnan",
"isreal",
"i0",
"lerp",
"lgamma",
"log",
"log1p",
"log2",
"log10",
"log_normal",
"log_softmax",
"mvlgamma",
"norm",
"normal",
"nan_to_num",
"neg",
"positive",
"rad2deg",
"reciprocal",
"round", # TODO: model kwargs
"sigmoid",
"sgn",
"sign",
"signbit",
"sin",
"sinc",
"sinh",
"softmax",
"sqrt",
"square",
"tan",
"tanh",
"trace",
"trunc",
#
# Elementwise Binary References
#
"add",
"atan2",
"bitwise_and",
"bitwise_left_shift",
"bitwise_or",
"bitwise_right_shift",
"bitwise_xor",
"clamp_min",
"clamp_max",
"copysign",
"div",
"eq",
"float_power",
"floor_divide",
"fmax",
"fmin",
"fmod",
"gcd",
"ge",
"gt",
"heaviside",
"hypot",
"igamma",
"igammac",
"imag",
"isclose",
"lcm",
# 'ldexp',
"le",
"logaddexp",
"logaddexp2",
"logical_and",
"logical_not",
"logical_or",
"logical_xor",
"logsumexp",
"lt",
# 'max', # implement with reductions
"maximum",
# 'min', # implement with reductions
"minimum",
"mul",
"ne",
"nextafter",
# 'polar', # abs, cos, sin
"pow",
"real",
"rpow",
"remainder",
"rsub",
"rtruediv",
"rfloordiv",
"sub",
"true_divide",
"trunc_divide",
"xlogy",
#
# Elementwise Ternary References
#
"addcdiv",
"addcmul",
"clamp",
#
# Conditional references
#
"masked_fill",
"masked_fill_",
"where",
#
# Data conversion and movement references
#
"clone",
"copy_to", # TODO: add OpInfo (or implement .to)
"item",
"to",
#
# Reduction ops
#
"all",
"amax",
"amin",
"any",
"cumsum",
"cumprod",
"mean",
"dot",
"vdot",
"std",
"std_mean",
"sum",
"sum_to_size",
"prod",
"var",
"var_mean",
#
# Linear algebra ops
#
"addr",
#
# View & Shape Ops
#
"alias",
"alias_copy",
"atleast_1d",
"atleast_2d",
"atleast_3d",
"as_strided",
"as_strided_copy",
"as_strided_scatter",
"block_diag",
"broadcast_shapes",
"broadcast_tensors",
"broadcast_to",
"cat",
"chunk",
"column_stack",
"conj",
"constant_pad_nd",
"contiguous",
"diag_embed",
"diag",
"diagonal",
"diagonal_copy",
"diagonal_scatter",
"dsplit",
"dstack",
"expand",
"expand_as",
"expand_copy",
"flatten",
"flip",
"fliplr",
"flipud",
"hsplit",
"hstack",
"meshgrid",
"movedim",
"narrow",
"narrow_copy",
"native_group_norm",
"native_layer_norm",
"permute",
"permute_copy",
"ravel",
"repeat",
"reshape",
"reshape_as",
"roll",
"rot90",
"rsqrt",
"split_with_sizes",
"stack",
"swap_axes", # alias for transpose
"squeeze",
"squeeze_copy",
"t",
"t_copy",
"T",
"take_along_dim",
"tensor_split",
"transpose",
"transpose_copy",
"unfold",
"unfold_copy",
"unsqueeze",
"unsqueeze_copy",
"view",
"view_as",
"view_copy",
"vsplit",
"vstack",
"view_as_complex",
"unflatten",
"unbind",
"triu",
"tril",
"triu_indices",
"tril_indices",
#
# Tensor Creation
#
"arange",
"cauchy",
"empty",
"empty_like",
"empty_permuted",
"empty_strided",
"eye",
"full",
"full_like",
"linspace",
"logspace",
"new_empty",
"new_empty_strided",
"new_full",
"new_ones",
"new_zeros",
"ones",
"ones_like",
"randn",
"scalar_tensor",
"zero",
"zeros",
"zeros_like",
#
# Test-related functions
#
"allclose",
"equal",
#
# Statistical operations
#
"bucketize",
#
# Misc
#
"is_complex",
"renorm",
"stft",
"istft",
]
Tensor = torch.Tensor
DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined]
aten = torch._ops.ops.aten
# Note that the docstrings for the public methods from this file are in
# torch/_torch_docs.py
def is_noncontiguous_supported(device):
return device is None or device.type != "hpu"
def handle_noncontiguous_outputs(input_tlist, output):
device = None
from torch._subclasses.fake_tensor import FakeTensor
for t in input_tlist:
if isinstance(t, FakeTensor):
device = t.fake_device
break
if not is_noncontiguous_supported(device):
output = output.contiguous()
return output
def _broadcast_shapes(*_shapes):
from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
shapes = tuple(
(x,) if isinstance(x, IntLike) else x
for x in filter(lambda x: x is not None, _shapes)
)
# Short-circuits on no input
if len(shapes) == 0:
return None
# Type checking
# TODO: make common validations available as utils
for shape in shapes:
assert isinstance(shape, Sequence)
# Computes common shape
common_shape: List[Union[int, torch.SymInt]] = [
1,
] * reduce(max, (len(shape) for shape in shapes))
for arg_idx, shape in enumerate(shapes):
for idx in range(-1, -1 - len(shape), -1):
if guard_size_oblivious(common_shape[idx] == 1):
if shape[idx] < 0:
raise ValueError(
"Attempting to broadcast a dimension with negative length!"
)
common_shape[idx] = shape[idx]
elif guard_size_oblivious(shape[idx] != 1):
torch._check(
common_shape[idx] == shape[idx],
lambda: f"Attempting to broadcast a dimension of length {shape[idx]} at {idx}! "
f"Mismatching argument at index {arg_idx} had {shape}; but expected shape "
f"should be broadcastable to {common_shape}",
)
return common_shape
def _maybe_broadcast(*args, preserve_cpu_scalar_tensors=True):
# Computes common shape
common_shape = _broadcast_shapes(
*(t.shape if isinstance(t, TensorLike) else None for t in args)
)
def __maybe_broadcast(x, shape):
if x is None:
return None
elif isinstance(x, Number):
return x
elif isinstance(x, TensorLike):
if preserve_cpu_scalar_tensors and utils.is_cpu_scalar_tensor(x):
return x
if not utils.same_shape(x.shape, common_shape):
return x.expand(common_shape)
return x
else:
raise RuntimeError(
"Unexpected type when broadcasting: " + str(type(x)) + "!"
)
return tuple(__maybe_broadcast(x, common_shape) for x in args)
# Utilities should come BEFORE this import
from torch._decomp import register_decomposition
#
# Elementwise unary references
#
infer_aten_op = object()
# TODO: add type promotion support
def _make_elementwise_unary_reference(
type_promotion_kind,
*,
aten_op=infer_aten_op,
extra_meta=None,
exact_dtype=False,
) -> Callable:
def inner(prim: Callable):
nonlocal aten_op
@wraps(prim)
@out_wrapper(exact_dtype=exact_dtype)
@elementwise_unary_scalar_wrapper
@elementwise_type_promotion_wrapper(
type_promoting_args=("a",),
type_promotion_kind=type_promotion_kind,
)
def _ref(a: TensorLikeType) -> TensorLikeType:
if extra_meta is not None:
extra_meta(a)
output = prim(a)
return handle_noncontiguous_outputs([a], output)
if aten_op is infer_aten_op:
aten_op = utils.get_aten_op(prim, prim.__name__)
if aten_op is not None:
register_decomposition(aten_op)(_ref)
return _ref
return inner
def _make_alias(fn, name):
"""
This function defines an alias of another function and sets its __name__ argument.
It also sets its __module__ argument to the module of the caller.
Note that when naively doing `alias = fn`, we have that `alias.__name__ == "fn"`, and
`alias.__module__ == fn.__module__`.
"""
def _fn(*args, **kwargs):
return fn(*args, **kwargs)
_fn.__name__ = name
_fn.__module__ = inspect.currentframe().f_back.f_globals["__name__"] # type: ignore[union-attr]
return _fn
def _make_inplace(fn):
"""
Given a function with out variant (i.e. using `out_wrapper()), it returns its in-place variant
See https://github.com/pytorch/pytorch/wiki/Developer-FAQ#how-do-in-place-operations-work-in-pytorch
"""
# nb. We use the name of the first argument used in the unary references
@wraps(fn)
def _fn(a, *args, **kwargs):
return fn(a, *args, out=a, **kwargs)
inplace_name = f"{fn.__name__}_"
_fn.__name__ = inplace_name
_fn = register_decomposition(getattr(aten, inplace_name))(_fn) # type: ignore[assignment]
# We access the __all__ attribute of the module where fn is defined
# There may be a cleaner way of doing this...
from inspect import getmodule
_all = getmodule(fn).__all__ # type: ignore[union-attr]
if inplace_name not in _all:
_all.append(inplace_name)
return _fn
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT,
exact_dtype=True,
)
def abs(a):
return prims.abs(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def acos(a):
return prims.acos(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def acosh(a):
return prims.acosh(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def asin(a):
return prims.asin(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def asinh(a):
return prims.asinh(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def atan(a):
return prims.atan(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def atanh(a):
return prims.atanh(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT)
def bitwise_not(a):
return prims.bitwise_not(a)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
exact_dtype=True,
)
def ceil(a):
return prims.ceil(a)
@register_decomposition(aten.is_complex)
def is_complex(input: TensorLikeType):
return utils.is_complex_dtype(input.dtype)
@register_decomposition(aten.conj_physical)
@out_wrapper()
def conj_physical(input: TensorLikeType):
if not utils.is_complex_dtype(input.dtype):
return input
return prims.conj_physical(input)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def cos(a):
return prims.cos(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def cosh(a):
return prims.cosh(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def digamma(a):
return prims.digamma(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def erf(a):
return prims.erf(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def erfinv(a):
return prims.erf_inv(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def erfc(a):
return prims.erfc(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def exp(a):
return prims.exp(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def expm1(a):
return prims.expm1(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def exp2(a):
return prims.exp2(a)
# Fill has its own implementation because it has a value parameter
# CompositeImplicitAutograd - don't register decomp
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("a,"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH,
)
def fill(a: TensorLikeType, value: NumberType) -> TensorLikeType:
assert isinstance(a, TensorLike)
assert isinstance(value, Number)
python_type = utils.dtype_to_type(a.dtype)
if not utils.is_weakly_lesser_type(type(value), python_type):
msg = f"value argument of type {type(value)} cannot be safely cast to type {python_type}!"
raise ValueError(msg)
return prims.fill(a, value)
def fill_(a: TensorLikeType, value: NumberType) -> TensorLikeType:
r = prims.fill(a, value)
prims.copy_to(a, r)
return a
@register_decomposition(aten.zero)
@out_wrapper()
def zero(input: TensorLikeType) -> TensorLikeType:
return torch.zeros_like(input)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
exact_dtype=True,
)
def floor(a):
return prims.floor(a)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
exact_dtype=True,
)
def frac(x: TensorLikeType) -> TensorLikeType:
trunc_x = torch.mul(torch.floor(torch.abs(x)), torch.sign(x))
return torch.sub(x, trunc_x)
# imag does not use _make_elementwise_unary_reference because it does not support out
def imag(a: TensorLikeType) -> TensorLikeType:
assert isinstance(a, TensorLike)
torch._check(
utils.is_complex_dtype(a.dtype), lambda: "imag only supports complex tensors."
)
return prims.imag(a)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
aten_op=None, # CompositeImplicitAutograd
)
def isfinite(a: TensorLikeType) -> TensorLikeType:
if utils.is_float_dtype(a.dtype) or utils.is_complex_dtype(a.dtype):
return prims.isfinite(a)
return ones_like(a, dtype=torch.bool)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL)
def isinf(a: TensorLikeType) -> TensorLikeType:
if utils.is_complex_dtype(a.dtype):
return torch.logical_or(isinf(torch.real(a)), isinf(torch.imag(a)))
if utils.is_float_dtype(a.dtype):
return torch.abs(a) == float("inf")
return torch.zeros_like(a, dtype=torch.bool)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
exact_dtype=True,
)
def isposinf(a: TensorLikeType) -> TensorLikeType:
torch._check(
not utils.is_complex_dtype(a.dtype),
lambda: f"Complex dtype is not supported for isposinf, got dtype {a.dtype}",
)
if utils.is_float_dtype(a.dtype):
return a == float("inf")
return torch.zeros_like(a, dtype=torch.bool)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
exact_dtype=True,
)
def isneginf(a: TensorLikeType) -> TensorLikeType:
torch._check(
not utils.is_complex_dtype(a.dtype),
lambda: f"Complex dtype is not supported for isneginf, got dtype {a.dtype}",
)
if utils.is_float_dtype(a.dtype):
return a == float("-inf")
return torch.zeros_like(a, dtype=torch.bool)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL)
def isnan(a: TensorLikeType) -> TensorLikeType:
return prims.ne(a, a)
# alias
mvlgamma = _make_alias(torch.special.multigammaln, "mvlgamma") # type: ignore[has-type]
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
aten_op=None, # CompositeImplicitAutograd
)
def isreal(a: TensorLikeType) -> TensorLikeType:
if utils.is_complex_dtype(a.dtype):
return torch.imag(a) == 0
return torch.ones_like(a, dtype=torch.bool)
# TODO: if this is special maybe it should be defined there and imported here?
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, aten_op=aten.i0
)
def i0(a):
return prims.bessel_i0(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def lgamma(a):
return prims.lgamma(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def log(a):
return prims.log(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def log1p(a):
return prims.log1p(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def log2(a):
return prims.log2(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def log10(a):
return prims.log10(a)
# CompositeImplicitAutograd - don't register decomp
@out_wrapper()
def log_softmax(
a: TensorLikeType,
dim: int,
dtype: Optional[torch.dtype] = None,
) -> TensorLikeType:
result_dtype = dtype or a.dtype
computation_dtype = utils.get_computation_dtype(result_dtype)
a_ = _maybe_convert_to_dtype(a, computation_dtype)
return _maybe_convert_to_dtype(a_ - logsumexp(a_, dim, keepdim=True), result_dtype) # type: ignore[return-value]
@register_decomposition(aten.logsumexp)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("self",),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
)
def logsumexp(
self: TensorLikeType, dim: DimsType, keepdim: bool = False
) -> TensorLikeType:
if not isinstance(dim, Iterable):
dim = (dim,)
if self.numel() == 0:
return torch.sum(torch.exp(self), dim, keepdim).log()
maxes = torch.amax(torch.real(self), dim, keepdim=True)
maxes = torch.masked_fill(maxes, maxes.abs() == float("inf"), 0)
maxes_squeezed = maxes if keepdim else torch.squeeze(maxes, dim)
result = torch.sum(torch.exp(self - maxes), dim, keepdim)
return result.log().add(maxes_squeezed)
@register_decomposition(aten.nan_to_num)
@out_wrapper()
def nan_to_num(
a: TensorLikeType,
nan: Optional[NumberType] = 0.0,
posinf: Optional[NumberType] = None,
neginf: Optional[NumberType] = None,
) -> TensorLikeType:
assert isinstance(a, TensorLike)
if utils.is_boolean_dtype(a.dtype) or utils.is_integer_dtype(a.dtype):
return a.clone()
if nan is None:
nan = 0.0
if posinf is None:
posinf = torch.finfo(a.dtype).max
if neginf is None:
neginf = torch.finfo(a.dtype).min
result = torch.where(torch.isnan(a), nan, a) # type: ignore[call-overload]
result = torch.where(torch.isneginf(a), neginf, result) # type: ignore[call-overload]
result = torch.where(torch.isposinf(a), posinf, result) # type: ignore[call-overload]
return result
def _neg_meta(a: TensorLikeType):
torch._check(
a.dtype is not torch.bool,
lambda: (
"Negation, the `-` operator, on a bool tensor is not supported. "
"If you are trying to invert a mask, use the `~` or `logical_not()` "
"operator instead."
),
)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, extra_meta=_neg_meta
)
def neg(a):
return prims.neg(a)
# positive does not use _make_elementwise_unary_reference because it does not support out
# CompositeImplicitAutograd - don't register decomp
def positive(a: TensorLikeType) -> TensorLikeType:
assert isinstance(a, TensorLike)
if a.dtype is torch.bool:
msg = "positive does not support bool tensors."
raise RuntimeError(msg)
return a
# real does not use _make_elementwise_unary_reference because it does not support out
def real(a: TensorLikeType) -> TensorLikeType:
assert isinstance(a, TensorLike)
if utils.is_complex_dtype(a.dtype):
return prims.real(a)
return a
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def reciprocal(a):
return prims.reciprocal(a)
@register_decomposition(aten.round)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("a",),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def round(a: TensorLikeType, *, decimals: int = 0) -> TensorLikeType:
if decimals == 0:
return prims.round(a)
else:
ten_pow = 10**decimals
ten_neg_pow = 10 ** (-decimals)
return prims.mul(prims.round(prims.mul(a, ten_pow)), ten_neg_pow)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def rsqrt(a):
return prims.rsqrt(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def sigmoid(a: TensorLikeType) -> TensorLikeType:
return true_divide(1, add(1, exp(neg(a))))
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
exact_dtype=True,
)
def sgn(a):
if utils.is_complex_dtype(a.dtype):
a_abs = a.abs()
return torch.where(a_abs == 0, 0, a / a_abs)
else:
return a.sign()
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
exact_dtype=True,
)
def sign(a):
return prims.sign(a)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
exact_dtype=True,
)
def signbit(a):
return prims.signbit(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def sin(a):
return prims.sin(a)
# Autograd note: This will give the right first derivative at zero (by chance),
# but not the right second derivative
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def sinc(a):
a = math.pi * a
return torch.where(a == 0, 1, torch.sin(a) / a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def sinh(a):
return prims.sinh(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def sqrt(a):
return prims.sqrt(a)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.BOOL_TO_LONG,
aten_op=None, # CompositeImplicitAutograd,
)
def square(a: TensorLikeType) -> TensorLikeType:
return mul(a, a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def tan(a):
return prims.tan(a)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def tanh(a):
return prims.tanh(a)
@_make_elementwise_unary_reference(
ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
exact_dtype=True,
)
def trunc(a):
return prims.trunc(a)
# TODO: register this as a real ref/decomposition once TorchInductor supports complex!
def view_as_complex(self: TensorLikeType) -> TensorLikeType:
input_dtype = self.dtype
torch._check(
utils.is_float_dtype(input_dtype),
lambda: f"view_as_complex is only supported for floating point"
f"tensors, but got a tensor of scalar type: {input_dtype}",
)
sizes = self.size()
torch._check(
len(sizes) != 0,
lambda: "Input tensor must have one or more dimensions",
)
torch._check(
sizes[-1] == 2,
lambda: "Tensor must have a last dimension of size 2",
)
old_strides = self.stride()
torch._check(
old_strides[-1] == 1,
lambda: "Tensor must have a last dimension with stride 1",
)
dims = old_strides[:-1]
torch._check(
builtins.all(stride % 2 == 0 for stride in dims),
lambda: "Tensor must have a stride divisible by 2 for all but last dimension",
)
torch._check(
self.storage_offset() % 2 == 0,
lambda: "Tensor must have a storage_offset divisible by 2",
)
return prims.view_element_type(
self, utils.corresponding_complex_dtype(input_dtype)
).squeeze(-1)
def _make_elementwise_binary_reference(
type_promotion_kind,
aten_op=infer_aten_op,
name=None,
has_out=True,
supports_lhs_python_scalar=True,
supports_rhs_python_scalar=True,
supports_two_python_scalars=False,
should_register_decomposition=True,
) -> Callable:
def inner(prim: Callable):
nonlocal aten_op, name
if name is None:
name = prim.__name__
@wraps(prim)
@elementwise_type_promotion_wrapper(
type_promoting_args=("a", "b"),
type_promotion_kind=type_promotion_kind,
)
def _ref(
a: Union[Tensor, NumberType],
b: Union[Tensor, NumberType],
) -> Tensor:
torch._check_value(
supports_lhs_python_scalar or not isinstance(a, Number),
lambda: f"{name}: Received a lhs Python scalar to an elementwise binary "
"operation that does not accept lhs scalars!",
)
torch._check_value(
supports_rhs_python_scalar or not isinstance(b, Number),
lambda: f"{name}: Received a rhs Python scalar to an elementwise binary "
"operation that does not accept rhs scalars!",
)
torch._check_value(
supports_two_python_scalars
or not (isinstance(a, Number) and isinstance(b, Number)),
lambda: f"{name}: Receive two Number inputs to an elementwise binary operation!",
)
a, b = _maybe_broadcast(a, b)
output = prim(a, b)
return handle_noncontiguous_outputs([a, b], output)
if has_out:
_ref = out_wrapper()(_ref) # type: ignore[assignment]
_ref.__name__ = name
if aten_op is infer_aten_op:
aten_op = utils.get_aten_op(prim, name)
if aten_op is not None and should_register_decomposition:
register_decomposition(aten_op)(_ref)
return _ref
return inner
# Add has its own implementation because it has an alpha argument
@register_decomposition(aten.add)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("a", "b"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def add(
a: Union[TensorLikeType, NumberType],
b: Union[TensorLikeType, NumberType],
*,
alpha: Optional[NumberType] = None,
):
"""
Reference implementation of torch.add
"""
a, b = _maybe_broadcast(a, b)
if alpha is not None:
dtype = a.dtype if isinstance(a, TensorLike) else b.dtype # type: ignore[union-attr]
python_type = utils.dtype_to_type(dtype)
if python_type != bool and not utils.is_weakly_lesser_type(
type(alpha), python_type
):
msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!"
raise ValueError(msg)
if isinstance(b, TensorLike):
b = prims.mul(b, alpha)
else:
b = b * alpha
output = prims.add(a, b)
return handle_noncontiguous_outputs([a, b], output)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def atan2(a, b):
return prims.atan2(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def bitwise_and(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.bitwise_and(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def bitwise_left_shift(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.shift_left(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def bitwise_or(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.bitwise_or(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def bitwise_right_shift(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.shift_right_arithmetic(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def bitwise_xor(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.bitwise_xor(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
supports_lhs_python_scalar=False,
)
def copysign(
a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType]
):
if isinstance(b, Number) and isinstance(a, Tensor):
b = scalar_tensor(b, dtype=a.dtype, device=a.device)
elif isinstance(a, Tensor) and isinstance(b, Tensor) and a.device != b.device:
msg = f"Expected divisor (b) to be on the same device ({a.device}) as dividend (a), but it is found on {b.device}!"
raise RuntimeError(msg)
return where(signbit(b), neg(abs(a)), abs(a))
# complex = _make_elementwise_binary_reference(prims.complex, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT)
@register_decomposition(aten.div)
@out_wrapper()
def div(
a: Union[TensorLikeType, NumberType],
b: Union[TensorLikeType, NumberType],
*,
rounding_mode: Optional[str] = None,
):
"""
Reference implementation of torch.div
"""
if rounding_mode is None:
return true_divide(a, b)
elif rounding_mode == "trunc":
return trunc_divide(a, b)
elif rounding_mode == "floor":
return floor_divide(a, b)
else:
msg = f"div expected rounding_mode to be one of None, 'trunc', or 'floor' but found {rounding_mode}."
raise ValueError(msg)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
supports_lhs_python_scalar=False,
)
def eq(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.eq(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.BOOL_TO_LONG,
)
def pow(
a: Union[TensorLikeType, NumberType],
b: Union[TensorLikeType, NumberType],
) -> TensorLikeType:
assert isinstance(a, TensorLikeType) or isinstance(b, TensorLikeType)
if isinstance(b, Number):
if b == 1.0:
return a.clone() # type: ignore[return-value,union-attr]
elif b == 2.0:
return a * a # type: ignore[return-value]
elif b == 0.5:
return torch.sqrt(a) # type: ignore[arg-type]
elif isinstance(a, Number):
if a == 1.0:
return torch.fill(b, True)
if a == 2.0 and (
utils.is_float_dtype(b.dtype) or utils.is_complex_dtype(b.dtype)
):
return torch.exp2(b)
return prims.pow(a, b)
# Float power has its own implementation because it has unique type promotion.
# CompositeImplicitAutograd - don't register decomp
@out_wrapper()
def float_power(
a: Union[TensorLikeType, NumberType],
b: Union[TensorLikeType, NumberType],
) -> Tensor:
if isinstance(a, Number) and isinstance(b, Number):
raise ValueError(
"Receive two Number inputs to an elementwise binary operation!"
)
# Handles type promotion
dtype = utils.get_higher_dtype(a, b)
assert dtype is not None
if utils.is_complex_dtype(dtype):
dtype = torch.complex128
else:
dtype = torch.float64
# Float power has the following contiguous cast behavior to be
# consistent with its C++ impl
a = _maybe_convert_to_dtype(a, dtype)
b = _maybe_convert_to_dtype(b, dtype)
a, b = _maybe_broadcast(a, b)
return pow(a, b)
# >>> a = torch.tensor(-0.2500, dtype=torch.float64)
# tensor(-0.250000000000000, dtype=torch.float64)
#
# >>> b = torch.tensor(-0.0010, dtype=torch.float64)
# tensor(-0.001000000000000, dtype=torch.float64)
#
# Note: In this case, casting float to double will expand the float mantissa with zeros,
# while creating a double generates a distinct mantissa.
# >>> torch.tensor(-0.001).to(dtype=torch.float64)
# tensor(-0.001000000047497, dtype=torch.float64)
#
# Floor Division
# The difference is caused because torch.remainder(a, b) = -0.001.
#
# >>> torch.floor(torch.true_divide(a, b))
# tensor(250., dtype=torch.float64)
#
# >>> torch.div(a, b, rounding_mode='floor')
# tensor(249., dtype=torch.float64)
#
# Definition: a // b = (a - remainder(a, b)) / b
# >>> torch.true_divide(torch.sub(a, torch.remainder(a, b)), b)
# tensor(249., dtype=torch.float64)
#
# For reference, see CPython's implementation:
# https://github.com/python/cpython/blob/ace008c531dd685a30c1dd68f9b5ba35f20171cf/Objects/floatobject.c#L636
@_make_elementwise_binary_reference(
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_two_python_scalars=True,
should_register_decomposition=False,
)
def floor_divide(
a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType]
):
# Wrap scalars because some references only accept tensor arguments.
if isinstance(a, Number) and isinstance(b, Number):
a = scalar_tensor(a)
b = scalar_tensor(b)
elif isinstance(b, Number) and isinstance(a, Tensor):
b = scalar_tensor(b, dtype=a.dtype, device=a.device)
elif isinstance(a, Number) and isinstance(b, Tensor):
a = scalar_tensor(a, dtype=b.dtype, device=b.device)
elif isinstance(a, Tensor) and isinstance(b, Tensor) and a.device != b.device:
if a.device == torch.device("cpu"):
msg = f"Expected divisor (b) to be on the same device ({a.device}) as dividend (a), but it is found on {b.device}!"
raise RuntimeError(msg)
else:
b = prims.device_put(b, device=a.device)
assert isinstance(a, Tensor) and isinstance(b, Tensor)
dtype = a.dtype
if utils.is_float_dtype(dtype):
return _floor_divide_float(a, b)
elif utils.is_integer_dtype(dtype):
return _floor_divide_integer(a, b)
else:
torch._check(False, lambda: f"{dtype} not supported for floor_divide")
def _floor_divide_integer(a: Tensor, b: Tensor) -> Tensor:
a, b = _maybe_broadcast(a, b)
if not a.dtype.is_signed:
return prims.div(a, b)
# Convert truncation to flooring:
offset = (torch.signbit(a) != torch.signbit(b)).logical_and(torch.fmod(a, b) != 0)
return prims.div(a, b) - _maybe_convert_to_dtype(offset, a.dtype)
def _floor_divide_float(a: Tensor, b: Tensor) -> Tensor:
mod = fmod(a, b)
div = true_divide(sub(a, mod), b)
# Ensure that the remainder has the same sign as denominator
different_signed_inputs = bitwise_xor(lt(a, 0), lt(b, 0))
non_zero_remainder = ne(mod, 0)
mask = bitwise_and(non_zero_remainder, different_signed_inputs)
div = where(mask, sub(div, 1), div)
# Map quotient to nearest integer value
floor_div = floor(div)
mask = gt(sub(div, floor_div), 0.5)
floor_div = where(mask, add(floor_div, 1), floor_div)
basic_div = true_divide(a, b)
zero_tensor = scalar_tensor(0, dtype=basic_div.dtype, device=basic_div.device)
# If quotient is zero, copy signbit from true_divide quotient
floor_div = where(ne(div, 0), floor_div, copysign(zero_tensor, basic_div))
# If denominator is zero, then follow true_divide behavior
return where(ne(b, 0), floor_div, basic_div)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def fmax(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.fmax(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def fmin(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.fmin(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=True,
)
def fmod(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.fmod(a, b)
@register_decomposition(aten.frexp)
@out_wrapper("mantissa", "exponent")
def frexp(self: TensorLikeType) -> Tuple[TensorLikeType, TensorLikeType]:
return torch.return_types.frexp(prims.frexp(self))
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def gcd(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.gcd(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
supports_lhs_python_scalar=False,
)
def ge(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.ge(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
supports_lhs_python_scalar=False,
)
def gt(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.gt(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def heaviside(input: TensorLikeType, values: TensorLikeType) -> TensorLikeType:
input_eq_zero = torch.eq(input, 0)
input_lt_zero = torch.logical_or(torch.lt(input, 0), torch.isnan(input))
zeros_and_ones = torch.where(input_lt_zero, 0, 1)
output = torch.where(input_eq_zero, values, zeros_and_ones)
return output
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def hypot(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.hypot(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def igamma(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.igamma(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def igammac(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.igammac(a, b)
def _check_close_args(
name: str,
a: TensorLikeType,
b: TensorLikeType,
rtol: float,
atol: float,
) -> None:
torch._check_value(
a.dtype == b.dtype,
lambda: f"{name}: Attempting to compare tensors of different dtypes {a.dtype} and {b.dtype}!",
)
torch._check(
rtol >= 0,
lambda: f"{name}: rtol must be greater than or equal to zero, but got {rtol}!",
)
torch._check(
atol >= 0,
lambda: f"{name}: atol must be greater than or equal to zero, but got {atol}!",
)
# CompositeImplicitAutograd - don't register decomp
def isclose(
a: TensorLikeType,
b: TensorLikeType,
rtol: float = 1e-05,
atol: float = 1e-08,
equal_nan: bool = False,
) -> TensorLikeType:
_check_close_args(name="torch.isclose", a=a, b=b, rtol=rtol, atol=atol)
close = eq(a, b)
if equal_nan and (utils.is_float_dtype(a.dtype) or utils.is_complex_dtype(a.dtype)):
close = logical_or(close, logical_and(isnan(a), isnan(b)))
# Note: In case of zero tolerances the closeness inequality degenerates to an equality check.
# In this case, the short-circuit prevents false positives as detailed in the paragraph below.
if atol == 0 and rtol == 0:
return close
# Note [closeness error computation]
# atol and rtol are provided as doubles, so the computation
# rtol * other will produce a float or complex tensor.
# When the difference (self - other) is compared to it then the
# tensor representing the difference will also be cast to float or complex.
# However, since (self - other) in uint8 is very likely to produce a
# negative value, this moves the cast forward so the difference is
# always computed in a float or complex type.
# If the values of the integer tensors cannot be exactly represented
# by the default scalar type then this may cause an incorrect result.
if not utils.is_float_dtype(a.dtype) and not utils.is_complex_dtype(a.dtype):
a = prims.convert_element_type(a, torch.get_default_dtype())
b = prims.convert_element_type(b, torch.get_default_dtype())
allowed_error = add(atol, abs(mul(b, rtol)))
actual_error = abs(sub(a, b))
# Computes finite closeness
result = logical_or(
close, logical_and(isfinite(actual_error), le(actual_error, allowed_error))
)
return result
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def lcm(a: TensorLikeType, b: TensorLikeType):
dtype = a.dtype
# promoting to int32 to maintain 100% consistency with C++ and to
# prevent overflow in case of int8 and int16
promote_to_int = dtype in (torch.int8, torch.int16)
if promote_to_int:
a = prims.convert_element_type(a, torch.int32)
b = prims.convert_element_type(b, torch.int32)
g = torch.gcd(a, b)
# Avoid division by zero in case gcd(0, 0) == 0
g = torch.where(g == 0, 1, g)
res = torch.abs(prims.div(a, g) * b)
return res if not promote_to_int else prims.convert_element_type(res, dtype)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
supports_lhs_python_scalar=False,
)
def le(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.le(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def logaddexp(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
# Nb. this implementation does not distribute the gradients evenly when a == b
mask = torch.real(a) >= torch.real(b)
max_ = torch.where(mask, a, b)
min_ = torch.where(mask, b, a)
inf_mask = torch.logical_and(
torch.logical_not(torch.isfinite(torch.real(a))), torch.real(a) == torch.real(b)
)
if utils.is_complex_dtype(a.dtype) or utils.is_complex_dtype(b.dtype):
# are you wondering what this bunch of codes are for? edge cases!
neg_min_mask = torch.real(min_) < 0
inf_vals = torch.where(
neg_min_mask, min_, torch.log(torch.exp(min_) + torch.exp(max_))
)
non_nan_vals = torch.where(
inf_mask, inf_vals, max_ + torch.log1p(torch.exp(min_ - max_))
)
# the type for full_like does not include tensor yet
nan_mask = torch.isnan(min_)
return torch.where(nan_mask, complex(float("nan"), float("nan")), non_nan_vals) # type: ignore[call-overload]
else:
return torch.where(inf_mask, a, max_ + torch.log1p(torch.exp(min_ - max_)))
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def logaddexp2(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
torch._check(
not (utils.is_complex_dtype(a.dtype) or utils.is_complex_dtype(b.dtype)),
lambda: "logaddexp2 doesn't support complex dtypes",
)
# Nb. this implementation does not distribute the gradients evenly when a == b
mask = a >= b
max_ = torch.where(mask, a, b)
min_ = torch.where(mask, b, a)
inf_mask = torch.logical_and(torch.isinf(a), a == b)
inv_log_2 = 1.0 / math.log(2)
result = max_ + torch.log1p(torch.exp2(min_ - max_)) * inv_log_2
return torch.where(inf_mask, a, result)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
)
def logical_and(a: TensorLikeType, b: TensorLikeType):
if not utils.is_boolean_dtype(a.dtype):
a = a != 0
if not utils.is_boolean_dtype(b.dtype):
b = b != 0
return a & b
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL)
def logical_not(a: TensorLikeType):
if not utils.is_boolean_dtype(a.dtype):
return a == 0
return ~a
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
)
def logical_or(a: TensorLikeType, b: TensorLikeType):
if not utils.is_boolean_dtype(a.dtype):
a = a != 0
if not utils.is_boolean_dtype(b.dtype):
b = b != 0
return bitwise_or(a, b)
# TODO: skip unnecessary conversion of long to float
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
)
def logical_xor(a: TensorLikeType, b: TensorLikeType):
if not utils.is_boolean_dtype(a.dtype):
a = a != 0
if not utils.is_boolean_dtype(b.dtype):
b = b != 0
return a ^ b
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
supports_lhs_python_scalar=False,
)
def lt(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.lt(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def maximum(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.maximum(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def minimum(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.minimum(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
supports_two_python_scalars=True,
)
def mul(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.mul(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL,
supports_lhs_python_scalar=False,
)
def ne(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.ne(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH,
supports_lhs_python_scalar=False,
supports_rhs_python_scalar=False,
)
def nextafter(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.nextafter(a, b)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def remainder(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.remainder(a, b)
# reverse sub
@register_decomposition(aten.rsub)
@out_wrapper()
def rsub(
a: Union[TensorLikeType, NumberType],
b: Union[TensorLikeType, NumberType],
alpha: NumberType = 1,
):
if isinstance(a, Number):
msg = "Received a Number for the first argument, but expected a Tensor"
raise ValueError(msg)
return torch.sub(b, a, alpha=alpha)
# TODO: consider refactoring this with add impl
# sub has its own implementation because it has an alpha argument
@register_decomposition(aten.sub)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("a", "b"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def sub(
a: Union[TensorLikeType, NumberType],
b: Union[TensorLikeType, NumberType],
*,
alpha: NumberType = 1,
):
"""
Reference implementation of torch.sub
"""
a, b = _maybe_broadcast(a, b)
if isinstance(a, TensorLike) and isinstance(b, TensorLike):
torch._check(
not utils.is_boolean_dtype(a.dtype) and not utils.is_boolean_dtype(b.dtype),
lambda: (
"Subtraction, the `-` operator, with two bool tensors is not supported. "
"Use the `^` or `logical_xor()` operator instead."
),
)
if alpha != 1:
dtype = a.dtype if isinstance(a, TensorLike) else b.dtype # type: ignore[union-attr]
python_type = utils.dtype_to_type(dtype)
if not utils.is_weakly_lesser_type(type(alpha), python_type):
msg = f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!"
raise ValueError(msg)
if isinstance(b, torch.Tensor):
b = prims.mul(b, alpha)
else:
# Carefully not to use prims.mul if b is a scalar / symint.
# prims.mul always returns a tensor,
# which will mess with type promotion.
b = b * alpha
output = prims.sub(a, b)
return handle_noncontiguous_outputs([a, b], output)
@_make_elementwise_binary_reference(
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
name="true_divide",
aten_op=None, # CompositeImplicitAutograd
supports_two_python_scalars=True,
)
def true_divide(a: TensorLikeType, b: TensorLikeType) -> TensorLikeType:
return prims.div(a, b)
@register_decomposition(aten.xlogy)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("a", "b"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
)
def xlogy(a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType]):
torch._check(
isinstance(a, TensorLike) or isinstance(b, TensorLike),
lambda: 'Expected either argument a or b to be a Tensor"',
)
# Operations like eq and log do not handle scalar values, so we convert them to scalar_tensors.
if isinstance(b, TensorLike) and isinstance(a, Number):
a = scalar_tensor(a, dtype=b.dtype, device=b.device)
elif isinstance(a, TensorLike) and isinstance(b, Number):
b = scalar_tensor(b, dtype=a.dtype, device=a.device)
# mypy: expected "Tensor"
assert isinstance(a, TensorLike)
assert isinstance(b, TensorLike)
rhs = torch.where(torch.eq(a, 0), 0, torch.mul(a, torch.log(b)))
return torch.where(torch.isnan(b), float("nan"), rhs)
@_make_elementwise_binary_reference(
type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
aten_op=None, # CompositeImplicitAutograd
supports_two_python_scalars=True,
)
def trunc_divide(
a: Union[TensorLikeType, NumberType], b: Union[TensorLikeType, NumberType]
):
dtype = utils.get_dtype(a)
if utils.is_integer_dtype(dtype):
return prims.div(a, b)
return trunc(prims.div(a, b))
#
# Elementwise Ternary References
#
@register_decomposition(aten.addcdiv)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("self", "tensor1", "tensor2"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
)
def addcdiv(
self: TensorLikeType,
tensor1: TensorLikeType,
tensor2: TensorLikeType,
*,
value: NumberType = 1,
) -> TensorLikeType:
"""
Reference implementation of torch.addcdiv
"""
if value is not None:
dtype = self.dtype # no scalars allowed, see add
python_type = utils.dtype_to_type(dtype)
torch._check_value(
utils.is_weakly_lesser_type(type(value), python_type),
lambda: f"value argument of type {type(value)} cannot be safely cast to type {python_type}!",
)
return self + value * tensor1 / tensor2
@register_decomposition(aten.addcmul)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("self", "tensor1", "tensor2"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def addcmul(
self: TensorLikeType,
tensor1: TensorLikeType,
tensor2: TensorLikeType,
*,
value: NumberType = 1,
) -> TensorLikeType:
"""
Reference implementation of torch.addcmul
"""
if value is not None:
dtype = self.dtype # no scalars allowed, see add
python_type = utils.dtype_to_type(dtype)
torch._check_value(
utils.is_weakly_lesser_type(type(value), python_type),
lambda: f"value argument of type {type(value)} cannot be safely cast to type {python_type}!",
)
return self + value * tensor1 * tensor2
@register_decomposition(aten.clamp)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("a", "min", "max"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def clamp(
a: TensorLikeType,
min: Optional[TensorOrNumberLikeType] = None,
max: Optional[TensorOrNumberLikeType] = None,
) -> TensorLikeType:
# NOTE: grad behavior with implementation `where` is not consistent on `nan`
if min is None and max is None:
msg = "clamp called but both min and max are none!"
raise ValueError(msg)
if min is not None:
a_isnan = torch.isnan(a)
condition = torch.bitwise_or(torch.ge(a, min), a_isnan) # type: ignore[arg-type]
# we should also propagate `nan` coming from boundaries. However, that's
# not necessary since `ge` would already `False` when either operands has
# a `nan`. So this line below is redundant
# `condition = bitwise_and(condition, bitwise_not(isnan(min)))`
a = torch.where(condition, a, min) # type: ignore[arg-type]
if max is not None:
a_isnan = torch.isnan(a)
# same as above, no need to adjust `nan` from `max`
condition = torch.bitwise_or(torch.le(a, max), a_isnan) # type: ignore[arg-type]
a = torch.where(condition, a, max) # type: ignore[arg-type]
return a
@register_decomposition(aten.clamp_min)
@out_wrapper()
def clamp_min(
self: TensorLikeType,
min: Optional[TensorOrNumberLikeType] = None,
) -> TensorLikeType:
return torch.clamp(self, min=min) # type: ignore[arg-type]
@register_decomposition(aten.clamp_max)
@out_wrapper()
def clamp_max(
self: TensorLikeType,
max: Optional[TensorOrNumberLikeType] = None,
) -> TensorLikeType:
return torch.clamp(self, max=max) # type: ignore[arg-type]
#
# Conditional references
#
# https://pytorch.org/docs/stable/generated/torch.where.html
# TODO: implement alternate where
@register_decomposition(aten.where)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("a", "b"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH,
)
def where(
pred: Tensor,
a: Optional[TensorOrNumberLikeType] = None,
b: Optional[TensorOrNumberLikeType] = None,
):
""" """
if a is None or b is None:
raise NotImplementedError
utils.check_same_device(pred, a, b, allow_cpu_scalar_tensors=True)
torch._check(
pred.dtype is torch.bool,
lambda: f"expected predicate to be bool, got {pred.dtype}",
)
pred, a, b = _maybe_broadcast(pred, a, b)
return prims.where(pred, a, b)
#
# Data Movement References
#
@register_decomposition(aten.clone)
@out_wrapper()
def clone(
a: TensorLikeType, *, memory_format: torch.memory_format = torch.preserve_format
) -> TensorLikeType:
result = prims.clone(a, memory_format=memory_format)
return result
def copy_to(a: Tensor, b: Tensor, *, allow_cross_device=True):
if not allow_cross_device and a.device != b.device:
msg = f"Attempting to copy from device {b.device} to device {a.device}, but cross-device copies are not allowed!"
raise RuntimeError(msg)
return prims.copy_to(a, b)
@register_decomposition(aten.item)
def item(a: TensorLikeType) -> NumberType:
if a.numel() != 1:
msg = f"Can't convert a tensor with {a.numel()} elements to a number!"
raise ValueError(msg)
# NOTE: explicit conversion is necessary for bool!
# See https://github.com/pytorch/pytorch/issues/78071
number_type = utils.dtype_to_type(a.dtype)
return number_type(prims.item(a))
# fast path when `to` returns an alias to input. This mimics the same function in aten
def _to_will_alias(
a: TensorLikeType,
device: Optional[DeviceLikeType] = None,
dtype: Optional[torch.dtype] = None,
copy: Optional[bool] = None,
layout: Optional[torch.layout] = None,
memory_format: Optional[torch.memory_format] = None,
pin_memory: Optional[bool] = False,
non_blocking: bool = False, # not using non_blocking
) -> bool:
return (
not copy
and (device is None or a.device == device)
and (dtype is None or a.dtype == dtype)
and (layout is None or a.layout == layout)
# is_pinned issue #84925
# and (pin_memory is None or pin_memory == a.is_pinned())
and (
memory_format is None
or memory_format == torch.preserve_format
or utils.is_contiguous_for_memory_format(a, memory_format=memory_format)
)
)
@singledispatch
def _to_dispatch(*args, **kwargs):
raise NotImplementedError
@_to_dispatch.register
def _to_device(
device: torch.device,
dtype: torch.dtype,
non_blocking: bool = False,
copy: bool = False,
memory_format: Optional[torch.memory_format] = None,
) -> Dict[str, Any]:
kwargs = {
"device": device,
"dtype": dtype,
"non_blocking": non_blocking,
"copy": copy,
"memory_format": memory_format,
}
return kwargs
@_to_dispatch.register
def _to_device_str(
device: str,
dtype: torch.dtype,
non_blocking: bool = False,
copy: bool = False,
memory_format: Optional[torch.memory_format] = None,
) -> Dict[str, Any]:
kwargs = {
"device": torch.device(device),
"dtype": dtype,
"non_blocking": non_blocking,
"copy": copy,
"memory_format": memory_format,
}
return kwargs
@_to_dispatch.register
def _to_dtype(
dtype: torch.dtype,
non_blocking: bool = False,
copy: bool = False,
memory_format: Optional[torch.memory_format] = None,
) -> Dict[str, Any]:
kwargs = {
"dtype": dtype,
"non_blocking": non_blocking,
"copy": copy,
"memory_format": memory_format,
}
return kwargs
@_to_dispatch.register
def _to_other(
other: Tensor,
non_blocking: bool = False,
copy: bool = False,
memory_format: Optional[torch.memory_format] = None,
) -> Dict[str, Any]:
device = other.device
dtype = other.dtype
layout = other.layout
# is_pinned issue #84925
# pin_memory = other.is_pinned()
kwargs = {
"device": device,
"dtype": dtype,
"layout": layout,
"non_blocking": non_blocking,
"copy": copy,
"memory_format": memory_format,
}
return kwargs
# remove to_kwargs that is already present in `a`
def _canonicalize_to_arguments(a: Tensor, to_kwargs: dict):
options_to_check = ["dtype", "device", "layout", "memory_format"]
# "device" option could be passed a str instead torch.device
if "device" in to_kwargs and isinstance(to_kwargs["device"], str):
to_kwargs["device"] = torch.device(to_kwargs["device"])
for kw in options_to_check:
if kw in to_kwargs:
if (
(kw == "memory_format" and to_kwargs[kw] is torch.preserve_format)
or (
kw == "device"
and to_kwargs[kw].type == a.device.type
and (
not to_kwargs[kw].index or to_kwargs[kw].index == a.device.index
)
)
or (
getattr(a, kw, None) == to_kwargs[kw]
) # this also handles {"memory_format": None}
):
to_kwargs.pop(kw)
def to(a: TensorLikeType, *args, **kwargs) -> TensorLikeType:
# handled dispatch via positional arguments
if len(args) != 0:
kwargs = _to_dispatch(*args, **kwargs)
# TODO: is_pinned is not currently supported in refs or fake_tensor
# https://github.com/pytorch/pytorch/issues/84925
assert "pin_memory" not in kwargs
_canonicalize_to_arguments(a, kwargs)
if _to_will_alias(a, **kwargs):
return a
copy = kwargs.pop("copy") if "copy" in kwargs else False
non_blocking = kwargs.pop("non_blocking") if "non_blocking" in kwargs else False
# short-circuit to `prims.convert_element_type` when `to` is just a dtype change
if (
(copy or (kwargs.get("dtype", a.dtype) != a.dtype))
and (not non_blocking)
and ("memory_format" not in kwargs)
and ("device" not in kwargs)
and ("layout" not in kwargs)
# is_pinned issue #84925
# and ("pin_memory" not in kwargs)
):
return prims.convert_element_type(a, kwargs.get("dtype", a.dtype))
result = torch.empty_like(a, **kwargs)
# TODO: non_blocking should be handled by `copy_to`
copy_to(result, a)
return result
#
# Reduction references
#
def _reduction(
a: TensorLikeType,
prim: Callable,
*,
has_identity: bool = True,
accepts_dim_tuple: bool = True, # to handle min/argmin that accept single dim only
dims: Optional[DimsType] = None,
keepdims: bool = False,
dtype: Optional[torch.dtype] = None, # should be specified for ops that support it
out: Optional[Tensor] = None,
output_dtype_kind: REDUCTION_OUTPUT_TYPE_KIND,
) -> TensorLikeType: # it is usually SAME, but I want
# ref writers to actually think about what to put here
assert isinstance(a, TensorLike)
if a.ndim > 64:
raise RuntimeError(
f"Received a tensor with {a.ndim} dimensions, but only tensors with up to 64 dims are supported!"
)
if out is not None:
assert isinstance(out, TensorLike)
if dtype is not None:
# TODO - this is true for eager mode currently, but it's wrong behavior for complex norms
if dtype != out.dtype:
raise RuntimeError(
"dtype argument and out dtype must match in reduction"
)
if not accepts_dim_tuple:
assert dims is None or isinstance(dims, Dim)
if isinstance(dims, Dim):
dims = (dims,) # type: ignore[assignment]
dims = utils.reduction_dims(a.shape, dims)
if not has_identity:
valid_shape = a.ndim == 0 or builtins.all(a.shape[i] for i in dims)
if not valid_shape:
raise RuntimeError(
"reducing over zero-size dimension for reduction operation without identity"
)
computation_dtype, result_dtype = utils.reduction_dtypes(
a, output_dtype_kind, dtype
)
a = _maybe_convert_to_dtype(a, computation_dtype) # type: ignore[method-assign]
result = prim(a, dims)
if keepdims:
output_shape = [a.shape[i] if i not in dims else 1 for i in range(a.ndim)]
broadcast_dims = [i for i in range(a.ndim) if i not in dims]
result = prims.broadcast_in_dim(result, output_shape, broadcast_dims)
if out is not None:
assert result_dtype is not None
if dtype is not None and result_dtype != out.dtype:
raise RuntimeError(
"Expected the dtype of reduction result and out to match"
)
out = _maybe_resize_out(out, result.shape)
return _safe_copy_out(copy_from=result, copy_to=out) # type: ignore[arg-type]
if result.dtype != result_dtype and result_dtype is not None:
result = prims.convert_element_type(result, result_dtype)
return result
def _make_copy_from_view(fn):
"""
Given a view function (e.g. torch.diagonal) generates its copy variant (e.g. torch.diagonal_copy)
"""
aten_fn = getattr(aten, fn.__name__)
annotations = getattr(fn, "__annotations__", {})
fn = out_wrapper()(aten_fn)
@wraps(fn)
def _fn(*args, out=None, **kwargs):
result = fn(*args, out=out, **kwargs)
if out is not None:
return result
return pytree.tree_map(
lambda x: x.clone(memory_format=torch.contiguous_format),
result,
)
copy_name = f"{fn.__name__}_copy"
_fn.__name__ = copy_name
_fn.__annotations__.update(annotations)
register_decomposition(getattr(aten, copy_name))(_fn)
return _fn
@register_decomposition(aten.all)
@out_wrapper()
def all(
a: TensorLikeType,
dim: Optional[DimsType] = None,
keepdim: bool = False,
) -> TensorLikeType:
result = torch.logical_not(torch.any(torch.logical_not(a), dim, keepdim=keepdim))
if a.dtype == torch.uint8:
result = result.to(dtype=torch.uint8)
return result
@register_decomposition(aten.any)
@out_wrapper()
def any(
a: TensorLikeType,
dim: Optional[DimsType] = None,
keepdim: bool = False,
) -> TensorLikeType:
a_ = _maybe_convert_to_dtype(a, torch.bool)
if isinstance(dim, (list, tuple)) and len(dim) == 0:
result = a_.clone()
else:
result = a_.sum(dim=dim, keepdim=keepdim).ne(False)
# Preserves uint8 -- probably a legacy mask thing
if a.dtype is torch.uint8:
return prims.convert_element_type(result, torch.uint8)
return result
@register_decomposition([aten.sum.dim_IntList, aten.sum.IntList_out])
def sum(
a: TensorLikeType,
dim: Union[Optional[int], Optional[List[int]]] = None,
keepdim: bool = False,
*,
dtype: Optional[torch.dtype] = None,
out: Optional[Tensor] = None,
) -> TensorLikeType:
if dtype is None:
if out is not None:
dtype = out.dtype
elif utils.is_boolean_dtype(a.dtype) or utils.is_integer_dtype(a.dtype):
dtype = torch.int64
else:
dtype = a.dtype
# reduces over all dimensions if dim=() is passed
if dim == () or dim == []:
dim = None
return _reduction(
a,
prims.sum,
dims=dim,
keepdims=keepdim,
dtype=dtype,
out=out,
output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME,
)
def sum_to_size(
a: Tensor,
*shape,
) -> Tensor:
shape = utils.extract_shape_from_varargs(shape, validate=False)
torch._check(
utils.is_expandable_to(shape, a.shape),
lambda: f'sum_to_size: size "{shape}" is not expandable to size "{a.shape}"',
)
# In ATen scalar tensors are sent through sum and the result is returned as
# type promoted
if utils.is_same_shape(shape, a.shape) and len(shape) > 0:
return prims.view_of(a)
leading_dims = a.ndim - len(shape)
reduce_dims = tuple(range(leading_dims)) + tuple(
i
for i in range(leading_dims, len(shape))
if shape[i - leading_dims] == 1 and a.shape[i] != 1
)
return torch.sum(a, dim=reduce_dims, keepdim=True, dtype=None)
@register_decomposition(aten.prod)
def prod(
a: TensorLikeType,
dim: Union[Optional[int], Optional[List[int]]] = None,
keepdim: bool = False,
*,
dtype=None,
out: Optional[Tensor] = None,
) -> TensorLikeType:
if dtype is None:
if out is not None:
dtype = out.dtype
elif utils.is_boolean_dtype(a.dtype) or utils.is_integer_dtype(a.dtype):
dtype = torch.int64
else:
dtype = a.dtype
# reduces over all dimensions if dim=() is passed
if dim == () or dim == []:
dim = None
return _reduction(
a,
prims.prod,
dims=dim,
keepdims=keepdim,
dtype=dtype,
out=out,
output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME,
)
@register_decomposition(aten.amin)
def amin(
a: TensorLikeType,
dim: Optional[DimsType] = None,
keepdim: bool = False,
*,
out: Optional[Tensor] = None,
) -> TensorLikeType:
# reduces over all dimensions if dim=() is passed
if dim == () or dim == []:
dim = None
return _reduction(
a,
prims.amin,
dims=dim,
keepdims=keepdim,
dtype=None,
out=out,
has_identity=False,
output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME,
)
@register_decomposition(aten.amax)
def amax(
a: TensorLikeType,
dim: Optional[DimsType] = None,
keepdim: bool = False,
*,
out: Optional[Tensor] = None,
) -> TensorLikeType:
# reduces over all dimensions if dim=() is passed
if dim == () or dim == []:
dim = None
return _reduction(
a,
prims.amax,
dims=dim,
keepdims=keepdim,
dtype=None,
out=out,
has_identity=False,
output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.SAME,
)
def _dim_var_dispatch(dim=None, unbiased=None):
# There's the following overload of torch.var:
# var(Tensor self, bool unbiased=True) -> (Tensor, Tensor)
# We need to explicitly convert bool dims to unbiased arg
if unbiased is None and isinstance(dim, bool):
unbiased = dim
dim = None
return dim, unbiased
@register_decomposition(aten.var)
@out_wrapper()
def var(
a: TensorLikeType,
dim: Optional[DimsType] = None,
unbiased: Optional[bool] = None,
keepdim: bool = False,
*,
correction: Optional[NumberType] = None,
) -> TensorLikeType:
dim, unbiased = _dim_var_dispatch(dim, unbiased)
correction = utils.set_correction(unbiased, correction)
# reduces over all dimensions if dim=() is passed
if dim == () or dim == []:
dim = None
result = _reduction(
a,
partial(prims.var, correction=correction),
dims=dim,
keepdims=keepdim,
dtype=None,
out=None,
has_identity=True,
output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT,
)
return result
@register_decomposition(aten.std)
@out_wrapper()
def std(
a: TensorLikeType,
dim: Union[Optional[int], Optional[List[int]]] = None,
unbiased: Optional[bool] = None,
keepdim: bool = False,
*,
correction: Optional[NumberType] = None,
) -> TensorLikeType:
dim, unbiased = _dim_var_dispatch(dim, unbiased)
correction = utils.set_correction(unbiased, correction)
opmath_dtype, dtype = utils.reduction_dtypes(
a, REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT
)
a = _maybe_convert_to_dtype(a, opmath_dtype)
a_var = torch.var(a, dim, correction=correction, keepdim=keepdim)
a_std = torch.sqrt(a_var)
assert dtype is not None
return _maybe_convert_to_dtype(a_std, dtype)
@register_decomposition(aten.mean)
def mean(
a: TensorLikeType,
dim: Optional[DimsType] = None,
keepdim: bool = False,
*,
dtype=None,
out=None,
) -> TensorLikeType:
# reduces over all dimensions if dim=() is passed
if dim == () or dim == []:
dim = None
orig_dtype = dtype
if dtype is None:
dtype = a.dtype
# can't use out wrapper because of this argument
torch._check(
out is None or out.dtype == dtype,
lambda: f"Expected out tensor to have dtype {dtype}, but got {out.dtype} instead",
)
result = _reduction(
a,
prims.sum,
dims=dim,
keepdims=keepdim,
dtype=dtype,
out=None,
output_dtype_kind=REDUCTION_OUTPUT_TYPE_KIND.KEEP_PROMOTED_TYPE,
)
torch._check(
utils.is_float_dtype(dtype) or utils.is_complex_dtype(dtype),
lambda: (
f"mean(): could not infer output dtype. "
f"{'Input' if orig_dtype is None else 'Optional'} dtype must be either "
f"a floating point or complex dtype. Got: {dtype}"
),
)
if isinstance(dim, Dim):
dim = (dim,) # type: ignore[assignment]
dims = utils.reduction_dims(a.shape, dim) # type: ignore[arg-type]
nelem = 1 if a.ndim == 0 else reduce(operator.mul, (a.shape[i] for i in dims), 1)
result = true_divide(result, nelem)
result_dtype = a.dtype if dtype is None else dtype
result = _maybe_convert_to_dtype(result, result_dtype) # type: ignore[method-assign]
if out is not None:
assert isinstance(out, TensorLike)
out = _maybe_resize_out(out, result.shape)
return _safe_copy_out(copy_from=result, copy_to=out) # type: ignore[arg-type]
return result
@register_decomposition(aten.std_mean)
@out_wrapper("out0", "out1")
def std_mean(
a: TensorLikeType,
dim: Optional[DimsType] = None,
*,
unbiased: Optional[bool] = None,
keepdim: bool = False,
correction: Optional[NumberType] = None,
):
dim, unbiased = _dim_var_dispatch(dim, unbiased)
correction = utils.set_correction(unbiased, correction)
opmath_dtype, dtype = utils.reduction_dtypes(
a, REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT
)
original_dtype = a.dtype
a = _maybe_convert_to_dtype(a, opmath_dtype)
a_var, a_mean = torch.var_mean(a, dim, correction=correction, keepdim=keepdim)
a_std = torch.sqrt(a_var)
assert dtype is not None
return (
_maybe_convert_to_dtype(a_std, dtype),
_maybe_convert_to_dtype(a_mean, original_dtype),
)
@register_decomposition(aten.var_mean)
@out_wrapper("out0", "out1")
def var_mean(
a: TensorLikeType,
dim: Optional[DimsType] = None,
unbiased: Optional[bool] = None,
keepdim: bool = False,
*,
correction: Optional[NumberType] = None,
):
dim, unbiased = _dim_var_dispatch(dim, unbiased)
v = var(a, dim, unbiased, keepdim, correction=correction)
m = mean(a, dim, keepdim)
return v, m
@register_decomposition(aten.addr)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("self", "vec1", "vec2"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def addr(
self: TensorLikeType,
vec1: TensorLikeType,
vec2: TensorLikeType,
*,
beta: NumberType = 1,
alpha: NumberType = 1,
) -> TensorLikeType:
torch._check(
vec1.ndim == 1,
lambda: f"addr: Expected 1-D argument vec1, but got {vec1.ndim}-D",
)
torch._check(
vec2.ndim == 1,
lambda: f"addr: Expected 1-D argument vec2, but got {vec2.ndim}-D",
)
for arg, arg_name in ((alpha, "alpha"), (beta, "beta")):
if isinstance(arg, bool):
torch._check(
utils.is_boolean_dtype(self.dtype)
and utils.is_boolean_dtype(vec1.dtype)
and utils.is_boolean_dtype(vec2.dtype),
lambda: f"Boolean {arg_name} only supported for Boolean results.",
)
self = self.expand(vec1.shape[0], vec2.shape[0])
if utils.is_boolean_dtype(self.dtype):
# Integers are accepted for booleans
torch._check(
is_weakly_lesser_type(type(beta), int),
lambda: f"expected bool/int beta but got {type(beta)}",
)
torch._check(
is_weakly_lesser_type(type(alpha), int),
lambda: f"expected bool/int alpha but got {type(beta)}",
)
if not beta:
return torch.outer(vec1, vec2) if alpha else torch.full_like(self, False)
else:
return torch.logical_or(
self,
torch.outer(vec1, vec2) if alpha else torch.full_like(self, False),
)
else:
torch._check(
is_weakly_lesser_type(type(beta), dtype_to_type(self.dtype)),
lambda: f"cannot safely convert {type(beta)} to {self.dtype}",
)
torch._check(
is_weakly_lesser_type(type(alpha), dtype_to_type(self.dtype)),
lambda: f"cannot safely convert {type(alpha)} to {self.dtype}",
)
if beta == 0:
# This means NaNs from self are dropped if beta is zero
return alpha * torch.outer(vec1, vec2)
else:
return beta * self + alpha * torch.outer(vec1, vec2)
# CompositeImplicitAutograd - don't register decomp
def atleast_1d(
arg: Union[TensorLikeType, Sequence[TensorLikeType]], *args: TensorLikeType
) -> Union[TensorLikeType, Tuple[TensorLikeType, ...]]:
"""Reference implementation of :func:`torch.atleast_1d`."""
if not args and isinstance(arg, collections.abc.Sequence):
args_ = arg
else:
assert not isinstance(arg, collections.abc.Sequence)
args_ = (arg,) + args
res = tuple(a if a.ndim >= 1 else unsqueeze(a, 0) for a in args_)
return res if len(res) > 1 else res[0]
# Helper function with assert to avoid MyPy error
# of incompatible type passed to unsqueeze
def _unsqueeze_atleast(
at_least_fn: Callable, dim: int, arg: TensorLikeType
) -> TensorLikeType:
arg_ = at_least_fn(arg)
assert isinstance(arg_, TensorLike)
return unsqueeze(arg_, dim)
# CompositeImplicitAutograd - don't register decomp
def atleast_2d(
arg: Union[TensorLikeType, Sequence[TensorLikeType]], *args: TensorLikeType
) -> Union[TensorLikeType, Tuple[TensorLikeType, ...]]:
"""Reference implementation of :func:`torch.atleast_2d`."""
if not args and isinstance(arg, collections.abc.Sequence):
args_ = arg
else:
assert not isinstance(arg, collections.abc.Sequence)
args_ = (arg,) + args
unsqueeze_atleast_1d = partial(_unsqueeze_atleast, atleast_1d, 0)
res = tuple(a if a.ndim >= 2 else unsqueeze_atleast_1d(a) for a in args_)
return res if len(res) > 1 else res[0]
# CompositeImplicitAutograd - don't register decomp
def atleast_3d(
arg: Union[TensorLikeType, Sequence[TensorLikeType]], *args: TensorLikeType
) -> Union[TensorLikeType, Tuple[TensorLikeType, ...]]:
"""Reference implementation of :func:`torch.atleast_3d`."""
if not args and isinstance(arg, collections.abc.Sequence):
args_ = arg
else:
assert not isinstance(arg, collections.abc.Sequence)
args_ = (arg,) + args
unsqueeze_atleast_2d = partial(_unsqueeze_atleast, atleast_2d, -1)
res = tuple(a if a.ndim >= 3 else unsqueeze_atleast_2d(a) for a in args_)
return res if len(res) > 1 else res[0]
def as_strided(
a: TensorLikeType,
size: ShapeType,
stride: StrideType,
storage_offset: Optional[int] = None,
) -> TensorLikeType:
storage_offset_int = (
storage_offset if storage_offset is not None else a.storage_offset()
)
return prims.as_strided(a, size, stride, storage_offset_int)
@register_decomposition(aten.as_strided_scatter)
@out_wrapper()
def as_strided_scatter(
input: TensorLikeType,
src: TensorLikeType,
size: ShapeType,
stride: StrideType,
storage_offset: Optional[int] = None,
) -> TensorLikeType:
storage_offset_int = 0 if storage_offset is None else storage_offset
return prims.as_strided_scatter(input, src, size, stride, storage_offset_int)
def broadcast_shapes(*shapes) -> ShapeType:
return torch.Size(_broadcast_shapes(*shapes))
@aten.broadcast_tensors.default.py_impl(DispatchKey.CompositeImplicitAutograd)
@aten.broadcast_tensors.default.py_impl(DispatchKey.Meta)
def broadcast_tensors(*tensors) -> List[TensorLikeType]:
if len(tensors) == 1 and not isinstance(tensors[0], Tensor):
tensors = tensors[0]
return list(_maybe_broadcast(*tensors, preserve_cpu_scalar_tensors=False))
# CompositeImplicitAutograd - don't register decomp
def broadcast_to(a: TensorLikeType, size: ShapeType) -> TensorLikeType:
start = len(size) - len(a.shape)
dims = tuple(range(start, len(a.shape) + start))
return prims.broadcast_in_dim(a, size, dims)
@register_decomposition(aten.cat)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("tensors",),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH,
)
def cat(tensors: TensorSequenceType, dim: int = 0) -> TensorLikeType:
def cat_compute_output_memory_format(inputs):
format = None
for t in inputs:
f = utils.suggest_memory_format(t)
if f == torch.contiguous_format:
return f
if format is not None and format != f:
return torch.contiguous_format
format = f
assert format is not None
return format
if len(tensors) == 0:
msg = "cat expects at least one tensor, but received zero!"
raise ValueError(msg)
for tensor in tensors:
assert isinstance(tensor, TensorLike)
utils.check_same_device(*tensors, allow_cpu_scalar_tensors=False)
from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
# This is a bit tricky. Naively, you would expect to just pick one
# arbitrary tensor and check that all tensors match this tensor. However,
# there is legacy behavior which says that if you have a 1-D empty tensor
# (0,), this is permissible. So you can't assume that all the tensors
# have same dimensionality, and you can't assume that the first tensor is
# the correct stencil.
#
# We'll implement this in a few passes. First, we will try to infer the
# ndim of the cat output. If this ndim != 1, then we know that all ndim =
# 1 inputs must be empty, or are errors. If this ndim == 1, then life
# is easy (the legacy special case coincides with regular handling).
#
# NB: The regular implementation of cat just filters out empty inputs,
# but we do it slightly different here for better handling for unbacked
# SymInts
example = None
for i, t in enumerate(tensors):
if example is None:
if t.ndim != 1:
example = t
else:
if t.ndim != 1:
torch._check(
t.ndim == example.ndim,
lambda: "Number of dimensions of tensors must match. "
f"Expected {example.ndim}-D tensors, but got {t.ndim}-D for "
f"tensor number {i} in the list",
)
if example is None:
# example is None if everything is 1-D. If so, just arbitrarily pick
# the first one
example = tensors[0]
shape = example.shape
filtered = []
for tensor_idx, tensor in enumerate(tensors):
if len(shape) != len(tensor.shape):
assert tensor.ndim == 1 # we've already checked this above
# Don't suggest the legacy behavior in the error message
torch._check(
# NB: it is not enough to simply assert that tensor.shape[0] == 0;
# this MUST be true even under guard size oblivious.
# Effectively, we must actually know that the shape is zero,
# passing an unbacked SymInt which we will defer a runtime
# assert on won't cut it. This is a policy decision (size
# oblivious semantics say that u0 tensors never are inferred
# to be zero size, even if they must be that for the cat to go
# through), and is load bearing for our Inductor lowerings
# (which assume that size oblivious tests are OK to determine
# if a shape is permissibly zero.)
guard_size_oblivious(tensor.shape[0] == 0),
lambda: f"Number of dimensions of tensors must match. "
f"Expected {example.ndim}-D tensors, but got 1-D for "
f"tensor number {tensor_idx} in the list",
)
else:
# Remove inputs that are 1-D, zero size
if tensor.ndim == 1 and guard_size_oblivious(tensor.shape[0] == 0):
continue
# Don't bother checking size match, prims.cat will handle it
filtered.append(tensor)
memory_format = cat_compute_output_memory_format(tensors)
if len(filtered) == 0:
t = tensors[0]
# TODO: fix this to work with meta tensors
try:
# BUG? This looks like it wants to call builtins.any() but is
# actually calling .any() (in this file). Changing to builtins.any()
# causes tests to fail:
# PYTORCH_OPINFO_SAMPLE_INPUT_INDEX=4 python test/test_ops.py -k \
# TestFakeTensorCUDA.test_fake_crossref_backward_amp_cat_cuda_float32
requires_grad = bool(any(x.requires_grad for x in tensors)) # type: ignore[arg-type]
except Exception:
requires_grad = False # type: ignore[assignment]
return empty(
(0,),
dtype=t.dtype,
device=t.device,
requires_grad=requires_grad,
memory_format=memory_format,
)
dim = utils.canonicalize_dim(filtered[0].ndim, dim)
utils.validate_idx(filtered[0].ndim, dim)
return prims.cat(filtered, dim).clone(memory_format=memory_format)
# CompositeImplicitAutograd - don't register decomp
@out_wrapper()
def column_stack(tensors: TensorSequenceType) -> TensorLikeType:
aligned_tensors = tuple(
x if x.ndim > 1 else x.reshape((x.numel(), 1)) for x in tensors
)
return cat(aligned_tensors, 1)
def conj(input: TensorLikeType) -> TensorLikeType:
if not utils.is_complex_dtype(input.dtype):
return input
if input.is_sparse:
return torch.conj_physical(input)
return prims.conj(input)
# This replicates at::constant_pad_nd, defined in ATen/native/PadNd.cpp
@register_decomposition(aten.constant_pad_nd)
@out_wrapper()
def constant_pad_nd(
input: TensorLikeType, pad: List[int], value: NumberType = 0
) -> TensorLikeType:
torch._check(
len(pad) % 2 == 0,
lambda: f"Length of pad must be even but instead it equals {len(pad)}",
)
input_sizes = input.shape
l_inp = len(input_sizes)
l_pad = len(pad) // 2
l_diff = l_inp - l_pad
torch._check(
l_inp >= l_pad,
lambda: "Length of pad should be no more than twice the number of "
f"dimensions of the input. Pad length is {len(pad)} while the input has "
f"{l_inp} dimensions.",
)
c_input = input
for i in range(l_diff, l_inp):
pad_idx = 2 * (l_inp - i - 1)
if pad[pad_idx] < 0:
c_input = c_input.narrow(i, -pad[pad_idx], c_input.shape[i] + pad[pad_idx])
if pad[pad_idx + 1] < 0:
c_input = c_input.narrow(i, 0, c_input.shape[i] + pad[pad_idx + 1])
# If all the pads are negative we can return the result.
# Avoid early exiting if all pads = 0 to prevent specialization on export.
# During export, raw if statements are specialized on the input, meaning
# that we lose a branch depending on the example input used to export.
# Here, this is either the case where all pads = 0, or the case where at
# least one pad > 0 and the rest are >= 0.
# Avoiding the early exit when all pads = 0 ensures we can export
# constant_pad_nd for cases when all pads >= 0.
# Note: if any pads are negative, this code specializes due to the if statements above.
if builtins.all(p < 0 for p in pad):
return c_input.clone()
new_shape = list(input_sizes[:l_diff])
for i in range(l_pad):
pad_idx = len(pad) - ((i + 1) * 2)
new_dim = input_sizes[l_diff + i] + pad[pad_idx] + pad[pad_idx + 1]
torch._check(
new_dim > 0,
lambda: f"The input size {input_sizes[l_diff + i]}, plus negative padding "
f"{pad[pad_idx]} and {pad[pad_idx + 1]} resulted in a negative output size, "
f"which is invalid. Check dimension {l_diff + i} of your input.",
)
new_shape.append(new_dim)
memory_format = utils.suggest_memory_format(input)
output = torch.empty(
new_shape,
dtype=input.dtype,
device=input.device,
requires_grad=input.requires_grad,
memory_format=memory_format,
)
if value == 0 and input.dtype == torch.bool:
value = False
# torch.fill isn't typed to allow complex values
output = torch.fill(output, value) # type: ignore[arg-type]
c_output = output
for i in range(l_diff, l_inp):
pad_idx = 2 * (l_inp - i - 1)
if pad[pad_idx] >= 0:
c_output = c_output.narrow(
i, pad[pad_idx], c_output.shape[i] - pad[pad_idx]
)
if pad[pad_idx + 1] >= 0:
c_output = c_output.narrow(i, 0, c_output.shape[i] - pad[pad_idx + 1])
prims.copy_to(c_output, c_input)
return output
def contiguous(
a: Tensor, *, memory_format: torch.memory_format = torch.contiguous_format
) -> Tensor:
torch._check(
memory_format != torch.preserve_format,
lambda: "preserve memory format is unsupported by the contiguous operator",
)
if utils.is_contiguous_for_memory_format(a, memory_format=memory_format):
return a
return torch.clone(a, memory_format=memory_format)
@out_wrapper()
def dstack(tensors: TensorSequenceType) -> TensorLikeType:
torch._check(len(tensors) > 0, lambda: "dstack expects a non-empty TensorList")
aligned_tensors = atleast_3d(*tensors)
return cat(aligned_tensors, 2)
@register_decomposition(aten.expand)
def expand(a: Tensor, *shape) -> Tensor:
from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
# NOTE: cannot use utils.extract_shape_from_varargs here
# because that also validates the shape, but the shape
# given to expand may be "invalid"
if len(shape) == 1 and isinstance(shape[0], Sequence):
shape = tuple(shape[0])
torch._check(
len(shape) >= len(a.shape),
lambda: "expand: the requested shape has too few dimensions!",
)
offset = len(shape) - len(a.shape)
shape_ = list(shape)
for idx, x in enumerate(a.shape):
offset_idx = idx + offset
requested_length = shape[offset_idx]
torch._check(
guard_size_oblivious(requested_length == x)
or guard_size_oblivious(x == 1)
or requested_length == -1,
lambda: f"expand: attempting to expand a dimension of length {x}!",
)
shape_[offset_idx] = requested_length if requested_length != -1 else x
# At this point shape must be valid
utils.validate_shape(shape_)
return prims.broadcast_in_dim(
a, shape_, tuple(range(offset, len(a.shape) + offset))
)
# CompositeImplicitAutograd - don't register decomp
def expand_as(a: Tensor, b: Tensor) -> Tensor:
return a.expand(b.shape)
def chunk(a: TensorLikeType, chunks: int, dim: int = 0) -> Tuple[TensorLikeType, ...]:
if chunks <= 0:
msg = f"Expected at least one chunk, but got {chunks}!"
raise ValueError(msg)
dim = utils.canonicalize_dim(a.ndim, dim)
length = a.shape[dim]
chunk_size = math.ceil(length / chunks)
full_chunks = math.floor(length / chunk_size)
tail_chunk_size = length % chunk_size
result = [narrow(a, dim, i * chunk_size, chunk_size) for i in range(full_chunks)]
if tail_chunk_size != 0:
result.append(narrow(a, dim, full_chunks * chunk_size, tail_chunk_size))
return tuple(result)
# Note: flatten, unlike other shape operators, returns the input tensor on a no-op (unless
# a 0D tensor is flattened, in which case it's returned in 1D)
# CompositeImplicitAutograd - don't register decomp
def flatten(a: TensorLikeType, start_dim: int = 0, end_dim: int = -1) -> TensorLikeType:
start_dim = utils.canonicalize_dim(a.ndim, start_dim)
end_dim = utils.canonicalize_dim(a.ndim, end_dim)
# Short-circuits on no-op
if start_dim == end_dim and a.ndim != 0:
return a
# Tries to take a view
# TODO: we could look at directing collapse_view to skip its meta function here (unsafe_collapse_view)
new_shape, new_strides = prims._collapse_view_helper(a, start_dim, end_dim)
if new_shape is not None:
return prims.collapse_view(a, start_dim, end_dim)
# Makes a copy if it can't make a view
return prims.collapse(a, start_dim, end_dim)
@register_decomposition(aten.flip)
@out_wrapper()
def flip(a: TensorLikeType, dims: DimsSequenceType) -> TensorLikeType:
if not isinstance(dims, tuple) and not isinstance(dims, list):
raise ValueError("dims has to be a sequence of ints")
dims = utils.canonicalize_dims(a.ndim, dims) # type: ignore[assignment]
utils.validate_no_repeating_dims(dims)
return prims.rev(a, dims)
# CompositeImplicitAutograd - don't register decomp
def fliplr(a: TensorLikeType) -> TensorLikeType:
if a.ndim < 2:
raise RuntimeError("Input must be >= 2-d.")
return flip(a, (1,))
# CompositeImplicitAutograd - don't register decomp
def flipud(a: TensorLikeType) -> TensorLikeType:
if a.ndim < 1:
raise RuntimeError("Input must be >= 1-d.")
return flip(a, (0,))
# CompositeImplicitAutograd - don't register decomp
def narrow(
a: TensorLikeType, dim: int, start: Union[int, TensorLikeType], length: int
) -> TensorLikeType:
# Supports Tensor overload that was added for XLA:
# https://github.com/pytorch/pytorch/issues/31558
if isinstance(start, TensorLike):
torch._check(
start.dim() == 0 and utils.is_integer_dtype(start.dtype),
lambda: "start must be an 0-dim integral Tensor.",
)
start = start.item() # type: ignore[assignment]
start = cast(int, start)
torch._check(a.dim() > 0, lambda: "narrow() cannot be applied to a 0-dim tensor.")
torch._check(length >= 0, lambda: "narrow(): length must be non-negative.")
dim = utils.canonicalize_dim(a.ndim, dim)
dim_length = a.size(dim)
torch._check_with(
IndexError,
-dim_length <= start and start <= dim_length,
lambda: f"start out of range (expected to be in range of [{-dim_length}, {dim_length}], but got {start})",
)
if start < 0:
start = start + dim_length
torch._check(
start <= dim_length - length,
lambda: f"start ({start}) + length ({length}) exceeds dimension size ({dim_length}).",
)
new_shape = list(a.shape)
new_shape[dim] = length
return a.as_strided(
new_shape, a.stride(), a.storage_offset() + a.stride(dim) * start
)
def _normalize(
a: Tensor, norm_dims: DimsType, eps: float
) -> Tuple[Tensor, Tensor, Tensor]:
"""Computes mean and 1/std of a tensor along norm_dims.
Used as a helper function for normalization layers.
Args:
a (Tensor): input tensor
norm_dims (DimsType): dimensions to normalize over
eps (float): epsilon for numerical stability
Returns:
out (Tensor): normalized tensor.
mean (Tensor): mean of the tensor along norm_dims.
rstd (Tensor): 1/std of the tensor along norm_dims.
"""
norm_dims = utils.canonicalize_dims(a.ndim, norm_dims)
computation_dtype = utils.get_computation_dtype(a.dtype)
a_acc = _maybe_convert_to_dtype(a, computation_dtype)
assert isinstance(a_acc, TensorLike) # to avoid mypy error for var_mean
biased_var, mean = torch.var_mean(
a_acc, dim=norm_dims, unbiased=False, keepdim=True
)
rstd = torch.rsqrt(biased_var + eps)
out = (a_acc - mean) * rstd
return out, mean, rstd
# add all specified dimensions
def _unsqueeze_multiple(x: TensorLikeType, dimensions: List[int]) -> TensorLikeType:
for dim in sorted(dimensions):
x = torch.unsqueeze(x, dim)
return x
@register_decomposition(aten.native_group_norm.default)
def native_group_norm(
input: Tensor,
weight: Optional[Tensor],
bias: Optional[Tensor],
batch_size: int,
num_channels: int,
flattened_inner_size: int,
num_groups: int,
eps: float,
) -> Tuple[Tensor, Tensor, Tensor]:
torch._check(
input.ndim >= 2,
lambda: f"Expected at least 2 dimensions for input tensor but received {input.ndim}",
)
torch._check(
num_channels % num_groups == 0,
lambda: "Expected number of channels in input to be divisible by num_groups, "
+ f"but got input of shape {input.shape} and num_groups = {num_groups}",
)
# num_channels / num_groups and flattened inner dimension are the reduction axes
reduction_dims = [2, 3]
input_reshaped = torch.reshape(
input,
[batch_size, num_groups, num_channels // num_groups, flattened_inner_size],
)
out, mean, rstd = _normalize(input_reshaped, reduction_dims, eps)
out = out.view(input.shape)
broadcast_dims = [0] + list(range(2, input.ndim))
unsqueeze_bias = None
if bias is not None:
unsqueeze_bias = _unsqueeze_multiple(bias, broadcast_dims)
unsqueeze_weight = None
if weight is not None:
unsqueeze_weight = _unsqueeze_multiple(weight, broadcast_dims)
if unsqueeze_weight is not None:
out = out * unsqueeze_weight
if unsqueeze_bias is not None:
out = out + unsqueeze_bias
out = _maybe_convert_to_dtype(out, input.dtype) # type: ignore[assignment]
mean = _maybe_convert_to_dtype(mean, input.dtype) # type: ignore[assignment]
rstd = _maybe_convert_to_dtype(rstd, input.dtype) # type: ignore[assignment]
# remove broadcast dimensions from mean and rstd
mean = torch.squeeze(mean, reduction_dims)
rstd = torch.squeeze(rstd, reduction_dims)
return (out, mean, rstd)
@register_decomposition(aten.native_layer_norm)
@out_wrapper("out0", "out1", "out2")
def native_layer_norm(
input: Tensor,
normalized_shape: ShapeType,
weight: Optional[Tensor],
bias: Optional[Tensor],
eps: float,
) -> Tuple[Tensor, Tensor, Tensor]:
normalized_ndim = len(normalized_shape)
torch._check(
normalized_ndim >= 1,
lambda: "Expected normalized_shape to be at least 1-dimensional, i.e., "
+ "containing at least one element, but got normalized_shape = "
+ str(normalized_shape),
)
# torch.Size([1, 2, 3]) == [1, 2, 3] evaluates to False
# while torch.Size([1, 2, 3]) == (1, 2, 3) is True
# therefore we use tuple(normalized_shape)
torch._check(
weight is None or weight.shape == tuple(normalized_shape),
lambda: "Expected weight to be of same shape as normalized_shape, but got "
+ "weight of shape "
+ str(weight.shape) # type: ignore[union-attr]
+ " and normalized_shape = "
+ str(normalized_shape),
)
torch._check(
bias is None or bias.shape == tuple(normalized_shape),
lambda: "Expected bias to be of same shape as normalized_shape, but got "
+ "bias of shape "
+ str(bias.shape) # type: ignore[union-attr]
+ " and normalized_shape = "
+ str(normalized_shape),
)
torch._check(
input.ndim >= normalized_ndim
and input.shape[(input.ndim - normalized_ndim) :] == tuple(normalized_shape),
lambda: "Given normalized_shape="
+ str(normalized_shape)
+ ", expected input with shape "
+ str(normalized_shape)
+ ", but got input of size "
+ str(input.shape),
)
input = input.contiguous()
if weight is not None:
weight = weight.contiguous()
if bias is not None:
bias = bias.contiguous()
axis = input.ndim - normalized_ndim
reduction_dims = list(range(axis, input.ndim))
out, mean, rstd = _normalize(input, reduction_dims, eps)
if weight is None and bias is not None:
out = out + bias
elif weight is not None and bias is None:
out = out * weight
elif weight is not None and bias is not None:
out = out * weight + bias
out = _maybe_convert_to_dtype(out, input.dtype) # type: ignore[assignment]
if input.device.type in ["cpu", "mtia"]:
mean = _maybe_convert_to_dtype(mean, input.dtype) # type: ignore[assignment]
rstd = _maybe_convert_to_dtype(rstd, input.dtype) # type: ignore[assignment]
return (out, mean, rstd)
@torch._subclasses.fake_impls.register_op_impl(aten.native_layer_norm.default)
def native_layer_norm_fake(fake_mode, func, *args, **kwargs):
return native_layer_norm(*args)
# TODO: Adding this as a meta function causes functorch tests to fail when compiled with debug mode.
# test/test_eager_transforms.py::TestFunctionalizeCPU::test_functionalize_fx_transpose_simple_cpu
@register_decomposition(aten.permute)
def permute(a: TensorLikeType, *dims) -> TensorLikeType:
_permutation = utils.canonicalize_dims(
a.ndim, utils.extract_dims_from_varargs(dims)
)
return prims.transpose(a, _permutation)
@register_decomposition(aten.renorm)
@out_wrapper()
def renorm(
input: TensorLikeType, p: RealNumberType, dim: int, maxnorm: RealNumberType
) -> TensorLikeType:
torch._check(not isinstance(p, complex), lambda: "renorm: p must be real-valued")
torch._check(p > 0, lambda: "renorm: non-positive norm not supported")
torch._check(
not isinstance(maxnorm, complex), lambda: "renorm: maxnorm must be real-valued"
)
torch._check(
maxnorm >= 0, lambda: f"renorm: expected maxnorm to be >= 0 but got {maxnorm}"
)
ndim = input.ndim
torch._check(
ndim > 1,
lambda: f"renorm: input needs at least 2 dimensions, got {ndim} dimensions",
)
dim = utils.canonicalize_dim(ndim, dim)
reduce_dims = list(range(ndim))
del reduce_dims[dim]
# For half and bfloat16, calculate norm in float precision then cast
# normalization factor to half
acc_type = utils.get_computation_dtype(input.dtype)
if acc_type != input.dtype:
norm = torch.linalg.vector_norm(
input, p, reduce_dims, keepdim=True, dtype=acc_type
)
else:
norm = torch.linalg.vector_norm(input, p, reduce_dims, keepdim=True)
eps = 1e-7
norm_factor = torch.where(norm > maxnorm, maxnorm / (norm + eps), 1.0)
if acc_type != input.dtype:
norm_factor = prims.convert_element_type(norm_factor, input.dtype)
return (input * norm_factor).contiguous()
# CompositeImplicitAutograd - don't register decomp
@aten.stft.center.py_impl(DispatchKey.CompositeImplicitAutograd)
def stft(
input: Tensor,
n_fft: int,
hop_length: Optional[int] = None,
win_length: Optional[int] = None,
window: Optional[Tensor] = None,
center: bool = True,
pad_mode: str = "reflect",
normalized: bool = False,
onesided: Optional[bool] = None,
return_complex: Optional[bool] = None,
) -> Tensor:
torch._check(
window is None or window.device == input.device,
lambda: (
f"stft input and window must be on the same device but got self on {input.device}"
+ f" and window on {window.device}" # type: ignore[union-attr]
),
)
hop_length_ = hop_length if hop_length is not None else n_fft // 4
win_length_ = win_length if win_length is not None else n_fft
if return_complex is None:
return_complex_ = input.is_complex() or (
window is not None and utils.is_complex_dtype(window.dtype)
)
torch._check(
return_complex_,
(
"stft requires the return_complex parameter be given for real inputs, "
+ "and will further require that return_complex=True in a future PyTorch release."
),
)
else:
return_complex_ = return_complex
torch._check(
utils.is_float_dtype(input.dtype) or utils.is_complex_dtype(input.dtype),
lambda: "stft expected a tensor of floating point or complex values",
)
torch._check(1 <= input.ndim <= 2, lambda: "stft expected a 1D or 2D tensor")
original_ndim = input.ndim
if original_ndim == 1:
input = input.unsqueeze(0)
if center:
extra_dims = 3 - input.ndim
pad_amount = n_fft // 2
extended_shape = [*itertools.repeat(1, extra_dims), *input.shape]
input = aten.pad(input.view(extended_shape), [pad_amount, pad_amount], pad_mode)
input = input.view(input.size()[extra_dims:])
batch = input.size(0)
length = input.size(1)
torch._check(
0 < n_fft <= length,
lambda: f"stft expected 0 < n_fft <= {length}, but got n_fft={n_fft}",
)
torch._check(
hop_length_ > 0,
lambda: f"stft expected hop_length > 0 but got hop_length={hop_length_}",
)
torch._check(
0 < win_length_ <= n_fft,
lambda: f"stft expected 0 < win_length <= n_fft but got win_length={win_length_}",
)
torch._check(
window is None or window.shape == (win_length_,),
lambda: (
f"expected a 1D window tensor of size equal to win_length={win_length_}, "
+ f"but got window with size {window.shape}" # type: ignore[union-attr]
),
)
if win_length_ < n_fft:
if window is None:
window = torch.ones(win_length_, dtype=input.dtype, device=input.device)
left = (n_fft - win_length_) // 2
window = aten.constant_pad_nd(window, [left, n_fft - win_length_ - left])
input = input.unfold(dimension=-1, size=n_fft, step=hop_length_)
if window is not None:
input = input * window
complex_fft = utils.is_complex_dtype(input.dtype)
onesided = onesided if onesided is not None else not complex_fft
norm = "ortho" if normalized else None
if onesided:
torch._check(
not complex_fft,
lambda: "Cannot have onesided output if window or input is complex",
)
out = torch.fft.rfft(input, dim=-1, norm=norm)
else:
out = torch.fft.fft(input, dim=-1, norm=norm)
out.transpose_(1, 2)
if original_ndim == 1:
out = out.squeeze_(0)
return out if return_complex_ else torch.view_as_real(out)
# CompositeImplicitAutograd - don't register decomp
@aten.istft.default.py_impl(DispatchKey.CompositeImplicitAutograd)
def istft(
input: Tensor,
n_fft: int,
hop_length: Optional[int] = None,
win_length: Optional[int] = None,
window: Optional[Tensor] = None,
center: bool = True,
normalized: bool = False,
onesided: Optional[bool] = None,
length: Optional[int] = None,
return_complex=False,
) -> Tensor:
torch._check(
window is None or window.device == input.device,
lambda: (
f"istft input and window must be on the same device but got self on {input.device}"
+ f" and window on {window.device}" # type: ignore[union-attr]
),
)
hop_length_ = hop_length if hop_length is not None else n_fft // 4
win_length_ = win_length if win_length is not None else n_fft
torch._check(
utils.is_complex_dtype(input.dtype),
lambda: (
"istft input and window must be on the same device but got self on "
+ f"{input.device} and window on {window.device}" # type: ignore[union-attr]
),
)
n_frames = input.size(-1)
fft_size = input.size(-2)
expected_output_signal_len = n_fft + hop_length_ * (n_frames - 1)
torch._check(input.numel() > 0, lambda: "istft input tensor cannot be empty")
torch._check(
2 <= input.ndim <= 3,
lambda: f"istft expected a tensor with 2 or 3 dimensions, but got {input.ndim}",
)
onesided_ = onesided if onesided is not None else fft_size != n_fft
if onesided_:
torch._check(
n_fft // 2 + 1 == fft_size,
lambda: (
"istft expected the frequency dimension (3rd to the last) of the input tensor "
+ "to match n_fft / 2 + 1 when onesided=True, but got {fft_size}"
),
)
else:
torch._check(
n_fft == fft_size,
lambda: (
"istft expected the frequency dimension (3rd to the last) of the input tensor "
+ "to match n_fft when onesided=False, but got {fft_size}",
),
)
torch._check(
0 < hop_length_ <= win_length_,
lambda: "istft expected 0 < hop_length <= win_length",
)
torch._check(
0 < win_length_ <= n_fft, lambda: "istft expected 0 < win_length <= n_fft"
)
torch._check(
window is None or window.shape == (win_length_,),
lambda: "Invalid window shape. window has to be 1D and length of `win_length`",
)
if window is None:
real_dtype = utils.corresponding_real_dtype(input.dtype)
window_ = torch.ones(win_length_, dtype=real_dtype, device=input.device)
else:
window_ = window
if win_length_ != n_fft:
left = (n_fft - win_length_) // 2
window_ = aten.constant_pad_nd(window_, (left, n_fft - win_length_ - left), 0)
original_ndim = input.ndim
if input.ndim == 2:
input = input.unsqueeze(0)
input = input.transpose(1, 2)
norm = "ortho" if normalized else None
if return_complex:
torch._check(
not onesided_,
lambda: "cannot have onesided output if window or input is complex",
)
input = torch.fft.ifft(input, dim=-1, norm=norm)
else:
torch._check(
window is None or not utils.is_complex_dtype(window.dtype),
lambda: "Complex windows are incompatible with return_complex=False",
)
if not onesided_:
input = input.narrow(dim=-1, start=0, length=n_fft // 2 + 1)
input = torch.fft.irfft(input, dim=-1, norm=norm)
assert input.size(2) == n_fft
y_tmp = input * window_.view([1, 1, n_fft])
y = aten.unfold_backward(
y_tmp,
input_sizes=(y_tmp.size(0), expected_output_signal_len),
dim=1,
size=n_fft,
step=hop_length_,
)
window_envelop = aten.unfold_backward(
window_.pow(2).expand((1, n_frames, n_fft)),
input_sizes=(y_tmp.size(0), expected_output_signal_len),
dim=1,
size=n_fft,
step=hop_length_,
)
assert expected_output_signal_len == y.size(1)
assert expected_output_signal_len == window_envelop.size(1)
start = n_fft // 2 if center else 0
if length is not None:
end = start + length
elif center:
end = expected_output_signal_len - n_fft // 2
else:
end = expected_output_signal_len
length = max(0, end - start)
y = y.narrow(dim=1, start=start, length=length)
window_envelop = window_envelop.narrow(dim=1, start=start, length=length)
y = y / window_envelop
if original_ndim == 2:
y = y.squeeze(0)
if end > expected_output_signal_len:
warnings.warn(
"The length of signal is shorter than the length parameter. Result is being "
+ "padded with zeros in the tail. Please check your center and hop_length settings"
)
y = aten.constant_pad_nd(y, (0, end - expected_output_signal_len), 0)
return y
# Get the new shape and stride after applying unfold to an input tensor
def _get_unfold_shape_stride(
a_shape: ShapeType, a_stride: StrideType, dimension: int, size: int, step: int
):
a_ndim = len(a_shape)
dim = utils.canonicalize_dim(a_ndim, dimension, wrap_scalar=True)
max_size = 1 if a_ndim == 0 else a_shape[dim]
last_stride = 1 if a_ndim == 0 else a_stride[dim]
torch._check(
size <= max_size,
lambda: f"Maximum size for tensor at dimension {dim} is {max_size} but size is {size}",
)
torch._check(
step > 0,
lambda: f"Step is {step} but must be > 0",
)
shape = list(a_shape)
strides = list(a_stride)
shape.append(size)
strides.append(last_stride)
if dim < a_ndim:
shape[dim] = (shape[dim] - size) // step + 1
strides[dim] *= step
return shape, strides
@register_decomposition(aten.repeat)
@out_wrapper()
def repeat(a: Tensor, *repeat_shape) -> Tensor:
repeat_shape = utils.extract_shape_from_varargs(repeat_shape, validate=False)
torch._check(
len(repeat_shape) >= len(a.shape),
lambda: "repeat: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor",
)
if len(repeat_shape) == 0:
return torch.clone(a)
num_new_dimensions = len(repeat_shape) - a.ndim
padded_shape = [1] * num_new_dimensions
for dim_size in a.shape:
padded_shape.append(dim_size)
target_shape = tuple(
padded_size * repeat_size
for padded_size, repeat_size in zip(padded_shape, repeat_shape)
)
# return an empty tensor if one of the repeat_shape dimensions is zero
if 0 in repeat_shape:
return torch.empty(
target_shape,
dtype=a.dtype,
device=a.device,
requires_grad=a.requires_grad,
memory_format=utils.suggest_memory_format(a),
)
urtensor_shape = target_shape
urtensor_stride = utils.make_contiguous_strides_for(target_shape)
for dim, dim_size in enumerate(padded_shape):
# repeat each dimension by using unfold_copy operation
urtensor_shape, urtensor_stride = _get_unfold_shape_stride(
urtensor_shape, urtensor_stride, dim, dim_size, max(dim_size, 1)
)
# derive permute order by sorting urtensor strides
enumerated_stride = list(enumerate(urtensor_stride))
enumerated_stride.sort(key=operator.itemgetter(1), reverse=True)
permute_order, sorted_stride = zip(*enumerated_stride)
# add new and expand dimensions according to urtensor
repeat_xtensor = a.expand(urtensor_shape)
# clone tensor to concretize expanded dimensions
cloned_result = torch.clone(repeat_xtensor)
# transpose axis so strides are in sorted order
permuted_result = cloned_result.permute(permute_order)
# reshape to get contiguous tensor with correct target shape
return permuted_result.reshape(target_shape)
def _reshape_view_helper(a: TensorLikeType, *shape, allow_copy: bool) -> TensorLikeType:
from torch.fx.experimental.symbolic_shapes import guard_size_oblivious, sym_eq
# Creates a valid shape
shape = utils.extract_shape_from_varargs(shape, validate=False)
# Reshape may be given a shape with a -1 length
# This indicates that the dimension's length should be inferred
shape = utils.infer_size(shape, a.numel())
# Special-cases tensors with no elements
if guard_size_oblivious(a.numel() == 0):
return as_strided(a, shape, utils.make_contiguous_strides_for(shape))
# Special-cases reshaping zero dim tensors
if a.ndim == 0:
_a = a
for length in shape:
assert length == 1
_a = unsqueeze(_a, -1)
if _a is a:
return prims.view_of(a)
else:
return _a
# Special-cases reshaping to zero dim tensors
if len(shape) == 0:
_a = a
for length in a.shape:
assert length == 1
_a = squeeze(_a, -1)
if _a is a:
return prims.view_of(a)
else:
return _a
if a.is_contiguous():
# Special-cases for nd_to_1d
if len(shape) == 1 and a.ndim > 1:
return torch.as_strided(a, [a.numel()], [1])
# Special-cases for 1d_to_2d
if len(shape) == 2 and a.ndim == 1:
dim0 = shape[0]
dim1 = shape[1]
return torch.as_strided(a, [dim0, dim1], [dim1, 1])
# Handles general case: a 1+D tensor reshaped into a distinct 1+D shape
# NOTE [Reshape Algorithm]
# This algorithm works by attempting to greedily construct the desired dimensions in
# the output shape, left to right. It does this by, conceptually, accumulating
# dimensions of the original tensor, also left to right, until the dimension
# can be constructed using prims.split_dim.
# The algorithm also has special handling for tail squeezes/unsqueezes, like
# if a reshape from (5, 5) to (5, 5, 1) or vice versa.
#
# This algorithm does not flatten the original tensor and then split dims as appropriate
# because that would create copies more often than this algorithm. flatten is the only
# operation below which can create a view or a copy, and while it prefers creating
# views it may sometimes create a copy if the tensor's strides do not permit a view.
# As a result, this algorithm tries to minimize flattening.
#
# Note that a better version of this algorithm may exist. Regions which could be
# flattened without creating a copy can be identified in advance, and that might
# allow fewer flatten calls or faster short-circuiting to make a copy.
idx = 0
a_ = a
for length in shape:
# Handles tail unsqueezes
if idx >= a_.ndim:
assert length == 1
last_dim = a_.ndim - 1
# NOTE: using split_dim instead of unsqueeze may seem silly here,
# but it's necessary to get the strides correct
a_ = prims.split_dim(a_, last_dim, a_.shape[last_dim])
idx = idx + 1
continue
# Skips dimensions that are already the correct length
if guard_size_oblivious(length == a_.shape[idx]):
idx = idx + 1
continue
# Gathers enough original dimensions such that this new dimension can be created
# Note that this accumulation will terminate because we've verified a and the shape
# specify the same number of elements above
accum = a_.shape[idx]
end = idx
while guard_size_oblivious(accum % length != 0):
end = end + 1
accum = accum * a_.shape[end]
if end != idx:
# NOTE: in this case multiple dimensions must be flatten to create the desired dimension
# This flattening is why reshape sometimes creates a copy -- because flattening
# may return a view of a copy
# Checks if collapse can be a view and short-circuits to copying reshape if it can't
new_shape, new_strides = prims._collapse_view_helper(a_, idx, end)
if new_shape is None:
if allow_copy:
return prims.reshape(a, shape)
msg = f"Cannot view a tensor with shape {a.shape} and strides {a.stride()} as a tensor with shape {shape}!"
raise ValueError(msg)
a_ = flatten(a_, idx, end)
# Splits the (possibly flattened) dimension to create the desired dim length
if guard_size_oblivious(accum != length):
a_ = prims.split_dim(a_, idx, length)
idx = idx + 1
# Squeezes tail
while idx < a_.ndim:
torch._check(
a_.shape[idx] == 1,
lambda: f"a.size({idx}) expected to be 1 but got {a_.shape[idx]}",
)
a_ = squeeze(a_, idx)
if a_ is a:
return prims.view_of(a)
else:
return a_
# CompositeImplicitAutograd - don't register decomp
# NOTE: shape is a vararg because Tensor.reshape can be called with as
# Tensor.reshape(a, b, c) or Tensor.reshape((a, b, c)) Function call
# torch.reshape doesn't support unpacked shapes
def reshape(a: TensorLikeType, *shape: ShapeType) -> TensorLikeType:
return _reshape_view_helper(a, *shape, allow_copy=True)
# CompositeImplicitAutograd - don't register decomp
def reshape_as(self: TensorLikeType, other: TensorLikeType) -> TensorLikeType:
return self.reshape(other.size())
@register_decomposition(aten.roll)
@out_wrapper()
def roll(a: TensorLikeType, shifts: DimsType, dims: DimsType = ()) -> TensorLikeType:
"""Reference implementation of :func:`torch.roll`."""
dims = utils.canonicalize_dims(a.ndim, dims)
# ATen specifies int[1] type for shifts and dims which expands integers to tuples of length 1
if not isinstance(shifts, Iterable):
shifts = (shifts,)
if not isinstance(dims, Iterable):
dims = (dims,)
# Avoid modulo by zero
if a.numel() == 0:
# Keeping this as ref for now as FakeTensor runs into some issues with complex tensors
return a.clone()
if a.dim() == 0 and len(dims) > 0:
raise IndexError(
f"Dimension specified as {dims[0]} but tensor has no dimensions"
)
len_shifts = len(shifts)
len_dims = len(dims)
if len_shifts != 1 or len_dims != 1:
if len_shifts == 0:
raise RuntimeError("`shifts` required")
# Takes care of the case when dims is not specified (default)
# By default, the tensor is flattened before shifting, after which the original shape is restored
if len_dims == 0 and len_shifts == 1:
return torch.roll(torch.flatten(a), shifts, 0).view(a.shape)
if len_shifts != len_dims:
raise RuntimeError(
f"shifts and dimensions must align. shifts: {len_shifts}, dims: {len_dims}"
)
assert len_dims > 1
tail_shifts = shifts[1:]
tail_dims = dims[1:]
first_dim_rolled = torch.roll(a, (shifts[0],), dims[0])
return torch.roll(first_dim_rolled, tail_shifts, tail_dims)
# This path is taken when only one dimension is rolled
# For example to get `first_dim_rolled` above
dim = dims[0]
size = a.shape[dim]
start = (size - shifts[0]) % size
idx = torch.arange(size, device=a.device)
return a.index_select(dim, torch.fmod(start + idx, size))
@register_decomposition(aten.rot90)
@out_wrapper()
def rot90(
a: TensorLikeType, k: int = 1, dims: DimsSequenceType = (0, 1)
) -> TensorLikeType:
"""Reference implementation of :func:`torch.rot90`."""
if len(dims) != 2:
raise RuntimeError(
f"expected total rotation dims == 2, but got dims = {len(dims)}"
)
if a.ndim < 2:
raise RuntimeError(f"expected total dims >= 2, but got total dims = {a.ndim}")
# Do this after the initial checks to be compatible with the behavior in
# core.
dims = utils.canonicalize_dims(a.ndim, dims)
if dims[0] == dims[1]:
raise RuntimeError(
f"expected rotation dims to be different, but got dim0 = {dims[0]} and dim1 = {dims[1]}"
)
k = k % 4 # Rotation direction is from the second towards the first axis for k < 0
if k == 1:
return torch.transpose(torch.flip(a, (dims[1],)), dims[0], dims[1])
elif k == 2:
return torch.flip(a, dims)
elif k == 3:
return torch.transpose(torch.flip(a, (dims[0],)), dims[0], dims[1])
else:
return a.clone(memory_format=torch.contiguous_format)
def _check_stack_inputs(tensors: TensorSequenceType) -> None:
entry_shape = tensors[0].shape
for i in range(1, len(tensors)):
assert tensors[i].shape == entry_shape, (
f"stack expects each tensor to be equal size, but got {entry_shape} at entry 0 "
f"and {tensors[i].shape} at entry {i}"
)
@register_decomposition(aten.stack)
@out_wrapper()
def stack(tensors: TensorSequenceType, dim: int = 0) -> TensorLikeType:
assert len(tensors) > 0, "stack expects a non-empty TensorList"
wrapped_dim = utils.canonicalize_dim(tensors[0].ndim + 1, dim)
# Refs need sparse support to check other condition
if wrapped_dim < tensors[0].ndim: # and not tensors[0].is_sparse:
_check_stack_inputs(tensors)
result_sizes = list(tensors[0].shape)
result_sizes.insert(wrapped_dim, len(tensors))
out = torch.cat(tensors, wrapped_dim)
return out.view(result_sizes)
# If dim == tensors[0].ndim, view cannot efficiently handle it
return torch.cat([t.unsqueeze(wrapped_dim) for t in tensors], dim)
# CompositeImplicitAutograd - don't register decomp
@out_wrapper()
def softmax(
a: TensorLikeType,
dim: int,
dtype: Optional[torch.dtype] = None,
) -> TensorLikeType:
result_dtype = dtype or a.dtype
computation_dtype = utils.get_computation_dtype(result_dtype)
a_ = _maybe_convert_to_dtype(a, computation_dtype)
if a.numel() == 0:
a_exp = exp(a_)
else:
a_max = amax(a_, dim, keepdim=True)
a_exp = exp(a_ - a_max)
return _maybe_convert_to_dtype(
true_divide(a_exp, sum(a_exp, dim, keepdim=True)), result_dtype
) # type: ignore[return-value]
# CompositeImplicitAutograd - don't register decomp
@out_wrapper()
def hstack(tensors: TensorSequenceType) -> TensorLikeType:
torch._check(len(tensors) > 0, lambda: "hstack expects a non-empty TensorList")
aligned_tensors = atleast_1d(*tensors)
if aligned_tensors[0].ndim == 1:
return cat(aligned_tensors, 0)
return cat(aligned_tensors, 1)
# CompositeImplicitAutograd - don't register decomp
@out_wrapper()
def vstack(tensors: TensorSequenceType) -> TensorLikeType:
torch._check(len(tensors) > 0, lambda: "vstack expects a non-empty TensorList")
aligned_tensors = atleast_2d(*tensors)
return cat(aligned_tensors, 0)
# CompositeImplicitAutograd - don't register decomp
def unflatten(a: TensorLikeType, dim: int, sizes: ShapeType) -> TensorLikeType:
dim = utils.canonicalize_dim(a.ndim, dim)
torch._check(len(sizes) != 0, lambda: "unflatten: sizes must be non-empty")
return a.view(tuple(a.shape[:dim]) + tuple(sizes) + tuple(a.shape[dim + 1 :]))
@register_decomposition(aten.unbind)
def unbind(t: TensorLikeType, dim: int = 0) -> TensorSequenceType:
from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
dim = utils.canonicalize_dim(t.ndim, dim)
torch._check_index(
len(t.shape) > 0,
lambda: "Dimension specified as 0 but tensor has no dimensions",
)
if guard_size_oblivious(t.shape[dim] == 0):
return ()
else:
return tuple(
torch.squeeze(s, dim) for s in torch.tensor_split(t, t.shape[dim], dim)
)
@out_wrapper()
def index_copy(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike):
return x.clone(memory_format=torch.contiguous_format).index_copy_(
dim, index, tensor
)
def index_copy_(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike):
dim = utils.canonicalize_dims(x.ndim, dim)
torch._check(
index.ndim <= 1,
lambda: f"Index should have dimension 1 or 0 (got {index.ndim})",
)
# Treat scalars as elements of \R^1
y = x.unsqueeze(0) if x.ndim == 0 else x
idx = (slice(None),) * dim + (index,)
y[idx] = tensor
return x
@register_decomposition(aten.index_fill)
@out_wrapper()
def index_fill(
x: TensorLike, dim: int, index: TensorLike, value: Union[NumberType, TensorLike]
):
return _index_fill(x, dim, index, value, inplace=False)
@register_decomposition(aten.index_fill_)
def index_fill_(
x: TensorLike, dim: int, index: TensorLike, value: Union[NumberType, TensorLike]
):
return _index_fill(x, dim, index, value, inplace=True)
def _index_fill(
x: TensorLike,
dim: int,
index: TensorLike,
value: Union[NumberType, TensorLike],
*,
inplace: bool,
):
torch._check(
index.ndim <= 1,
lambda: f"Index should have dimension 1 or 0 (got {index.ndim})",
)
if isinstance(value, TensorLike):
torch._check(
value.ndim == 0,
lambda: "Only supports 0-dimensional value tensor. " # type: ignore[union-attr]
f"Got a tensor with {value.ndim} dimensions.",
) # type: ignore[arg-type]
else:
value = torch.scalar_tensor(
value,
dtype=x.dtype,
layout=x.layout,
device=x.device, # type: ignore[arg-type]
)
# index_copy has some unnecessary preconditions when x is a scalar. We do this to work through them
zero_dim = x.ndim == 0
y = x.unsqueeze(0) if zero_dim else x
# index_copy does not broadcast on value so we have to do it manually
shape = list(y.shape)
shape[dim] = index.numel()
value = value.expand(shape)
index_copy = Tensor.index_copy_ if inplace else torch.index_copy
out = index_copy(y, dim, index, value) # type: ignore[operator]
if inplace:
return x
else:
if zero_dim:
# The clone is necessary so that it returns a fresh tensor rather than a view
out = out.squeeze(0).clone()
# index_fill preserves the strides. index_copy always returns contiguous tensors
if out.stride() != x.stride():
new_out = torch.empty_like(x)
new_out.copy_(out)
out = new_out
return out
@out_wrapper()
def index_add(
x: TensorLike,
dim: int,
index: TensorLike,
tensor: TensorLike,
*,
alpha: NumberType = 1,
):
# index_add always returns a new contiguous tensor
return x.clone(memory_format=torch.contiguous_format).index_add_(
dim,
index,
tensor,
alpha=alpha, # type: ignore[arg-type]
)
@register_decomposition(aten.index_select)
@out_wrapper()
def index_select(x: TensorLike, dim: int, index: TensorLike):
dim = utils.canonicalize_dims(x.ndim, dim)
torch._check(
index.ndim <= 1,
lambda: f"Index should have dimension 1 or 0 (got {index.ndim})",
)
if index.ndim == 0:
index = index.unsqueeze(0)
if x.ndim == 0:
# Treat scalars as elements of \R^1
# We cannot use x[idx] here as it accesses item() (??), hence this awkward construction
return torch.empty_like(x).index_copy(0, index, x.expand_as(index))
idx = (slice(None),) * dim + (index,)
return x[idx]
@register_decomposition(aten.squeeze.dims)
def squeeze(a: TensorLikeType, dim: Optional[DimsType] = None) -> TensorLikeType:
from torch.fx.experimental.symbolic_shapes import guard_size_oblivious
if dim is None:
dims = tuple(idx for idx, size in enumerate(a.shape) if size == 1)
return prims.squeeze(a, dims) if dims else prims.view_of(a)
ndim = a.ndim
dim = utils.canonicalize_dims(ndim, dim)
dims = (dim,) if isinstance(dim, Dim) else dim
# Short-circuits if the tensor has no dimensions
if ndim == 0:
assert len(dims) == 0 or dims == (0,)
return prims.view_of(a)
# Note: squeeze does not modify tensors when the given dim is not a dimension of length 1
dims = tuple(d for d in dims if guard_size_oblivious(a.shape[d] == 1))
if len(dims) == 0:
return prims.view_of(a)
if len(dims) == 1:
return prims.squeeze(a, dims)
dims_list = list(dims)
dims_list = sorted(dims_list, reverse=True)
for i in dims_list:
a = squeeze(a, i)
return a
@register_decomposition(aten.split_with_sizes)
def split_with_sizes(
self: Tensor, split_sizes: List[int], dim: int = 0
) -> List[Tensor]:
# NB: Perform the check_is_size tests first so that the
# sum test does not try to do a replacement
for i in range(len(split_sizes)):
torch._check_is_size(
split_sizes[i],
lambda: "split_with_sizes expects split_sizes have only non-negative entries",
)
torch._check_with(
ValueError,
builtins.sum(split_sizes) == self.shape[dim],
lambda: f"Split sizes add up to {builtins.sum(split_sizes)} but got the tensor's size of {self.shape[dim]}",
)
splits = []
offset = self.storage_offset()
for split_size in split_sizes:
new_shape = list(self.shape)
new_shape[dim] = split_size
# We reimplement narrow here to avoid a lot of checks in the
# decomposition of narrow which calls slice_in_dim and slice
splits.append(self.as_strided(new_shape, self.stride(), offset))
offset = offset + self.stride()[dim] * split_size
return splits
# Note: does not work with TensorMetas because of data-dependent control-flow
# CompositeImplicitAutograd - don't register decomp
def tensor_split(
a: TensorLikeType,
indices_or_sections: Union[Tensor, DimsType],
dim: int = 0,
) -> Tuple[TensorLikeType, ...]:
_dim = utils.canonicalize_dim(a.ndim, dim)
if a.ndim == 0:
msg = "tensor_split: received a rank zero tensor, but expected a tensor of rank one or greater!"
raise ValueError(msg)
# If indices_or_sections is a tensor, it must be a CPU Long tensor
if isinstance(indices_or_sections, TensorLike):
if not indices_or_sections.device.type == "cpu":
msg = (
f"tensor_split: if indices_or_sections is a tensor it must be on the CPU, "
f"but received one on {indices_or_sections.device}"
)
raise ValueError(msg)
if indices_or_sections.dtype != torch.long:
msg = "tensor_split: if indices_or_sections is a tensor it must have long dtype, "
f" but received one with dtype {indices_or_sections.dtype}"
raise ValueError(msg)
# Case 0 -- indices_or_sections is an integer or a scalar tensor n and a is split along dim into n parts of equal-ish length
if isinstance(indices_or_sections, IntLike) or (
isinstance(indices_or_sections, TensorLike) and indices_or_sections.ndim == 0
):
sections: int = (
indices_or_sections # type: ignore[assignment]
if isinstance(indices_or_sections, Number)
else indices_or_sections.item()
)
if sections <= 0:
msg = f"tensor_split: number of sections must be greater than 0, but was {sections}"
raise ValueError(msg)
dim_size = a.shape[_dim]
min_split_size = math.floor(dim_size / sections)
num_splits_one_extra = dim_size % sections
split_sizes = []
for split_idx in range(sections):
split_size = (
min_split_size + 1
if (split_idx < num_splits_one_extra)
else min_split_size
)
split_sizes.append(split_size)
return tuple(aten.split_with_sizes(a, split_sizes, dim=_dim))
# Case 1 -- indices_or_sections is a sequence of integers or a 1D tensor describing the splits
else:
indices = indices_or_sections
if isinstance(indices_or_sections, TensorLike):
if indices_or_sections.ndim != 1:
msg = "tensor_split: non-scalar indices_or_sections tensors must have only one dimension, "
f"but received a tensor with {indices_or_sections.ndim} dimensions"
raise ValueError(msg)
indices = indices_or_sections.tolist()
indices = [0] + list(indices) + [a.shape[_dim]]
split_sizes = [indices[i + 1] - indices[i] for i in range(len(indices) - 1)]
return tuple(aten.split_with_sizes(a, split_sizes, dim=_dim))
# CompositeImplicitAutograd - don't register decomp
def hsplit(
a: TensorLikeType, indices_or_sections: DimsType
) -> Tuple[TensorLikeType, ...]:
torch._check(
a.ndim >= 1,
lambda: (
"torch.hsplit requires a tensor with at least 1 dimension, but got a tensor with "
+ str(a.ndim)
+ " dimensions!"
),
)
dim = 0 if a.ndim == 1 else 1
if isinstance(indices_or_sections, IntLike):
split_size = indices_or_sections
torch._check(
(split_size != 0 and a.shape[dim] % split_size == 0),
lambda: (
"torch.hsplit attempted to split along dimension "
+ str(dim)
+ ", but the size of the dimension "
+ str(a.shape[dim])
+ " is not divisible by the split_size "
+ str(split_size)
+ "!"
),
)
return tensor_split(a, split_size, dim)
torch._check_type(
isinstance(indices_or_sections, (list, tuple)),
lambda: (
"hsplit(): received an invalid combination of arguments. "
"Expected indices_or_sections to be of type int, list of ints or tuple of ints "
f"but got type {type(indices_or_sections)}"
),
)
split_sizes = indices_or_sections
return tensor_split(a, split_sizes, dim)
# CompositeImplicitAutograd - don't register decomp
def vsplit(
a: TensorLikeType, indices_or_sections: DimsType
) -> Tuple[TensorLikeType, ...]:
torch._check(
a.ndim >= 2,
lambda: (
"torch.vsplit requires a tensor with at least 2 dimension, but got a tensor with "
+ str(a.ndim)
+ " dimensions!"
),
)
if isinstance(indices_or_sections, IntLike):
split_size = indices_or_sections
torch._check(
(split_size != 0 and a.shape[0] % split_size == 0),
lambda: (
f"torch.vsplit attempted to split along dimension 0"
f", but the size of the dimension "
f"{a.shape[0]}"
f" is not divisible by the split_size "
f"{split_size}"
f"!"
),
)
return tensor_split(a, split_size, 0)
torch._check_type(
isinstance(indices_or_sections, (list, tuple)),
lambda: (
"vsplit(): received an invalid combination of arguments. "
"Expected indices_or_sections to be of type int, list of ints or tuple of ints "
f"but got type {type(indices_or_sections)}"
),
)
split_sizes = indices_or_sections
return tensor_split(a, split_sizes, 0)
@register_decomposition(aten.diag.out)
@out_wrapper()
def diag(
self: TensorLikeType,
offset: int = 0,
) -> TensorLikeType:
ndim = self.dim()
torch._check(
ndim in (1, 2), lambda: f"diag(): Supports 1D or 2D tensors. Got {ndim}D"
)
if ndim == 1:
return torch.diag_embed(self, offset)
else:
return torch.diagonal_copy(self, offset)
@register_decomposition(aten.diagonal_scatter)
@out_wrapper()
def diagonal_scatter(
input: TensorLikeType,
src: TensorLikeType,
offset: int = 0,
dim1: int = 0,
dim2: int = 1,
) -> TensorLikeType:
out = utils.clone_preserve_strides(input)
diag = out.diagonal(offset, dim1, dim2)
torch._check(
diag.shape == src.shape,
lambda: "expected src to have a size equal to the diagonal of the input."
f"Got {src.shape} for a diagonal of shape {diag.shape}",
)
copy_to(diag, src)
return out
@register_decomposition(aten.diagonal)
def diagonal(
self: TensorLikeType,
offset: int = 0,
dim1: int = 0,
dim2: int = 1,
) -> TensorLikeType:
"""
Reference implementation of torch.diagonal
"""
num_dims = self.dim()
dim1 = utils.canonicalize_dim(idx=dim1, rank=num_dims)
dim2 = utils.canonicalize_dim(idx=dim2, rank=num_dims)
torch._check(
dim1 != dim2, lambda: f"diagonal dimensions cannot be identical {dim1}, {dim2}"
)
storage_offset = self.storage_offset()
if offset >= 0:
diag_size = max(min(self.size()[dim1], self.size()[dim2] - offset), 0)
else:
diag_size = max(min(self.size()[dim1] + offset, self.size()[dim2]), 0)
if diag_size > 0:
if offset >= 0:
storage_offset += offset * self.stride()[dim2]
else:
storage_offset -= offset * self.stride()[dim1]
sizes = [s for i, s in enumerate(self.size()) if i not in (dim1, dim2)]
sizes.append(diag_size)
strides = [s for i, s in enumerate(self.stride()) if i not in (dim1, dim2)]
strides.append(self.stride()[dim1] + self.stride()[dim2])
result = self.as_strided(size=sizes, stride=strides, storage_offset=storage_offset)
return result
@register_decomposition(aten.diag_embed)
@out_wrapper()
def diag_embed(
t: TensorLikeType,
offset: int = 0,
dim1: int = -2,
dim2: int = -1,
) -> TensorLikeType:
"""
Reference implementation of torch.diag_embed
"""
# convert from negative dims
rank = t.ndim + 1
dim1 = utils.canonicalize_dim(rank=rank, idx=dim1)
dim2 = utils.canonicalize_dim(rank=rank, idx=dim2)
# as per the docs, exchanging dims is equivalent to changing the sign of
# offset
if dim1 > dim2:
dim1, dim2 = dim2, dim1
offset = -offset
torch._check(
dim1 != dim2, lambda: f"diagonal dimensions cannot be identical {dim1}, {dim2}"
)
# as per the docs, the size of last dim is placed at dim1 and dim2
last_dim = t.size(-1)
if offset != 0:
# add padding to match the new size
t_shape = list(t.shape)
t_shape[-1] = builtins.abs(offset)
z = torch.zeros(t_shape, dtype=t.dtype, device=t.device, requires_grad=False)
pair = (z, t) if offset > 0 else (t, z)
t = torch.cat(pair, dim=-1)
# make sure the diagonal always has the same size
last_dim += builtins.abs(offset)
# preserve original data, but place 1 at dim1 and move last dim to dim2
t = t.unsqueeze(dim1).movedim(-1, dim2)
# generate ranges shifting indices based on offset
a_range = torch.arange(last_dim, device=t.device, dtype=torch.int64)
b_range = torch.arange(
offset, last_dim + offset, device=t.device, dtype=torch.int64
)
# broadcast
cond = a_range == b_range.unsqueeze(-1)
cond_shape = [last_dim if i in (dim1, dim2) else 1 for i in range(len(t.shape))]
cond = cond.reshape(cond_shape)
# aten.diag_embed always returns a new contiguous tensor
# contiguous() is needed to correctly model the output stride
return utils.mask_tensor(cond, t).contiguous()
@register_decomposition(aten.block_diag)
@out_wrapper()
def _block_diag_iterable(tensors: List[TensorLikeType]) -> TensorLikeType:
"""
Reference implementation of torch.block_diag
"""
tensors_2d = [
tensor.view(1, -1) if tensor.dim() <= 1 else tensor for tensor in tensors
]
ncols = builtins.sum(tensor.shape[1] for tensor in tensors_2d)
device = tensors_2d[0].device
result = []
col_start = 0
for i, tensor in enumerate(tensors_2d):
torch._check(
tensor.dim() == 2,
lambda: "Input tensors must have 2 or fewer dimensions. "
f"Input {i} has {tensor.dim()} dimensions",
)
torch._check(
tensor.device == device,
lambda: "Input tensors must all be on the same device. "
f"Input 0 is on device {device} and input {i} is on device {tensor.device}.",
)
row, col = tensor.shape
left = torch.zeros((row, col_start), device=device, dtype=tensor.dtype)
right = torch.zeros(
(row, ncols - col_start - col), device=device, dtype=tensor.dtype
)
result += [torch.cat((left, tensor, right), dim=1)]
col_start += col
return torch.cat(result, dim=0)
def block_diag(*tensors: List[TensorLikeType]) -> TensorLikeType:
"""
This is used as an input to PythonRefInfo. `torch.block_diag`
expects arguments splatted, but `aten.block_diag` expects only
one argument that is a list of Tensors.
"""
return _block_diag_iterable(tensors) # type: ignore[arg-type]
# CompositeImplicitAutograd - don't register decomp
def dsplit(a: TensorLikeType, sections: DimsType) -> TensorSequenceType:
if a.ndim < 3:
raise RuntimeError(
f"torch.dsplit requires a tensor with at least 3 dimension, but got a tensor with {a.ndim} dimensions!"
)
if isinstance(sections, IntLike) and (sections == 0 or a.shape[2] % sections != 0):
raise RuntimeError(
"torch.dsplit attempted to split along dimension 2, "
+ f"but the size of the dimension {a.shape[2]} is not divisible by the split_size {sections}!"
)
return tensor_split(a, sections, 2)
@register_decomposition(aten.t.default)
def t(a: TensorLikeType):
# TODO: Add sparse support
# if a.is_sparse:
# sparse_dim = a.sparse_dim()
# dense_dim = a.dense_dim()
# if not (sparse_dim <= 2 and dense_dim == 0):
# raise RuntimeError(
# f"t() expects a tensor with <= 2 sparse and 0 dense dimensions, but got {sparse_dim} sparse and"
# f"{dense_dim} dense dimensions"
# )
if a.ndim > 2:
raise RuntimeError(
f"t() expects a tensor with <= 2 dimensions, but self is {a.ndim}D"
)
return torch.transpose(a, 0, 0 if a.ndim < 2 else 1)
# CompositeImplicitAutograd - don't register decomp
def T(a: TensorLikeType) -> TensorLikeType:
# n != 2 && n != 0 is deprecated in regular PyTorch.
torch._check(
a.ndim in (0, 2),
lambda: (
"The use of `x.T` on tensors of dimension other than 0 or 2 "
"to reverse their shape is not supported."
),
)
return a.t()
@register_decomposition(aten.alias)
def alias(a: TensorLikeType) -> TensorLikeType:
return prims.view_of(a)
@register_decomposition(aten.transpose)
def transpose(a: TensorLikeType, dim0: int, dim1: int) -> TensorLikeType:
_dim0, _dim1 = utils.canonicalize_dims(a.ndim, (dim0, dim1)) # type: ignore[misc]
if a.ndim <= 1 or dim0 == dim1:
return aten.alias.default(a)
_permutation = list(range(0, a.ndim))
_permutation[_dim0] = _dim1
_permutation[_dim1] = _dim0
return torch.permute(a, _permutation)
# Aliases for transpose
swap_axes = transpose
@register_decomposition(aten.unfold)
def unfold(
self: TensorLikeType, dimension: int, size: int, step: int
) -> TensorLikeType:
shape, strides = _get_unfold_shape_stride(
self.shape, self.stride(), dimension, size, step
)
return self.as_strided(shape, strides)
@register_decomposition(aten.unfold_copy)
@out_wrapper()
def unfold_copy(self: TensorLikeType, dimension: int, size: int, step: int):
return self.unfold(dimension, size, step).clone(
memory_format=torch.contiguous_format
)
def _cumsumprod_common(
func,
init,
a: TensorLikeType,
dim: int,
*,
dtype: Optional[torch.dtype] = None,
out: Optional[Tensor] = None,
) -> TensorLikeType:
# We implement all the kwargs of a reduction. ATen just handles dtype
# nb. This decomposition may not be as efficient as a backend-specific implementation
ndim = a.ndim
dim = utils.canonicalize_dim(ndim, dim)
if ndim == 0:
return func(a.unsqueeze(0), dim=0, dtype=dtype, out=out)
a = a.unsqueeze(dim + 1)
rg = torch.arange(a.shape[dim], device=a.device)
mask = rg.unsqueeze(1) <= rg
for _ in range(ndim - dim - 1):
mask = mask.unsqueeze(-1)
masked_a = torch.where(mask, a, init)
return func(masked_a, dim=dim, dtype=dtype, out=out)
@register_decomposition(aten.cumsum)
def cumsum(
a: TensorLikeType,
dim: int,
*,
dtype: Optional[torch.dtype] = None,
out: Optional[Tensor] = None,
) -> TensorLikeType:
return _cumsumprod_common(func=sum, init=0, a=a, dim=dim, dtype=dtype, out=out)
@register_decomposition(aten.cumprod)
def cumprod(
a: TensorLikeType,
dim: int,
*,
dtype: Optional[torch.dtype] = None,
out: Optional[Tensor] = None,
) -> TensorLikeType:
return _cumsumprod_common(func=prod, init=1, a=a, dim=dim, dtype=dtype, out=out)
# Note: although squeeze is documented as having the out= kwarg it doesn't
@register_decomposition(aten.unsqueeze)
def unsqueeze(a: TensorLikeType, dim: int) -> TensorLikeType:
# Note that unsqueeze canonicalizes with rank + 1 because it allows
# a new innermost dimension to be specified
ndim = a.ndim + 1
dim = utils.canonicalize_dim(ndim, dim)
return prims.expand_dims(a, (dim,), ndim=ndim)
# NOTE: shape is a vararg because Tensor.reshape can be called with as
# Tensor.view(a, b, c) or Tensor.view((a, b, c)) Function call torch.view
# doesn't support unpacked shapes
# TODO: Turn this into a decomposition (currently fails on reshape meta tests)
@register_decomposition(aten.view.default)
def view(a: TensorLikeType, *shape: ShapeType) -> TensorLikeType:
return _reshape_view_helper(a, *shape, allow_copy=False)
# CompositeImplicitAutograd - don't register decomp
def view_as(self: TensorLikeType, other: TensorLikeType) -> TensorLikeType:
return self.view(other.size())
# CompositeImplicitAutograd - don't register decomp
def ravel(a: TensorLikeType) -> TensorLikeType:
return reshape(a, (-1,))
# CompositeImplicitAutograd - don't register decomp
# missing ref impl. for aten.gather
@out_wrapper()
def take_along_dim(
a: torch.Tensor, indices: torch.Tensor, dim: Optional[int] = None
) -> torch.Tensor:
torch._check(
a.ndim == indices.ndim,
lambda: (
"torch.take_along_dim(): input and indices should have the same "
f"number of dimensions, but got {a.ndim} dimensions for input, and "
f"{indices.ndim} dimensions for indices"
),
)
torch._check(
utils.is_integer_dtype(indices.dtype),
lambda: (
"torch.take_along_dim(): dtype of indices should be int but got "
f"{indices.dtype} instead"
),
)
if dim is None:
return torch.gather(a.view(-1), 0, indices.view(-1))
else:
self_sizes = list(a.shape)
self_sizes[dim] = indices.size(dim)
broadcast_shape = utils.infer_size_shapes(self_sizes, indices.size())
indices_broadcast = broadcast_to(indices, broadcast_shape)
indices_sizes = list(indices.shape)
indices_sizes[dim] = a.size(dim)
broadcast_shape = utils.infer_size_shapes(indices_sizes, a.size())
self_broadcast = broadcast_to(a, broadcast_shape)
return torch.gather(self_broadcast, dim, indices_broadcast)
@out_wrapper()
def empty(
*shape,
dtype: Optional[torch.dtype] = None,
layout: torch.layout = torch.strided,
device: Optional[DeviceLikeType] = None,
requires_grad: bool = False,
pin_memory: bool = False,
memory_format: torch.memory_format = torch.contiguous_format,
) -> TensorLikeType:
torch._check(
memory_format != torch.preserve_format,
lambda: "torch.empty: the Preserve memory format is not supported",
)
shape = utils.extract_shape_from_varargs(shape)
if memory_format == torch.contiguous_format:
strides = utils.make_contiguous_strides_for(shape)
elif memory_format == torch.channels_last_3d:
strides = utils.make_channels_last_3d_strides_for(shape)
else: # memory_format == torch.channels_last
torch._check(
memory_format == torch.channels_last,
lambda: f"torch.empty: received an unknown memory format {memory_format}!",
)
strides = utils.make_channels_last_2d_strides_for(shape)
return torch.empty_strided(
shape,
strides,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
)
@out_wrapper()
def empty_permuted(
shape,
physical_layout,
dtype: Optional[torch.dtype] = None,
layout: torch.layout = torch.strided,
device: Optional[DeviceLikeType] = None,
requires_grad: bool = False,
pin_memory: bool = False,
) -> TensorLikeType:
return prims.empty_permuted(
shape,
physical_layout,
dtype=dtype,
device=device,
requires_grad=requires_grad,
)
@register_decomposition(aten.new_empty)
@out_wrapper()
def new_empty(
a: TensorLikeType,
size: ShapeType,
*,
dtype: Optional[torch.dtype] = None,
layout: Optional[torch.layout] = None,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
) -> TensorLikeType:
dtype = a.dtype if dtype is None else dtype
layout = a.layout if layout is None else layout
device = a.device if device is None else device
return torch.empty(
size,
dtype=dtype,
device=device,
pin_memory=pin_memory,
layout=layout,
)
@register_decomposition(aten.new_empty_strided)
@out_wrapper()
def new_empty_strided(
a: TensorLikeType,
size: ShapeType,
stride: StrideType,
*,
dtype: Optional[torch.dtype] = None,
layout: Optional[torch.layout] = None,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
) -> TensorLikeType:
"""
Reference implementation of torch.Tensor.new_empty_strided
"""
dtype = a.dtype if dtype is None else dtype
layout = a.layout if layout is None else layout
device = a.device if device is None else device
return torch.empty_strided(
size,
stride,
dtype=dtype,
device=device,
pin_memory=pin_memory,
layout=layout,
)
@register_decomposition(aten.zeros.default)
@out_wrapper()
def zeros(
*size,
dtype: Optional[torch.dtype] = None,
layout: torch.layout = torch.strided,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
size = utils.extract_shape_from_varargs(size)
if dtype is None:
dtype = torch.get_default_dtype()
return torch.full(
size,
False if dtype == torch.bool else 0,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
)
@register_decomposition(aten.new_zeros)
@out_wrapper()
def new_zeros(
a: TensorLikeType,
size: ShapeType,
*,
dtype: Optional[torch.dtype] = None,
layout: Optional[torch.layout] = None,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
dtype = a.dtype if dtype is None else dtype
layout = a.layout if layout is None else layout
device = a.device if device is None else device
return torch.full(
size,
False if (dtype or a.dtype) == torch.bool else 0,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
)
@register_decomposition(aten.ones.default)
@out_wrapper()
def ones(
*size,
dtype: Optional[torch.dtype] = None,
layout: torch.layout = torch.strided,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
size = utils.extract_shape_from_varargs(size)
if dtype is None:
dtype = torch.get_default_dtype()
return torch.full(
size,
True if dtype == torch.bool else 1,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
)
@register_decomposition(aten.new_ones)
@out_wrapper()
def new_ones(
a: TensorLikeType,
size: ShapeType,
*,
dtype: Optional[torch.dtype] = None,
layout: Optional[torch.layout] = None,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
dtype = a.dtype if dtype is None else dtype
layout = a.layout if layout is None else layout
device = a.device if device is None else device
return torch.full(
size,
True if (dtype or a.dtype) == torch.bool else 1,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
)
@register_decomposition(aten.new_full)
@out_wrapper()
def new_full(
a: TensorLikeType,
size: ShapeType,
fill_value: NumberType,
*,
dtype: Optional[torch.dtype] = None,
layout: Optional[torch.layout] = None,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
) -> TensorLikeType:
dtype = a.dtype if dtype is None else dtype
layout = a.layout if layout is None else layout
device = a.device if device is None else device
return torch.full(
size,
fill_value,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
)
@register_decomposition(aten.empty_like)
@out_wrapper()
def empty_like(
a: TensorLikeType,
*,
dtype: Optional[torch.dtype] = None,
device: Optional[DeviceLikeType] = None,
layout: Optional[torch.layout] = None,
pin_memory: bool = False,
requires_grad: bool = False,
memory_format: torch.memory_format = torch.preserve_format,
) -> TensorLikeType:
dtype = a.dtype if dtype is None else dtype
layout = a.layout if layout is None else layout
device = a.device if device is None else device
if memory_format != torch.preserve_format:
return torch.empty(
a.shape,
dtype=dtype,
layout=layout,
device=device,
requires_grad=requires_grad,
pin_memory=pin_memory,
memory_format=memory_format,
)
# memory_format == torch.preserve_format
logical_to_physical_perm = (
utils.compute_elementwise_output_logical_to_physical_perm(a)
)
# identity perm is [2, 1, 0]
return torch.empty_permuted(
a.shape,
logical_to_physical_perm,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
)
@register_decomposition([aten.arange.start_step, aten.arange.start_out])
@out_wrapper()
def arange(
start: NumberType = 0,
end: Optional[NumberType] = None,
step: NumberType = 1,
*,
dtype: Optional[torch.dtype] = None,
layout: torch.layout = torch.strided,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
utils.check_layout(layout)
utils.check_pin_memory(pin_memory)
device = torch.device(utils.device_or_default(device))
assert not isinstance(start, complex)
assert not isinstance(end, complex)
assert not isinstance(step, complex)
# Case: torch.arange(5)
if end is None:
end = start
start = 0
torch._check(step != 0, lambda: "step must be nonzero")
if step > 0:
torch._check(
end >= start,
lambda: "upper bound and lower bound inconsistent with step sign",
)
elif step < 0:
torch._check(
end <= start,
lambda: "upper bound and lower bound inconsistent with step sign",
)
def is_finite(x):
return not isinstance(x, FloatWithoutSymFloat) or math.isfinite(x)
torch._check(
is_finite(start) and is_finite(end),
lambda: f"unsupported range: {start} -> {end}",
)
torch._check(
is_finite(step),
lambda: f"step must be finite but got {step}",
)
args = (start, end, step)
integer_args = builtins.all(isinstance(arg, IntLike) for arg in args)
if dtype is None:
dtype = torch.int64 if integer_args else torch.get_default_dtype()
is_integer = utils.is_integer_dtype(dtype)
if is_integer or integer_args:
xstart = sym_int(start)
xend = sym_int(end)
xstep = sym_int(step)
# For int64 we truncate arguments to int before calculating length, but
# other integral dtypes we don't. Weird... but needed to match ATen shapes.
if dtype == torch.int64 or integer_args:
# Uses floordiv to avoid ceil in inductor.
sgn = bool(xstep > 0) - bool(xstep < 0) # type: ignore[possibly-undefined]
length = (xend - xstart + xstep - sgn) // xstep # type: ignore[possibly-undefined]
else:
length = math.ceil((end - start) / step)
if is_integer:
return prims.iota(
length,
start=xstart, # type: ignore[possibly-undefined]
step=xstep, # type: ignore[possibly-undefined]
dtype=dtype,
device=device,
requires_grad=requires_grad,
)
index = prims.iota(
length,
start=0,
step=1,
dtype=torch.int64,
device=device,
requires_grad=False,
)
computation_dtype = (
torch.long if integer_args else utils.get_acc_type(dtype, device)
)
index = _maybe_convert_to_dtype(index, computation_dtype)
result = start + step * index
result = _maybe_convert_to_dtype(result, dtype)
if requires_grad:
result.requires_grad_(True)
return result
@register_decomposition(aten.lerp)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("start", "end", "weight"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def lerp(start: Tensor, end: Tensor, weight: Union[Tensor, NumberType]):
inputs = [start, end]
if isinstance(weight, Number):
weight = start.new_full((), weight) # type: ignore[arg-type]
else:
inputs.append(weight)
assert isinstance(weight, Tensor) # mypy
# We implement it this way for numerical stability. We assume (in the stability optimisation)
# that 0 <= weight <= 1. We take the abs to deal with complex numbers
# We want to perform operations near zero, which is where floating points are most precise
# thus, we perform the following optimisation:
# If weight.abs() >= 0.5:
# return (1 - weight) * (start - end) + end
mask = weight.abs() >= 0.5
coeff = torch.where(mask, weight - 1, weight)
base = torch.where(mask, end, start)
output = coeff * (end - start) + base
# make sure the decomposition output's stride is same as non-decomposition path.
stride = utils.compute_elementwise_output_strides(*_maybe_broadcast(*inputs))
if output.stride() != stride:
output = prims.copy_strided(output, stride)
return handle_noncontiguous_outputs(inputs, output)
@register_decomposition(aten.linspace)
@out_wrapper()
def linspace(
start: Union[NumberType, TensorLikeType],
end: Union[NumberType, TensorLikeType],
steps: NumberType,
*,
dtype: Optional[torch.dtype] = None,
device: Optional[DeviceLikeType] = None,
layout: torch.layout = torch.strided,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
if isinstance(start, TensorLikeType):
torch._check(
start.dim() == 0,
lambda: "linspace only supports 0-dimensional start and end tensors",
)
start = _maybe_convert_to_dtype(start, torch.float64)
if isinstance(end, TensorLikeType):
torch._check(
end.dim() == 0,
lambda: "linspace only supports 0-dimensional start and end tensors",
)
end = _maybe_convert_to_dtype(end, torch.float64)
if builtins.any(isinstance(arg, complex) for arg in (start, end, steps)):
default_complex_dtype = utils.corresponding_complex_dtype(
torch.get_default_dtype()
)
if dtype is None:
dtype = default_complex_dtype
else:
torch._check(
utils.is_complex_dtype(dtype),
lambda: f"linspace(): inferred dtype {default_complex_dtype} can't be safely cast to passed dtype {dtype}",
)
else:
dtype = dtype or torch.get_default_dtype()
assert isinstance(dtype, torch.dtype)
# steps does not participate in the computation of the dtype
torch._check_type(
isinstance(steps, IntLike),
lambda: f"received an invalid combination of arguments - got \
({type(start).__name__}, {type(end).__name__}, {type(steps).__name__})",
)
assert isinstance(steps, IntLike) # for mypy
torch._check(steps >= 0, lambda: "number of steps must be non-negative")
factory_kwargs = {
"layout": layout,
"device": device,
"pin_memory": pin_memory,
"requires_grad": requires_grad,
}
if steps == 0:
return torch.full((0,), 0, dtype=dtype, **factory_kwargs) # type: ignore[arg-type]
if steps == 1:
if isinstance(start, TensorLikeType):
return torch.empty((steps,), dtype=dtype, **factory_kwargs).copy_(start) # type: ignore[arg-type]
else:
return torch.full((steps,), start, dtype=dtype, **factory_kwargs) # type: ignore[arg-type]
# Perform in arange in int because some backends like ATen or Triton do not support all the dtypes
rg = torch.arange(0, steps, **factory_kwargs) # type: ignore[arg-type]
# Small types need to be computed in higher precision as this is, at heart, an associative scan
dtype_red = (
torch.int64
if (utils.is_boolean_dtype(dtype) or utils.is_integer_dtype(dtype))
else dtype
)
computation_dtype, _ = utils.reduction_dtypes(
rg, REDUCTION_OUTPUT_TYPE_KIND.SAME, dtype_red
)
cast_rg = partial(_maybe_convert_to_dtype, dtype=computation_dtype)
# We implement torch.lerp without performing rg / (steps - 1) explicitly
# With this we get out[0] == start, out[-1] == end
step = (end - start) / (steps - 1)
out = torch.where(
rg < steps / 2,
start + step * cast_rg(rg), # type: ignore[arg-type,operator]
end - step * cast_rg((steps - 1) - rg), # type: ignore[arg-type,operator]
)
return _maybe_convert_to_dtype(out, dtype) # type: ignore[return-value]
@register_decomposition(aten.logspace)
@out_wrapper()
def logspace(
start: Union[NumberType, TensorLikeType],
end: Union[NumberType, TensorLikeType],
steps: NumberType,
base: NumberType = 10,
*,
dtype: Optional[torch.dtype] = None,
device: Optional[DeviceLikeType] = None,
layout: torch.layout = torch.strided,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
if dtype is None:
dtype = torch.get_default_dtype()
# NB: NumPy doesn't have this cast
if prims.utils.is_integer_dtype(dtype):
if isinstance(start, FloatLike):
start = sym_int(start)
elif isinstance(start, TensorLikeType):
torch._check(
start.dim() == 0,
lambda: "logspace only supports 0-dimensional start and end tensors",
)
start = _maybe_convert_to_dtype(start, dtype)
if isinstance(end, FloatLike):
end = sym_int(end)
elif isinstance(end, TensorLikeType):
torch._check(
end.dim() == 0,
lambda: "logspace only supports 0-dimensional start and end tensors",
)
end = _maybe_convert_to_dtype(end, dtype)
if builtins.any(isinstance(arg, complex) for arg in (start, end, steps)):
default_complex_dtype = utils.corresponding_complex_dtype(
torch.get_default_dtype()
)
dtype = default_complex_dtype
_dtype = None # torch.linspace will update the correct dtype
else:
_dtype = torch.float64
assert not isinstance(base, complex) # for mypy
if base < 0:
raise NotImplementedError
ret = torch.linspace( # type: ignore[misc]
start, # type: ignore[arg-type]
end, # type: ignore[arg-type]
steps, # type: ignore[arg-type]
dtype=_dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
)
return _maybe_convert_to_dtype(torch.pow(base, ret), dtype) # type: ignore[arg-type,return-value]
@overload
def meshgrid(tensors: Sequence[TensorLikeType], indexing: str):
pass
@overload
def meshgrid(*tensors: TensorLikeType, indexing: str):
pass
@register_decomposition(aten.meshgrid) # type: ignore[misc]
def meshgrid(
*tensors: Union[TensorLikeType, List[TensorLikeType], Tuple[TensorLikeType]],
indexing: str,
) -> List[TensorLikeType]:
# This ref simultaneously handles two overloads (see stubs above)
# The `indexing` argument is currently optional for torch.meshgrid, but we
# plan to make the argument required: https://github.com/pytorch/pytorch/issues/50276
if isinstance(tensors[0], (list, tuple)):
assert len(tensors) == 1
tensors = tuple(tensors[0])
torch._check(
builtins.all(isinstance(a, TensorLike) for a in tensors),
lambda: "meshgrid expects its inputs to be tensors",
)
torch._check(len(tensors) > 0, lambda: "meshgrid expects a non-empty TensorList")
for i in range(len(tensors) - 1):
torch._check(
tensors[i].dtype == tensors[i + 1].dtype, # type: ignore[union-attr]
lambda: "meshgrid expects all tensors to have the same dtype",
)
torch._check(
tensors[i].device == tensors[i + 1].device, # type: ignore[union-attr]
lambda: "meshgrid expects all tensors to have the same device",
)
swap_first_and_second_tensors = False
if indexing == "xy":
swap_first_and_second_tensors = len(tensors) >= 2
if swap_first_and_second_tensors:
tensors = (tensors[1], tensors[0], *tensors[2:])
else:
torch._check(
indexing == "ij",
lambda: (
'torch.meshgrid: indexing must be one of "xy" or "ij", '
f"but received: {indexing}"
),
)
result_shape: List[int] = []
for t in tensors:
assert isinstance(t, TensorLike) # mypy
torch._check(
t.ndim == 0 or t.ndim == 1,
lambda: f"torch.meshgrid: Expected 0D or 1D tensor in the tensor list but got: {t}",
)
result_shape.append(t.numel())
grids: List[TensorLikeType] = []
for i, t in enumerate(tensors):
assert isinstance(t, TensorLike) # mypy
if t.ndim == 0:
t = t.view((1,))
grids.append(prims.broadcast_in_dim(t, result_shape, (i,)))
if swap_first_and_second_tensors:
# Swap outputs if we originally swapped at the beginning
grids[0], grids[1] = grids[1], grids[0]
return grids
# CompositeImplicitAutograd - don't register decomp
def movedim(
input: TensorLikeType,
source: Union[int, DimsSequenceType],
destination: Union[int, DimsSequenceType],
) -> TensorLikeType:
"""
Reference implementation of torch.movedim
"""
if type(source) is int:
source = (source,)
if type(destination) is int:
destination = (destination,)
# Converts to list to produce a compatible error message with core PyTorch,
# which prints sequences in square brackets.
torch._check(
len(source) == len(destination), # type: ignore[arg-type]
lambda: (
"movedim: Invalid source or destination dims: source " # type: ignore[arg-type]
f"({list(source)} dims) should contain the same number " # type: ignore[arg-type]
f"of dims as destination ({list(destination)} dims)" # type: ignore[arg-type]
),
)
rank = input.ndim
ss = tuple(utils.canonicalize_dims(rank=rank, indices=source)) # type: ignore[arg-type]
ds = tuple(utils.canonicalize_dims(rank=rank, indices=destination)) # type: ignore[arg-type]
sss = set(ss)
dss = set(ds)
# See above on why this converts to list in error messages.
torch._check(
len(ss) == len(sss),
lambda: f"movedim: repeated dim in `source` ({list(source)})", # type: ignore[arg-type]
)
torch._check(
len(ds) == len(dss),
lambda: f"movedim: repeated dim in `destination` ({list(destination)})", # type: ignore[arg-type]
)
m = dict(zip(ds, ss))
dims = []
si = 0 # source index
for di in range(rank):
# check if the destination index is in the mapping
s = m.get(di)
if s is not None:
# insert source index if found
dims.append(s)
else:
# insert source index sequentially, skipping indices from the mapping
while si in sss:
si += 1
dims.append(si)
si += 1
result = torch.permute(input, tuple(dims))
return result
# NOTE: for convenience, shape can be a tuple of ints or a tuple containing a tuple of ints
@register_decomposition(aten.empty_strided)
@out_wrapper()
def empty_strided(
shape: Union[ShapeType, Tuple[ShapeType]],
strides: StrideType,
*,
dtype: Optional[torch.dtype] = None,
device: Optional[DeviceLikeType] = None,
layout: torch.layout = torch.strided,
requires_grad: bool = False,
pin_memory: bool = False,
) -> TensorLikeType:
# Layout == strided, pin_memory is False
utils.check_layout(layout)
utils.check_pin_memory(pin_memory)
shape = utils.extract_shape_from_varargs(shape)
dtype = torch.get_default_dtype() if dtype is None else dtype
device = torch.device("cpu") if device is None else device
return prims.empty_strided(
shape,
strides,
dtype=dtype,
device=device,
requires_grad=requires_grad,
)
@register_decomposition(aten.eye)
@out_wrapper()
def eye(
n: int,
m: Optional[int] = None,
*,
dtype: Optional[torch.dtype] = None,
layout: torch.layout = torch.strided,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False, # TODO: unused
) -> TensorLikeType:
"""
Reference implementation of torch.eye
"""
if m is None:
m = n
torch._check(n >= 0, lambda: f"n must be greater or equal to 0, got {n}")
torch._check(m >= 0, lambda: f"m must be greater or equal to 0, got {m}")
range_n = torch.arange(n, dtype=torch.int64, device=device, requires_grad=False)
range_m = torch.arange(m, dtype=torch.int64, device=device, requires_grad=False)
cond = range_n.unsqueeze(-1) == range_m
if dtype is torch.bool:
return cond
else:
one = torch.ones(
(1,),
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=False,
)
return torch.where(cond, one, 0)
# TODO: Use requires_grad. All refs taking the requires_grad kwarg must
# return a leaf tensor.
# result.requires_grad_(requires_grad)
@register_decomposition([aten.full.default, aten.full.out])
@out_wrapper()
def full(
shape: ShapeType,
fill_value: NumberType,
*,
dtype: Optional[torch.dtype] = None,
layout: torch.layout = torch.strided,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
utils.check_layout(layout)
utils.check_pin_memory(pin_memory)
dtype = dtype if dtype is not None else utils.type_to_dtype(type(fill_value))
device = device if device is not None else torch.device("cpu")
e = empty(
shape,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
)
return torch.fill(e, fill_value) # type: ignore[arg-type]
def full_like(
a: TensorLikeType,
fill_value: NumberType,
*,
dtype: Optional[torch.dtype] = None,
layout: Optional[torch.layout] = None,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False,
memory_format: torch.memory_format = torch.preserve_format,
) -> TensorLikeType:
e = torch.empty_like(
a,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
memory_format=memory_format,
)
return fill(e, fill_value)
@register_decomposition(aten.zeros_like)
@out_wrapper()
def zeros_like(
a: TensorLikeType,
*,
dtype: Optional[torch.dtype] = None,
layout: Optional[torch.layout] = None,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False,
memory_format: torch.memory_format = torch.preserve_format,
) -> TensorLikeType:
return torch.full_like(
a,
False if (dtype or a.dtype) == torch.bool else 0,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
memory_format=memory_format,
)
@register_decomposition(aten.ones_like)
@out_wrapper()
def ones_like(
a: TensorLikeType,
*,
dtype: Optional[torch.dtype] = None,
layout: Optional[torch.layout] = None,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
requires_grad: bool = False,
memory_format: torch.memory_format = torch.preserve_format,
) -> TensorLikeType:
return torch.full_like(
a,
True if (dtype or a.dtype) == torch.bool else 1,
dtype=dtype,
layout=layout,
device=device,
pin_memory=pin_memory,
requires_grad=requires_grad,
memory_format=memory_format,
)
@register_decomposition(aten.randn.default)
@out_wrapper()
def randn(
*shape,
dtype: Optional[torch.dtype] = None,
device: Optional[DeviceLikeType] = None,
layout: Optional[torch.layout] = None,
requires_grad: bool = False,
pin_memory: bool = False,
) -> TensorLikeType:
utils.check_pin_memory(pin_memory)
shape_ = utils.extract_shape_from_varargs(shape)
dtype = utils.dtype_or_default(dtype)
device = utils.device_or_default(device)
return prims.normal(
shape_,
mean=0.0,
std=1.0,
dtype=dtype,
device=device,
requires_grad=requires_grad,
)
def scalar_tensor(
a: NumberType,
*,
dtype: Optional[torch.dtype] = None,
layout: torch.layout = torch.strided,
device: Optional[DeviceLikeType] = None,
pin_memory: bool = False,
) -> TensorLikeType:
utils.check_layout(layout)
utils.check_pin_memory(pin_memory)
dtype = dtype if dtype is not None else utils.type_to_dtype(type(a))
device = device if device is not None else torch.device("cpu")
return prims.scalar_tensor(a, dtype=dtype, device=device)
#
# Randomness References
#
def _uniform_helper(
shape: ShapeType,
low: Union[bool, int, float] = 0.0,
high: Union[bool, int, float] = 1.0,
*,
dtype: torch.dtype,
device: DeviceLikeType,
) -> TensorLikeType:
utils.validate_shape(shape)
assert isinstance(low, Number)
assert isinstance(high, Number)
low = sym_float(low)
high = sym_float(high)
assert isinstance(dtype, torch.dtype)
device = utils.canonicalize_device(device)
return prims._uniform_helper(shape, low=low, high=high, dtype=dtype, device=device)
@register_decomposition(aten.masked_fill)
@out_wrapper()
def masked_fill(a: TensorLikeType, mask: TensorLikeType, value: TensorOrNumberLikeType):
python_type = utils.dtype_to_type(a.dtype)
if isinstance(value, Number):
value_type = type(value)
else:
# NOTE: Could not use value = item(value) as it resulted in
# RuntimeError: Cannot cast FakeTensor(cpu) to number
value_ndim = value.ndim
torch._check(
value_ndim == 0,
lambda: f"only supports a 0-dimensional value tensor, but got tensor with {value_ndim} dimension",
)
# `masked_fill` allows cpu scalar to be moved to cuda, xpu and hpu but not otherwise.
is_cpu_scalar = (
a.device.type
in ["cuda", "xpu", torch._C._get_privateuse1_backend_name(), "hpu"]
and value.device.type == "cpu"
)
torch._check(
is_cpu_scalar or value.device == a.device,
lambda: "Expected `value` to be on same device as `a`",
)
value_type = utils.dtype_to_type(value.dtype)
if value_type is complex:
# only downcasting from complex to lower type is not allowed.
# We allow casting `value` to lower type for other case
# Eg. float -> int.
# Ref: https://github.com/pytorch/pytorch/issues/79195
torch._check(
utils.is_weakly_lesser_type(value_type, python_type),
lambda: f"could not convert to type {python_type} without overflow",
)
# Since `where` allows type-promotion,
# cast value to correct type before passing to `where`
value = _maybe_convert_to_dtype(value, a.dtype)
r = torch.where(mask, value, a) # type: ignore[arg-type]
# aten.mask_fill always return a new contiguous tensor
# contiguous() is needed to correctly model the output stride
return r.contiguous()
@register_decomposition(aten.masked_fill_)
def masked_fill_(
a: TensorLikeType, mask: TensorLikeType, value: TensorOrNumberLikeType
) -> TensorLikeType:
b = torch.masked_fill(a, mask, value) # type: ignore[arg-type]
a.copy_(b)
return a
# CompositeImplicitAutograd - don't register decomp
def allclose(
a: TensorLikeType,
b: TensorLikeType,
rtol: float = 1e-05,
atol: float = 1e-08,
equal_nan: bool = False,
) -> bool:
"""
Reference implementation of torch.allclose
"""
_check_close_args(name="torch.allclose", a=a, b=b, rtol=rtol, atol=atol)
return bool(
torch.all(torch.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)).item()
)
def equal(a: TensorLikeType, b: TensorLikeType) -> bool:
utils.check_same_device(a, b, allow_cpu_scalar_tensors=False)
utils.check_same_dtype(a, b)
# Shape check
if a.ndim != b.ndim:
return False
for x, y in zip(a.shape, b.shape):
if x != y:
return False
# Short-circuits if there are no elements to validate
if a.numel() == 0:
return True
return item(all(eq(a, b))) # type: ignore[return-value]
@register_decomposition(aten.norm)
@out_wrapper(exact_dtype=True)
def norm(
input: TensorLikeType,
p: Optional[Union[float, str]] = "fro",
dim: Optional[DimsType] = None,
keepdim: bool = False,
*,
dtype: Optional[torch.dtype] = None,
) -> TensorLikeType:
# In these cases we compute the "Frobenius norm"
if (
p == "fro" and (dim is None or isinstance(dim, Dim) or len(dim) <= 2)
) or p is None:
p = 2
if isinstance(dim, Dim):
dim = [dim]
if isinstance(p, str):
# Here we either call the nuclear norm, or we call matrix_norm with some arguments
# that will throw an error
if dim is None:
dim = tuple(range(input.ndim))
return torch.linalg.matrix_norm(input, p, dim, keepdim, dtype=dtype)
else:
return torch.linalg.vector_norm(input, p, dim, keepdim, dtype=dtype)
@register_decomposition(aten.trace)
@out_wrapper()
def trace(self: TensorLikeType) -> TensorLikeType:
torch._check(
self.ndim == 2, lambda: "expected a matrix, but got tensor with dim {self.ndim}"
)
return torch.sum(torch.diag(self, 0))
def _make_r_binary_op(base_op):
def rop(
a: Union[TensorLikeType, NumberType],
b: Union[TensorLikeType, NumberType],
) -> TensorLikeType:
return base_op(b, a)
return rop
rtruediv = _make_r_binary_op(true_divide)
rfloordiv = _make_r_binary_op(floor_divide)
rpow = _make_r_binary_op(pow)
@register_decomposition(aten.triu)
@out_wrapper()
def triu(a: TensorLikeType, diagonal: int = 0) -> TensorLikeType:
torch._check(
a.ndim >= 2, lambda: "triu: input tensor must have at least 2 dimensions"
)
h, w = a.shape[-2:]
mask = (
torch.arange(w, device=a.device).unsqueeze(-2)
- torch.arange(h, device=a.device).unsqueeze(-1)
) >= diagonal
# aten.triu always returns a new contiguous tensor
# contiguous() is needed to correctly model the output stride
return utils.mask_tensor(mask, a).contiguous()
@register_decomposition(aten.tril)
@out_wrapper()
def tril(a: TensorLikeType, diagonal: int = 0) -> TensorLikeType:
torch._check(
a.ndim >= 2, lambda: "tril: input tensor must have at least 2 dimensions"
)
h, w = a.shape[-2:]
mask = (
torch.arange(w, device=a.device).unsqueeze(-2)
- torch.arange(h, device=a.device).unsqueeze(-1)
) <= diagonal
# aten.tril always returns a new contiguous tensor
# contiguous() is needed to correctly model the output stride
return utils.mask_tensor(mask, a).contiguous()
# This is based on get_tril_size in aten/src/ATen/native/TensorFactories.h
# The components of the matrix that belong to the lower triangle with offset
# form a pentagon that can be broken down into a top trapezoid and a bottom
# rectangle. For the implementation of tril_indices, we need the sizes of
# both of these, as well as the length of the top side of the trapezoid.
def _get_tril_sizes(row: int, col: int, offset: int) -> Tuple[int, int, int]:
if row == 0 or col == 0:
return 0, 0, 0
m_first_row = min(col, 1 + offset) if offset > 0 else int(row + offset > 0)
m_last_row = max(0, min(col, row + offset))
n_row_all = max(0, min(row, row + offset))
n_row_trapezoid = m_last_row - m_first_row + 1
# Number of elements in top trapezoid
trapezoid_size = (m_first_row + m_last_row) * n_row_trapezoid // 2
# Number of elements in bottom rectangle
diff_row = n_row_all - n_row_trapezoid
rectangle_size = max(0, diff_row * col)
return trapezoid_size, rectangle_size, m_first_row
def _trilu_checks(
name: str,
row: int,
col: int,
dtype: torch.dtype,
layout: torch.layout,
pin_memory: bool,
):
torch._check(row >= 0, lambda: f"row must be non-negative, got {row}")
torch._check(col >= 0, lambda: f"col must be non-negative, got {col}")
torch._check(
dtype in (torch.int32, torch.int64),
lambda: f"\"{name}\" not implemented for '{dtype}'",
)
# This is based on tril_indices_cuda in aten/src/ATen/native/cuda/TensorFactories.cu
@register_decomposition(aten.tril_indices)
@out_wrapper()
def tril_indices(
row: int,
col: int,
offset: int = 0,
*,
dtype: torch.dtype = torch.long,
layout: torch.layout = torch.strided,
device: DeviceLikeType = "cpu",
pin_memory: bool = False,
) -> TensorLikeType:
_trilu_checks("tril_indices", row, col, dtype, layout, pin_memory)
trapezoid_size, rectangle_size, m_first_row = _get_tril_sizes(row, col, offset)
row_offset = max(0, -offset)
arange_kw = partial(
torch.arange, layout=layout, device=device, pin_memory=pin_memory
)
# first we do the indices for top trapezoid
xs1 = arange_kw(0, trapezoid_size, dtype=torch.float64)
b = m_first_row - 0.5
row_inds1 = torch.floor(-b + torch.sqrt(b * b + 2 * xs1))
col_inds1 = torch.floor(xs1 - (2 * m_first_row - 1 + row_inds1) * row_inds1 * 0.5)
row_inds1 = _maybe_convert_to_dtype(row_inds1 + row_offset, dtype)
col_inds1 = _maybe_convert_to_dtype(col_inds1, dtype)
# then bottom rectangle
xs2 = arange_kw(0, rectangle_size, dtype=dtype)
row_inds2 = xs2 // col + (col - m_first_row + 1 + row_offset)
col_inds2 = xs2 % col
return torch.stack(
(torch.cat((row_inds1, row_inds2)), torch.cat((col_inds1, col_inds2)))
)
# Similar to _get_tril_sizes above, but here there is a top trapezoid and
# a bottom rectangle instead. Note that you can't reduce this to
# _get_tril_sizes(col, row, -offset) because that would correspond to
# decomposing into a left trapezoid and right rectangle.
def _get_triu_sizes(row: int, col: int, offset: int) -> Tuple[int, int, int]:
if row == 0 or col == 0:
return 0, 0, 0
m_first_row = max(0, col - offset) if offset > 0 else col
# Number of elements in top rectangle
rectangle_size = max(0, min(row, -offset) * col)
# Number of elements in bottom trapezoid
trapezoid_size_tril, rectangle_size_tril, _ = _get_tril_sizes(row, col, offset - 1)
triu_size = row * col - (trapezoid_size_tril + rectangle_size_tril)
trapezoid_size = triu_size - rectangle_size
return trapezoid_size, rectangle_size, m_first_row
@register_decomposition(aten.triu_indices)
@out_wrapper()
def triu_indices(
row: int,
col: int,
offset: int = 0,
*,
dtype: torch.dtype = torch.long,
layout: torch.layout = torch.strided,
device: DeviceLikeType = "cpu",
pin_memory: bool = False,
) -> TensorLikeType:
_trilu_checks("triu_indices", row, col, dtype, layout, pin_memory)
trapezoid_size, rectangle_size, m_first_row = _get_triu_sizes(row, col, offset)
col_offset = max(0, offset)
arange_kw = partial(
torch.arange, layout=layout, device=device, pin_memory=pin_memory
)
# indices for top rectangle
xs2 = arange_kw(0, rectangle_size, dtype=dtype)
row_inds2 = xs2 // col
col_inds2 = xs2 % col
# bottom trapezoid
xs1 = arange_kw(0, trapezoid_size, dtype=torch.float64)
b = -0.5 - m_first_row
row_inds1 = torch.floor(-b - torch.sqrt(b * b - 2 * xs1))
col_inds1 = torch.floor(xs1 - ((2 * m_first_row - 1 - row_inds1) * row_inds1) * 0.5)
row_inds1 = _maybe_convert_to_dtype(row_inds1, dtype)
col_inds1 = _maybe_convert_to_dtype(col_inds1, dtype)
if col:
row_inds1 = row_inds1 + (rectangle_size // col)
col_inds1 = col_inds1 + col_offset
return torch.stack(
(torch.cat((row_inds2, row_inds1)), torch.cat((col_inds2, col_inds1)))
)
@register_decomposition(aten.bucketize)
@out_wrapper(exact_dtype=True)
def bucketize(
a: TensorOrNumberLikeType,
boundaries: TensorLikeType,
*,
out_int32: bool = False,
right: bool = False,
):
torch._check(
boundaries.dim() == 1,
lambda: f"boundaries tensor must be 1 dimension but got dim({boundaries.dim()})",
)
a = a if isinstance(a, torch.Tensor) else torch.tensor(a)
out_dtype = torch.int32 if out_int32 else torch.int64
n_boundaries = boundaries.shape[-1]
if n_boundaries == 0:
return torch.zeros_like(a)
# We are trying to find the bucket (defined by pairs of consecutive elements of `boundaries`)
# each element of `a` belongs to. We use binary search to achieve logarithimic complexity,
# but each step of the search is done "in parallel" over all elements of `a`
# can't use int32 as indexes, so we have to do all computations with int64 and convert at the end
start = torch.zeros(a.shape, device=a.device, dtype=torch.int64)
end = start + n_boundaries
# Max depth of the binary search
# Since we can't break out of the loop at different points for different elements of a,
# we just do the max amount of iterations that binary search requires and add condition
# tensor (cond_update below) to stop updating once the search terminates
# For first iteration through loop we can skip some checks, we have separate implementation
mid = start + (end - start) // 2
mid_val = boundaries[mid]
if right:
cond_mid = mid_val > a
else:
cond_mid = mid_val >= a
start = torch.where(cond_mid, start, mid + 1)
if n_boundaries > 1:
cond_update = torch.ones_like(a, dtype=torch.bool)
niters = int(math.log2(n_boundaries))
for _ in range(niters):
end = torch.where(cond_mid & cond_update, mid, end)
cond_update = start < end
# start might end up pointing to 1 past the end, we guard against that
mid = torch.where(cond_update, start + (end - start) // 2, 0)
mid_val = boundaries[mid]
# If right is true, the buckets are closed on the *left*
# (i.e., we are doing the equivalent of std::upper_bound in C++)
# Otherwise they are closed on the right (std::lower_bound)
if right:
cond_mid = mid_val > a
else:
cond_mid = mid_val >= a
start = torch.where((~cond_mid) & cond_update, mid + 1, start)
return start.to(dtype=out_dtype)
@register_decomposition(aten.cauchy)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("self",),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def cauchy(self, median=0, sigma=1, generator=None):
assert generator is None
torch._check(
not utils.is_complex_dtype(self.dtype)
and not utils.is_integer_dtype(self.dtype)
and not utils.is_boolean_dtype(self.dtype),
lambda: f"Cauchy distribution is a continuous probability distribution. \
dtype must be a floating point but you specified {self.dtype}",
)
torch._check(
sigma > 0.0,
lambda: f"cauchy_ expects sigma > 0.0, but found sigma={sigma}",
)
return median + sigma * torch.tan(math.pi * (torch.rand_like(self) - 0.5))
@register_decomposition(aten.exponential)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("self",),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def exponential(self, rate=1, generator=None):
assert generator is None
torch._check(
not utils.is_complex_dtype(self.dtype)
and not utils.is_integer_dtype(self.dtype)
and not utils.is_boolean_dtype(self.dtype),
lambda: f"Exponential distribution is a continuous probability distribution. \
dtype must be a floating point but you specified {self.dtype}",
)
torch._check(
rate > 0.0,
lambda: f"exponential_ expects lambda > 0.0, but found lambda={rate}",
)
uniform_val = torch.rand_like(self)
# copying numerics of transformation::exponential see comment:
# curand_uniform has (0,1] bounds. log(1) is 0 and exponential excludes 0.
# we need log to be not 0, and not underflow when converted to half
# fast __logf approximation can underflow, so set log to -epsilon/2 for 1 or close to 1 args
epsilon = torch.finfo(uniform_val.dtype).eps / 2
condition = uniform_val >= 1.0 - epsilon
log_uniform = torch.where(condition, -epsilon, torch.log(uniform_val))
return -1 / rate * log_uniform
@register_decomposition(aten.geometric)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("self",),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def geometric(self, p, generator=None):
assert generator is None
# TODO: fix inductor rand_like for integer, bool dtypes
torch._check(
not utils.is_complex_dtype(self.dtype)
and not utils.is_boolean_dtype(self.dtype),
lambda: f"geometric not implemented for {self.dtype}",
)
torch._check(
0 < p and p < 1,
lambda: f"geometric_ expects p to be in (0, 1), but got p={p}",
)
return torch.floor(torch.log1p(-torch.rand_like(self)) / math.log1p(-p)) + 1
@register_decomposition(aten.log_normal)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=("self",),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def log_normal(self, mean=1, std=2, generator=None):
assert generator is None
torch._check(
not utils.is_complex_dtype(self.dtype)
and not utils.is_integer_dtype(self.dtype)
and not utils.is_boolean_dtype(self.dtype),
lambda: f"log_normal not implemented for {self.dtype}",
)
torch._check(
0 < std,
lambda: f"log_normal_ expects std > 0.0, but found std={std}",
)
return torch.exp(std * torch.randn_like(self) + mean)
# TODO: add support for functionalization aten.normal_functional
# NOTE: the device and dtype will be ignored when shape is None
@register_decomposition(aten.normal)
@out_wrapper()
@elementwise_type_promotion_wrapper(
type_promoting_args=(
"mean",
"std",
),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def normal(
mean=0,
std=1,
size=None,
*,
generator=None,
dtype=None,
layout=None,
device=None,
pin_memory=None,
):
assert layout is None or layout == torch.strided
if not isinstance(std, TensorLike):
torch._check(
std >= 0, lambda: f"normal expects std >= 0.0, but found std {std}"
)
if size is None:
tensors = tuple(t for t in (mean, std) if isinstance(t, TensorLike))
torch._check(
len(tensors) > 0,
lambda: "normal expects that either mean or std is a tensor, or size is defined",
)
torch._check(
layout is None and pin_memory is None,
lambda: "Cannot pass layout, or pin_memory without size",
)
size = _broadcast_shapes(*(t.shape for t in tensors))
dtype = tensors[0].dtype
device = tensors[0].device
else:
torch._check(
not isinstance(mean, TensorLike) and not isinstance(std, TensorLike),
lambda: "normal expects mean and std to be scalars when size is defined",
)
dtype = torch.get_default_dtype() if dtype is None else dtype
device = torch.device("cpu") if device is None else device
normal_samples = prims.normal(
size,
mean=0.0,
std=1.0,
dtype=dtype,
device=device,
requires_grad=False,
generator=generator,
)
return std * normal_samples + mean
@register_decomposition(aten.normal_)
def normal_(self, mean=0, std=1, *, generator=None):
return normal(mean, std, self.shape, out=self, generator=generator)
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def rad2deg(self: TensorLikeType):
torch._check(
not utils.is_complex_dtype(self.dtype),
lambda: "rad2deg is not supported for complex tensors.",
)
M_180_PI = 57.295779513082320876798154814105170332405472466564
return self * M_180_PI
@_make_elementwise_unary_reference(ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT)
def deg2rad(self: TensorLikeType):
torch._check(
not utils.is_complex_dtype(self.dtype),
lambda: "deg2rad is not supported for complex tensors.",
)
M_PI_180 = 0.017453292519943295769236907684886127134428718885417
return self * M_PI_180
@register_decomposition(aten.count_nonzero)
@out_wrapper()
def count_nonzero(self, dim: Optional[DimsType] = None):
return (self != 0).sum(dim)
def _dot_check(self, other):
torch._check(
self.dim() == 1 and other.dim() == 1,
lambda: f"1D tensors expected, but got {self.dim()}D and {other.dim()}D tensors",
)
torch._check(
self.dtype == other.dtype,
lambda: "dot : expected both vectors to have same dtype, but found "
f"{self.dtype} and {other.dtype}",
)
def numel_error():
return (
f"inconsistent tensor size, expected tensor [{self.numel()}] and src [{other.numel()}] to have the"
f"same number of elements, but got {self.numel()} and {other.numel()} elements respectively"
)
torch._check(self.numel() == other.numel(), numel_error)
def _dot_check_wrapper(fn):
@wraps(fn)
def wrapper(self, other):
_dot_check(self, other)
return fn(self, other)
return wrapper
@register_decomposition(aten.dot)
@out_wrapper()
@_dot_check_wrapper
@elementwise_type_promotion_wrapper(
type_promoting_args=("self", "other"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def dot(self, other):
if self.is_complex():
if self.is_conj():
if other.is_conj():
return torch.dot(self.conj(), other.conj()).conj()
else:
return torch.vdot(self.conj(), other)
elif other.is_conj():
return torch.vdot(other.conj(), self)
return (self * other).sum()
@register_decomposition(aten.vdot)
@out_wrapper()
@_dot_check_wrapper
@elementwise_type_promotion_wrapper(
type_promoting_args=("self", "other"),
type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
)
def vdot(self, other):
if not self.is_complex():
return torch.dot(self, other)
if self.is_conj():
if other.is_conj():
return torch.vdot(other.conj(), self.conj())
else:
return torch.dot(self.conj(), other)
elif other.is_conj():
return torch.dot(self, other.conj()).conj()
# The decomposition fails if you do self.conj()... not sure why
return (self.conj_physical() * other).sum()
@register_decomposition(aten.select_scatter)
@out_wrapper()
def select_scatter(x: TensorLikeType, src: TensorLikeType, dim: int, index: int):
dim = utils.canonicalize_dim(x.ndim, dim)
mask_shape = [1] * x.ndim
mask_shape[dim] = -1
if index < 0:
index = index + x.shape[dim]
mask = torch.arange(x.shape[dim], device=x.device).view(mask_shape) == index
src = torch.unsqueeze(src, dim).expand(x.shape)
return torch.where(mask, src, x)
# inplace
abs_ = _make_inplace(abs)
acos_ = _make_inplace(acos)
acosh_ = _make_inplace(acosh)
add_ = _make_inplace(add)
addcmul_ = _make_inplace(addcmul)
addcdiv_ = _make_inplace(addcdiv)
asin_ = _make_inplace(asin)
asinh_ = _make_inplace(asinh)
atan_ = _make_inplace(atan)
atanh_ = _make_inplace(atanh)
atan2_ = _make_inplace(atan2)
bitwise_and_ = _make_inplace(bitwise_and)
bitwise_left_shift_ = _make_inplace(bitwise_left_shift)
bitwise_not_ = _make_inplace(bitwise_not)
bitwise_or_ = _make_inplace(bitwise_or)
bitwise_right_shift_ = _make_inplace(bitwise_right_shift)
bitwise_xor_ = _make_inplace(bitwise_xor)
ceil_ = _make_inplace(ceil)
clamp_ = _make_inplace(clamp)
clamp_min_ = _make_inplace(clamp_min)
clamp_max_ = _make_inplace(clamp_max)
conj_physical_ = _make_inplace(conj_physical)
copysign_ = _make_inplace(copysign)
cos_ = _make_inplace(cos)
cosh_ = _make_inplace(cosh)
cumsum_ = _make_inplace(cumsum)
cumprod_ = _make_inplace(cumprod)
deg2rad_ = _make_inplace(deg2rad)
digamma_ = _make_inplace(digamma)
div_ = _make_inplace(div)
eq_ = _make_inplace(eq)
erf_ = _make_inplace(erf)
erfc_ = _make_inplace(erfc)
erfinv_ = _make_inplace(erfinv)
exp_ = _make_inplace(exp)
exp2_ = _make_inplace(exp2)
expm1_ = _make_inplace(expm1)
float_power_ = _make_inplace(float_power)
floor_ = _make_inplace(floor)
floor_divide_ = _make_inplace(floor_divide)
fmod_ = _make_inplace(fmod)
frac_ = _make_inplace(frac)
gcd_ = _make_inplace(gcd)
ge_ = _make_inplace(ge)
gt_ = _make_inplace(gt)
heaviside_ = _make_inplace(heaviside)
hypot_ = _make_inplace(hypot)
igamma_ = _make_inplace(igamma)
igammac_ = _make_inplace(igammac)
i0_ = _make_inplace(i0)
lcm_ = _make_inplace(lcm)
le_ = _make_inplace(le)
lerp_ = _make_inplace(lerp)
lgamma_ = _make_inplace(lgamma)
log10_ = _make_inplace(log10)
log1p_ = _make_inplace(log1p)
log2_ = _make_inplace(log2)
log_ = _make_inplace(log)
logical_and_ = _make_inplace(logical_and)
logical_not_ = _make_inplace(logical_not)
logical_or_ = _make_inplace(logical_or)
logical_xor_ = _make_inplace(logical_xor)
lt_ = _make_inplace(lt)
mul_ = _make_inplace(mul)
mvlgamma_ = _make_inplace(mvlgamma)
nan_to_num_ = _make_inplace(nan_to_num)
ne_ = _make_inplace(ne)
neg_ = _make_inplace(neg)
nextafter_ = _make_inplace(nextafter)
pow_ = _make_inplace(pow)
rad2deg_ = _make_inplace(rad2deg)
reciprocal_ = _make_inplace(reciprocal)
remainder_ = _make_inplace(remainder)
rsqrt_ = _make_inplace(rsqrt)
sgn_ = _make_inplace(sgn)
sigmoid_ = _make_inplace(sigmoid)
sign_ = _make_inplace(sign)
sin_ = _make_inplace(sin)
sinc_ = _make_inplace(sinc)
sinh_ = _make_inplace(sinh)
sqrt_ = _make_inplace(sqrt)
square_ = _make_inplace(square)
sub_ = _make_inplace(sub)
tan_ = _make_inplace(tan)
tanh_ = _make_inplace(tanh)
tril_ = _make_inplace(tril)
triu_ = _make_inplace(triu)
true_divide_ = _make_inplace(true_divide)
trunc_ = _make_inplace(trunc)
xlogy_ = _make_inplace(xlogy)
cauchy_ = _make_inplace(cauchy)
exponential_ = _make_inplace(exponential)
geometric_ = _make_inplace(geometric)
log_normal_ = _make_inplace(log_normal)
zero_ = _make_inplace(zero)
alias_copy = _make_copy_from_view(aten.alias)
as_strided_copy = _make_copy_from_view(aten.as_strided)
diagonal_copy = _make_copy_from_view(aten.diagonal)
expand_copy = _make_copy_from_view(aten.expand)
# TODO: This must return a sparse tensor if the input is sparse, but refs have
# no sparse support. See narrow_copy_sparse in core.
narrow_copy = _make_copy_from_view(aten.narrow)
squeeze_copy = _make_copy_from_view(aten.squeeze)
permute_copy = _make_copy_from_view(aten.permute)
t_copy = _make_copy_from_view(aten.t)
transpose_copy = _make_copy_from_view(aten.transpose)
unsqueeze_copy = _make_copy_from_view(aten.unsqueeze)
view_copy = _make_copy_from_view(aten.view)
# xref: isStorage in torch/csrc/DynamicTypes.cpp
def _isStorage(obj):
return isinstance(obj, (torch.TypedStorage, torch.UntypedStorage))
# xref: compute_sizes in torch/csrc/utils/tensor_new.cpp
def _compute_sizes(seq, scalar_type):
MAX_DIMS = 128
is_storage = _isStorage(seq)
sizes = []
# TODO: this is inaccurate, we actually test PySequence_Check
while isinstance(seq, (list, tuple)):
length = len(seq)
if is_storage:
length //= scalar_type.itemsize
sizes.append(length)
if len(sizes) > MAX_DIMS:
raise ValueError(f"too many dimensions '{type(seq).__name__}'")
if length == 0:
break
try:
handle = seq[0]
except Exception:
raise ValueError( # noqa: B904
f"could not determine the shape of object type '{type(seq).__name__}'"
)
seq = handle
return sizes
# xref: infer_scalar_type in torch/csrc/utils/tensor_new.cpp
def _infer_scalar_type(obj):
if isinstance(obj, FloatLike):
return torch.get_default_dtype()
if isinstance(obj, IntLike) and not isinstance(obj, bool): # careful!
return torch.int64
if isinstance(obj, BoolLike):
return torch.bool
if isinstance(obj, complex):
default_dtype = torch.get_default_dtype()
if default_dtype is torch.float:
return torch.cfloat
elif default_dtype is torch.double:
return torch.cdouble
elif default_dtype is torch.half:
return torch.chalf
else:
raise RuntimeError("invalid default scalar type for complex")
if isinstance(obj, torch.Tensor):
return obj.dtype
if isinstance(obj, str):
raise TypeError(f"new(): invalid data type '{type(obj).__name__}'")
# TODO: this is inaccurate, we actually test PySequence_Check
if isinstance(obj, (list, tuple)):
scalarType = None
length = len(obj)
# match NumPy semantics, except use default tensor type instead of
# double.
if length == 0:
return torch.get_default_dtype()
for i in range(length):
cur_item = obj[i]
# TODO: test this
"""
if cur_item is obj:
raise TypeError("new(): self-referential lists are incompatible")
"""
item_scalarType = _infer_scalar_type(cur_item) # recurse!
if scalarType is not None:
scalarType = torch.promote_types(scalarType, item_scalarType)
else:
scalarType = item_scalarType
if scalarType is torch.cdouble:
# this won't change (unless we hit undefined, but that will
# fail later)
return scalarType
return scalarType
raise RuntimeError(f"Could not infer dtype of {type(obj).__name__}")
# Analogous to recursive_store
# xref: recursive_store in torch/csrc/utils/tensor_new.cpp
def _recursive_build(
scalarType: torch.dtype, obj: Union[TensorOrNumberLikeType, TensorSequenceType]
):
if isinstance(obj, Tensor) and obj.numel() == 1:
return obj.detach().to(dtype=scalarType, device="cpu", copy=True).view(())
elif isinstance(obj, Tensor):
# It is invalid to call ".tensor([...])" with a non-scalar tensor in eager mode
# >>> torch.tensor([torch.randn(2)])
# ValueError: only one element tensors can be converted to Python scalars
#
# But it is possible with a NumPy array
# >>> torch.tensor([np.random.uniform(size=(2,))]).shape
# torch.Size([1, 2])
return obj.detach().to(dtype=scalarType, device="cpu", copy=True)
elif isinstance(obj, Number):
return torch.scalar_tensor(obj, dtype=scalarType)
# seq can be a list of tensors
seq = obj
return torch.stack([_recursive_build(scalarType, item) for item in seq])
# xref: internal_new_from_data in torch/csrc/utils/tensor_new.cpp
def _internal_new_from_data(
options,
scalar_type,
device_opt,
data,
copy_variables,
copy_numpy,
type_inference,
pin_memory=False,
):
if isinstance(data, torch.Tensor):
torch._check(
not pin_memory, lambda: "Can't pin tensor constructed from a variable"
)
var = data
if copy_variables:
var = var.detach()
inferred_scalar_type = var.dtype if type_inference else scalar_type
device = device_opt if device_opt is not None else var.device
return var.to(
device=device,
dtype=inferred_scalar_type,
non_blocking=False,
copy=copy_variables,
)
# TODO
if hasattr(data, "__cuda_array_interface__"):
return NotImplemented
# TODO: test for numpy input with PyArray_Check
device = device_opt if device_opt is not None else options["device"]
inferred_scalar_type = _infer_scalar_type(data) if type_inference else scalar_type
# NB: Don't need to avoid tracing, as we aren't going to do any manual
# pointer filling tricks
if _isStorage(data):
return NotImplemented
else:
if torch.device(device).type == "meta":
return NotImplemented
# In the C implementation, we would directly start poking the memory
# of a freshly allocated CPU tensor. Here, we're going to do an
# alternate, heinously slow implementation: turn each individual
# scalar into a tensor, and then repeatedly cat them together
tensor = _recursive_build(inferred_scalar_type, data)
tensor = tensor.to(device, inferred_scalar_type, non_blocking=False, copy=False)
# NB: lift_fresh is not needed, because we built the tensor from scalars
# guaranteeing a fresh tensor in this case
return tensor
# xref: tensor_ctor in torch/csrc/utils/tensor_new.cpp
def tensor(data, *, dtype=None, device=None, pin_memory=False, requires_grad=False):
# TODO (or not): support names kwarg
if isinstance(data, torch.Tensor):
warnings.warn(
"To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() "
"or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor)"
)
type_inference = dtype is None
new_tensor = _internal_new_from_data(
# device="cpu" because that's what you get with torch.tensor(2) no
# device by default
{"device": "cpu"}, # TODO: use torch.get_default_tensor_type
dtype if dtype is not None else torch.get_default_dtype(),
device,
data,
copy_variables=True,
copy_numpy=True,
type_inference=type_inference,
pin_memory=pin_memory,
)
new_tensor.detach_()
if requires_grad:
new_tensor.requires_grad_(requires_grad)
return new_tensor
# Views
# We can't model these as above, as the pattern of doing `op(a, out=a)` does not work for a view function
# given that it does not reshape the input (it just copies the result into it)
# squeeze_ = _make_inplace(squeeze)
# t_ = _make_inplace(t)
# transpose_ = _make_inplace(transpose)
# unsqueeze_ = _make_inplace(unsqueeze)
import torch._refs._conversions
import torch._refs.fft
import torch._refs.linalg
import torch._refs.nn.functional
import torch._refs.special
|