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
|
# Owner(s): ["module: custom-operators"]
import collections
import itertools
import os
import re
import subprocess
import sys
import typing
import unittest
from typing import * # noqa: F403
import numpy as np
import torch._custom_ops as custom_ops
import torch.testing._internal.optests as optests
import torch.utils._pytree as pytree
import torch.utils.cpp_extension
from functorch import make_fx
from torch import Tensor
from torch._custom_op.impl import CustomOp, infer_schema
from torch._library.infer_schema import tuple_to_list
from torch._utils_internal import get_file_path_2 # @manual
from torch.testing._internal import custom_op_db
from torch.testing._internal.common_cuda import TEST_CUDA
from torch.testing._internal.common_device_type import (
instantiate_device_type_tests,
OpDTypes,
ops,
)
from torch.testing._internal.common_utils import (
instantiate_parametrized_tests,
IS_WINDOWS,
parametrize,
run_tests,
scoped_load_inline,
skipIfTorchDynamo,
subtest,
TestCase,
)
from torch.testing._internal.custom_op_db import numpy_nonzero
# Shadowed by `torch.testing._internal.common_utils.custom_op`
from torch._custom_op.impl import custom_op # usort: skip
def requires_compile(fun):
fun = unittest.skipIf(IS_WINDOWS, "torch.compile doesn't work with windows")(fun)
return fun
class CustomOpTestCaseBase(TestCase):
test_ns = "_test_custom_op"
def setUp(self):
super().setUp()
self.libraries = []
def tearDown(self):
super().tearDown()
import torch._custom_op
keys = list(torch._custom_op.impl.global_registry.keys())
for key in keys:
if not key.startswith(f"{self.test_ns}::"):
continue
torch._custom_op.impl.global_registry[key]._destroy()
if hasattr(torch.ops, self.test_ns):
delattr(torch.ops, self.test_ns)
for lib in self.libraries:
lib._destroy()
del self.libraries
def ns(self):
return getattr(torch.ops, self.test_ns)
def lib(self):
result = torch.library.Library(self.test_ns, "FRAGMENT") # noqa: TOR901
self.libraries.append(result)
return result
def get_op(self, qualname):
return torch._custom_op.impl.get_op(qualname)
@requires_compile
class TestCustomOpTesting(CustomOpTestCaseBase):
@parametrize("check_gradients", (False, "auto"))
@parametrize("dynamic", (True, False))
def test_aot_autograd_check_degenerate_cases(
self, device, dynamic, check_gradients
):
def simple(x):
return x.clone()
# Should not raise
x = torch.randn(3, device=device)
optests.aot_autograd_check(
simple, (x,), {}, dynamic=dynamic, check_gradients=check_gradients
)
def outputs_dont_require_grad(x):
return x.detach()
# Should not raise
y = torch.randn(3, device=device, requires_grad=True)
optests.aot_autograd_check(
simple, (y,), {}, dynamic=dynamic, check_gradients=check_gradients
)
def no_outputs(x):
return x.detach()
# Should not raise
x = torch.randn(3, device=device, requires_grad=True)
y = torch.randn(3, device=device, requires_grad=False)
optests.aot_autograd_check(
no_outputs, (x,), {}, dynamic=dynamic, check_gradients=check_gradients
)
optests.aot_autograd_check(
no_outputs, (y,), {}, dynamic=dynamic, check_gradients=check_gradients
)
def test_incorrect_schema_mutation(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
guard = torch._C._AutoDispatchBelowAutograd()
try:
return op(x)
finally:
del guard
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
x.sin_()
return x.clone()
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
x = torch.tensor(3.14159 / 3, requires_grad=True, device=device)
with self.assertRaisesRegex(
optests.OpCheckError, "Argument x is not defined as mutable but was mutated"
):
torch.library.opcheck(op, (x,), {})
def test_incorrect_schema_view(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
# Emulate AutoDispatchBelowADInplaceOrView, which is not bound into python
with torch._C._AutoDispatchBelowAutograd():
with torch._C._ExcludeDispatchKeyGuard(
torch._C.DispatchKeySet(torch._C.DispatchKey.ADInplaceOrView)
):
return op(x)
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
return x.view_as(x)
def foo_meta(x):
return x.view_as(x)
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_meta, "Meta")
x = torch.tensor(3.14159 / 3, requires_grad=True)
with self.assertRaisesRegex(
optests.OpCheckError,
"Argument x is not defined to alias output but was aliasing",
):
torch.library.opcheck(op, (x,), {})
def test_missing_abstract_impl(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
with torch._C._AutoDispatchBelowAutograd():
return op(x)
@staticmethod
def backward(ctx, gx):
return 2 * gx
def foo_impl(x):
return torch.tensor(x.cpu().numpy() ** 2, device=x.device)
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
x = torch.tensor([0, 1.0], requires_grad=True)
with self.assertRaisesRegex(
optests.OpCheckError,
"_test_custom_op.foo.default",
):
torch.library.opcheck(op, (x,), {})
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_incorrect_abstract_impl(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
# Emulate AutoDispatchBelowADInplaceOrView, which is not bound into python
guard = torch._C._AutoDispatchBelowAutograd()
guard2 = torch._C.ExcludeDispatchKeyGuard(
torch._C.DispatchKeySet(torch._C.DispatchKey.ADInplaceOrView)
)
try:
return op(x)
finally:
del guard
del guard2
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
return x**2
def foo_meta(x):
return x.unsqueeze(1) ** 2
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
lib.impl("foo", foo_meta, "Meta")
x = torch.tensor([0, 1.0], requires_grad=True)
with self.assertRaisesRegex(optests.OpCheckError, "Shapes .* are not equal"):
torch.library.opcheck(op, (x,), {})
def test_missing_functionalization(self, device):
lib = self.lib()
lib.define("foo(Tensor(a!) x) -> Tensor(a!)")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.mark_dirty(x)
with torch._C._AutoDispatchBelowAutograd():
return op(x)
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
return x.sin_()
def foo_meta(x):
return x
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
lib.impl("foo", foo_meta, "Meta")
x = torch.tensor([0, 1.0])
y = x.clone()
with self.assertRaisesRegex(
optests.OpCheckError,
"We only support functionalizing operators whose outputs do not have alias annotations",
):
torch.library.opcheck(op, (y,), {})
def test_autograd_registered_at_backend(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x.clone()
@staticmethod
def backward(ctx, gx):
return gx * 0.5
lib.impl("foo", Foo.apply, "CPU")
lib.impl("foo", Foo.apply, "CUDA")
lib.impl("foo", lambda x: x.clone(), "Meta")
x = torch.randn([], requires_grad=True)
with self.assertRaisesRegex(
torch.testing._internal.optests.OpCheckError,
"does not have an autograd kernel",
):
torch.library.opcheck(op, (x,), {})
# I'm not sure why this is necessary
del lib
def test_global_state_mutation(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
invoked = 0
@staticmethod
def forward(ctx, x):
Foo.invoked += 1
return x.clone() * Foo.invoked
@staticmethod
def backward(ctx, gx):
return gx
lib.impl("foo", Foo.apply, "CompositeImplicitAutograd")
x = torch.tensor(3.14159 / 3, requires_grad=True)
with self.assertRaisesRegex(
optests.OpCheckError, "eager-mode PyTorch vs AOTAutograd"
):
torch.library.opcheck(op, (x,), {})
@ops(custom_op_db.custom_op_db, dtypes=OpDTypes.any_one)
def test_opcheck_opinfo(self, device, dtype, op):
for sample_input in op.sample_inputs(
device, dtype, requires_grad=op.supports_autograd
):
args = [sample_input.input] + list(sample_input.args)
kwargs = sample_input.kwargs
torch.library.opcheck(op.op, args, kwargs)
def test_opcheck_fails_basic(self, device):
@custom_op(f"{self.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor: ...
@foo.impl(["cpu", "cuda"])
def foo_impl(x):
return x.sum()
x = torch.randn(3, device=device, requires_grad=True)
# Triggers the CustomOp autograd NYI error
with self.assertRaisesRegex(
optests.OpCheckError, "Autograd has not been implemented for operator"
):
torch.library.opcheck(self.get_op(f"{self.test_ns}::foo"), (x,), {})
def test_autograd_registration_check_autograd_kernel(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
with torch._C._AutoDispatchBelowAutograd():
return op(x)
@staticmethod
def backward(ctx, gx):
return gx
def foo_impl(x):
return x.sin()
lib.impl("foo", Foo.apply, "Autograd")
lib.impl("foo", foo_impl, "CPU")
lib.impl("foo", foo_impl, "CUDA")
x = torch.randn(3, requires_grad=True, device=device)
# Should not raise
optests.autograd_registration_check(op, (x,), {})
def test_autograd_registration_check_compositeimplicitautograd(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
def foo_impl(x):
return x.sin().cos()
lib.impl("foo", foo_impl, "CompositeImplicitAutograd")
x = torch.randn(3, requires_grad=True, device=device)
# Should not raise
optests.autograd_registration_check(op, (x,), {})
def test_autograd_registration_check_incorrect_composite(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
def foo_impl(x):
return x.sin().cos()
lib.impl("foo", foo_impl, "CompositeExplicitAutograd")
x = torch.randn(3, requires_grad=True, device=device)
with self.assertRaisesRegex(AssertionError, "incorrectly registered"):
optests.autograd_registration_check(op, (x,), {})
def test_autograd_registration_check_incorrect(self, device):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
op = self.ns().foo.default
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return torch.sin(x)
@staticmethod
def backward(ctx, gx):
return gx
lib.impl("foo", Foo.apply, "CPU")
lib.impl("foo", Foo.apply, "CUDA")
x = torch.randn(3, requires_grad=True, device=device)
with self.assertRaisesRegex(AssertionError, "incorrectly registered"):
optests.autograd_registration_check(op, (x,), {})
def test_assert_raises_regex(self, device):
from torch.testing._internal.optests.aot_autograd import assert_raises_regex
with assert_raises_regex(RuntimeError, "c"):
raise RuntimeError("abcd")
with assert_raises_regex(RuntimeError, "c.*"):
raise RuntimeError("abcd")
with self.assertRaisesRegex(AssertionError, "instead got"):
with assert_raises_regex(RuntimeError, "c.*"):
raise ValueError("abcd")
with self.assertRaisesRegex(AssertionError, "Expected exception"):
with assert_raises_regex(RuntimeError, "c.*"):
pass
with self.assertRaisesRegex(AssertionError, "to match regex"):
with assert_raises_regex(RuntimeError, "f"):
raise RuntimeError("abcd")
class TestCustomOp(CustomOpTestCaseBase):
test_ns = "_test_custom_op"
def test_deploy_interaction(self):
# run in a different process to avoid parallel issues when we monkeypatch torch._running_with_deploy
script = """
import torch
torch._running_with_deploy = lambda: True
# creating the library is a no-op, so you can DEF multiple times
m1 = torch.library.Library("mylib4392", "DEF") # noqa: TOR901
m2 = torch.library.Library("mylib4392", "DEF") # noqa: TOR901
m = torch.library.Library("aten", "FRAGMENT") # noqa: TOR901
# define is a no-op
m.define("foobarbaz9996(Tensor x) -> Tensor")
assert not hasattr(torch.ops.aten, "foobarbaz9996"), "m.define should have been a noop"
def sin_override(x):
raise AssertionError("m.impl should have been a noop")
# impl is a no-op
m.impl("sin", sin_override, "CompositeImplicitAutograd")
x = torch.randn(3)
y = torch.sin(x)
# should be a no-op
@torch.library.custom_op("mylib::foobar", mutates_args={})
def foobar(x: torch.Tensor) -> torch.Tensor:
return x.sin()
# should be a no-op
@foobar.register_fake
def _(x):
return torch.empty_like(x)
# should be a no-op
m2.define("foobarbaz9996(Tensor x) -> Tensor")
# should be a no-op
@torch.library.register_fake("mylib4392::foobarbaz9996")
def _(x):
return torch.empty_like(x)
"""
script = script.strip()
env = os.environ.copy()
try:
subprocess.check_output(
[sys.executable, "-c", script],
stderr=subprocess.STDOUT,
# On Windows, opening the subprocess with the default CWD makes `import torch`
# fail, so just set CWD to this script's directory
cwd=os.path.dirname(os.path.realpath(__file__)),
env=env,
)
except subprocess.CalledProcessError as e:
self.fail(msg=("Subprocess exception:\n" + e.output.decode("utf-8")))
@requires_compile
def test_functionalize_error(self):
with torch.library._scoped_library(self.test_ns, "FRAGMENT") as lib:
lib.define("foo(Tensor(a!) x) -> Tensor(a!)")
def foo(x):
return x.sin_()
lib.impl("foo", foo, "CompositeExplicitAutograd")
foo_op = self.get_op(f"{self.test_ns}::foo")
lib.define("bar(Tensor(a) x) -> Tensor(a)")
def bar(x):
return x.view(-1)
lib.impl("bar", bar, "CompositeExplicitAutograd")
bar_op = self.get_op(f"{self.test_ns}::bar")
msg = r".*We only support functionalizing operators whose outputs do not have alias annotations"
x = torch.randn(3)
@torch.compile(backend="aot_eager", fullgraph=True)
def f(x):
return foo_op(x)
@torch.compile(backend="aot_eager", fullgraph=True)
def g(x):
return bar_op(x)
with self.assertRaisesRegex(RuntimeError, msg):
f(x)
with self.assertRaisesRegex(RuntimeError, msg):
g(x)
def test_invalid_schemas(self):
# function schmea validation goes through torchgen, so this is just a
# basic test.
with self.assertRaisesRegex(AssertionError, "Invalid function schema: foo"):
custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo", "(")
def test_invalid_qualname(self):
with self.assertRaisesRegex(ValueError, "overload"):
custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo.Tensor", "() -> ()")
def test_name_must_match(self):
with self.assertRaisesRegex(ValueError, "to have name"):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def baz(x: Tensor) -> Tensor:
raise NotImplementedError
def test_unsupported_schemas(self):
with self.assertRaisesRegex(ValueError, "only supports functional"):
custom_ops.custom_op(
f"{TestCustomOp.test_ns}::foo", "(Tensor(a!) x) -> Tensor(a)"
)(foo)
with self.assertRaisesRegex(ValueError, "only supports functional"):
custom_ops.custom_op(
f"{TestCustomOp.test_ns}::foo", "(Tensor(a) x) -> Tensor(a)"
)(foo)
with self.assertRaisesRegex(ValueError, "only supports functional"):
custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo", "(Tensor x) -> ()")(
foo
)
with self.assertRaisesRegex(ValueError, "self"):
custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo", "(Tensor self) -> ()")(
foo
)
# Tests for the older custom_op API
def test_schema_matches_signature(self):
with self.assertRaisesRegex(ValueError, "signature to match"):
@custom_op(f"{TestCustomOp.test_ns}::blah", "(Tensor y) -> Tensor")
def blah(x):
pass
with self.assertRaisesRegex(ValueError, "signature to match"):
@custom_op(
f"{TestCustomOp.test_ns}::blah2", "(Tensor x, *, Tensor y) -> Tensor"
)
def blah2(x, y):
pass
with self.assertRaisesRegex(ValueError, "signature to match"):
@custom_op(
f"{TestCustomOp.test_ns}::blah3",
"(Tensor x, *, Tensor w, Tensor z) -> Tensor",
)
def blah3(x, *, y, z):
pass
with self.assertRaisesRegex(ValueError, "signature to match"):
@custom_op(
f"{TestCustomOp.test_ns}::blah4",
"(Tensor x, *, Tensor z, Tensor y) -> Tensor",
)
def blah4(x, *, y, z):
pass
with self.assertRaisesRegex(ValueError, "not supported"):
@custom_op(f"{TestCustomOp.test_ns}::blah5", "(Tensor x) -> Tensor")
def blah5(*args):
pass
with self.assertRaisesRegex(ValueError, "not supported"):
@custom_op(
f"{TestCustomOp.test_ns}::blah6", "(*, Tensor z, Tensor y) -> Tensor"
)
def blah6(**kwargs):
pass
with self.assertRaisesRegex(ValueError, "default arguments"):
@custom_op(
f"{TestCustomOp.test_ns}::blah7", "(Tensor x, *, Tensor y) -> Tensor"
)
def blah7(x=1, *, y):
pass
with self.assertRaisesRegex(ValueError, "default arguments"):
@custom_op(
f"{TestCustomOp.test_ns}::blah8", "(Tensor x, *, Tensor y) -> Tensor"
)
def blah8(x, *, y=1):
pass
# kwonly-arg works
@custom_op(
f"{TestCustomOp.test_ns}::blah9", "(Tensor x, *, Tensor y) -> Tensor"
)
def blah9(x, *, y):
pass
def test_infer_schema_no_return(self):
with self.assertRaisesRegex(
ValueError, "No return type annotation was provided. Please add one."
):
@torch.library.custom_op("mylib::foo", mutates_args={})
def foo(x: torch.Tensor, y: int):
return x * y
def test_infer_schema_supported(self):
def a(x: Tensor) -> Tensor:
return torch.empty([])
self.assertExpectedInline(
infer_schema(a, mutates_args=()), """(Tensor x) -> Tensor"""
)
def kwonly1(x: Tensor, *, y: int, z: float) -> Tensor:
return torch.empty([])
self.assertExpectedInline(
infer_schema(kwonly1, mutates_args=()),
"""(Tensor x, *, SymInt y, float z) -> Tensor""",
)
def kwonly2(*, y: Tensor) -> Tensor:
return torch.empty([])
self.assertExpectedInline(
infer_schema(kwonly2, mutates_args=()), """(*, Tensor y) -> Tensor"""
)
def b(
x: Tensor,
y: int,
z: bool,
a: float,
b: torch.dtype,
c: torch.device,
d: torch.types.Number,
) -> Tuple[Tensor, int, float, bool]:
return torch.empty([]), 1, 0.1, True
self.assertExpectedInline(
infer_schema(b, mutates_args=()),
"""(Tensor x, SymInt y, bool z, float a, ScalarType b, Device c, Scalar d) -> (Tensor, SymInt, float, bool)""",
)
def c(
x: Tensor,
y: Sequence[Tensor],
z: Optional[Tensor],
w: Sequence[Optional[Tensor]],
) -> List[Tensor]:
return [torch.empty([])]
self.assertExpectedInline(
infer_schema(c, mutates_args=()),
"""(Tensor x, Tensor[] y, Tensor? z, Tensor?[] w) -> Tensor[]""",
)
def d(x: Tensor) -> Tuple[List[Tensor], Tensor]:
return [torch.empty([])], torch.empty([])
self.assertExpectedInline(
infer_schema(d, mutates_args=()), """(Tensor x) -> (Tensor[], Tensor)"""
)
def e() -> Tensor:
return torch.empty([])
self.assertExpectedInline(infer_schema(e, mutates_args=()), """() -> Tensor""")
def f(x: Tensor) -> None:
pass
self.assertExpectedInline(
infer_schema(f, mutates_args=()), """(Tensor x) -> ()"""
)
def g(
x: Tensor, y: List[Tensor], z: List[Tensor], w: List[Optional[Tensor]]
) -> None:
pass
self.assertExpectedInline(
infer_schema(g, mutates_args=()),
"""(Tensor x, Tensor[] y, Tensor[] z, Tensor?[] w) -> ()""",
)
self.assertExpectedInline(
infer_schema(g, mutates_args={"x", "w", "z"}),
"""(Tensor(a0!) x, Tensor[] y, Tensor(a2!)[] z, Tensor(a3!)?[] w) -> ()""",
)
self.assertExpectedInline(
infer_schema(g, mutates_args="unknown"),
"""(Tensor(a0!) x, Tensor(a1!)[] y, Tensor(a2!)[] z, Tensor(a3!)?[] w) -> ()""",
)
def h(
x: Tensor,
a: Optional[int] = None,
b: float = 3.14,
c: bool = True,
d: int = 3,
e: str = "foo",
f: torch.dtype = torch.float,
g: torch.dtype = torch.float32,
h: torch.dtype = torch.int,
i: torch.device = torch.device("cpu:0"),
j: torch.device = "cpu",
) -> None:
pass
self.assertExpectedInline(
infer_schema(h, mutates_args=()),
(
"""(Tensor x, SymInt? a=None, float b=3.14, bool c=True, SymInt d=3, str e="foo", """
"""ScalarType f=float32, ScalarType g=float32, ScalarType h=int32, Device i="cpu:0", Device j="cpu") -> ()"""
),
)
def foo_impl(x: torch.Tensor) -> torch.Tensor:
return x.sin()
schema = torch.library.infer_schema(foo_impl, op_name="myop", mutates_args={})
self.assertExpectedInline(schema, "myop(Tensor x) -> Tensor")
def test_infer_schema_unsupported(self):
with self.assertRaisesRegex(ValueError, "varargs"):
def foo(*args):
raise NotImplementedError
infer_schema(foo, mutates_args=())
with self.assertRaisesRegex(ValueError, "varkwargs"):
def foo(**kwargs):
raise NotImplementedError
infer_schema(foo, mutates_args=())
with self.assertRaisesRegex(ValueError, "must have a type annotation"):
def foo(x):
raise NotImplementedError
infer_schema(foo, mutates_args=())
with self.assertRaisesRegex(ValueError, "unsupported"):
def foo(x: Tensor) -> Tuple[Tensor, ...]:
raise NotImplementedError
infer_schema(foo, mutates_args=())
with self.assertRaisesRegex(ValueError, "can be mutated"):
def foo(x: Tensor, y: int) -> Tensor:
raise NotImplementedError
infer_schema(foo, mutates_args={"y"})
def _generate_examples(self, typ):
if typ is int:
return [17]
if typ is float:
return [3.14]
if typ is bool:
return [True]
if typ is str:
return ["foo"]
if typ is torch.dtype:
return [torch.float32]
if typ is torch.device:
return [torch.device("cpu")]
if typ == torch.types.Number:
return [2.718]
if typ is torch.Tensor:
return [torch.tensor(3)]
if typ == Optional[torch.types.Number]:
return [None, 2.718]
origin = typing.get_origin(typ)
if origin is Union:
args = typing.get_args(typ)
assert len(args) == 2 and (args[0] is type(None) or args[1] is type(None))
elt = args[0] if args[1] is type(None) else args[1]
return self._generate_examples(elt) + [None]
if origin is list:
args = typing.get_args(typ)
assert len(args) == 1
elt = args[0]
return [
self._generate_examples(elt),
self._generate_examples(elt),
self._generate_examples(elt),
]
if origin is collections.abc.Sequence:
args = typing.get_args(typ)
assert len(args) == 1
examples = self._generate_examples(args[0])
return list(itertools.product(examples, examples)) + []
raise NotImplementedError(
f"testrunner cannot generate instanstance of type {typ}"
)
def test_supported_return_types_single_return(self):
for typ in torch._library.infer_schema.SUPPORTED_RETURN_TYPES:
for example in self._generate_examples(typ):
try:
@custom_ops.custom_op(f"{self.test_ns}::foo")
def foo(x: Tensor) -> typ:
raise NotImplementedError
@custom_ops.impl(f"{self.test_ns}::foo")
def foo_impl(x: Tensor) -> typ:
return example
op = self.get_op(f"{self.test_ns}::foo")
result = op(torch.randn([]))
self.assertEqual(result, example, msg=f"{typ} {example}")
finally:
custom_ops._destroy(f"{self.test_ns}::foo")
def test_supported_return_types_multi_return(self):
for typ in torch._library.infer_schema.SUPPORTED_RETURN_TYPES:
for example in self._generate_examples(typ):
try:
@custom_ops.custom_op(f"{self.test_ns}::foo")
def foo(x: Tensor) -> Tuple[typ, typ]:
raise NotImplementedError
@custom_ops.impl(f"{self.test_ns}::foo")
def foo_impl(x: Tensor) -> Tuple[typ, typ]:
return (example, example)
op = self.get_op(f"{self.test_ns}::foo")
result = op(torch.randn([]))
expected = (example, example)
self.assertEqual(result, expected, msg=f"{typ} {example}")
finally:
custom_ops._destroy(f"{self.test_ns}::foo")
def test_supported_param_types(self):
for typ in torch._library.infer_schema.SUPPORTED_PARAM_TYPES:
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: Tensor, y: typ) -> Tensor:
raise NotImplementedError
yeet = None
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo", device_types=["cpu"])
def foo_cpu(x, y):
nonlocal yeet
yeet = y
return x.clone()
try:
for example in self._generate_examples(typ):
op = self.get_op(f"{self.test_ns}::foo")
op(torch.randn([]), example)
self.assertEqual(yeet, example, msg=f"{typ} {example}")
yeet = None
finally:
custom_ops._destroy(f"{TestCustomOp.test_ns}::foo")
def test_sequences(self):
# Sequence[int] gets automagically turned into int[] in the schema.
# This test checks that we actually do support arbitrary sequence types.
class MySequence(collections.abc.Sequence):
def __init__(self) -> None:
self._container = [1, 2, 3]
def __getitem__(self, idx):
return self._container[idx]
def __len__(self):
return len(self._container)
@custom_ops.custom_op(f"{self.test_ns}::foo")
def foo(x: torch.Tensor, sizes: Sequence[int]) -> torch.Tensor:
raise NotImplementedError
called = 0
@custom_ops.impl(f"{self.test_ns}::foo", device_types="cpu")
def foo_cpu(x, sizes):
nonlocal called
called += 1
# Dispatcher will normalize the sequence type into a List
self.assertEqual(sizes, [1, 2, 3])
return x.clone()
x = torch.randn([])
seq = MySequence()
op = self.get_op(f"{self.test_ns}::foo")
op(x, seq)
self.assertEqual(called, 1)
def test_unsupported_param_types(self):
# Not comprehensive (it doesn't need to be), just a check that our mechanism works
with self.assertRaisesRegex(ValueError, "unsupported type"):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: Tensor, y: List[Optional[int]]) -> Tensor:
raise NotImplementedError
del foo
with self.assertRaisesRegex(ValueError, "unsupported type"):
# int[N] in Dispatcher is a bit wild, so we don't try to support it.
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: Tensor, y: Tuple[int, int]) -> Tensor:
raise NotImplementedError
del foo
with self.assertRaisesRegex(ValueError, r"For example, typing.List\[int\]"):
# test that we propose a correct and supported type.
@torch.library.custom_op(f"{TestCustomOp.test_ns}::foo", mutates_args={})
def foo(x: Tensor, y: Tuple[int, int]) -> Tensor:
raise NotImplementedError
del foo
with self.assertRaises(ValueError) as cm:
@torch.library.custom_op(f"{TestCustomOp.test_ns}::foo", mutates_args={})
def foo(x: Tensor, y: Tuple[int, float]) -> Tensor:
raise NotImplementedError
del foo
self.assertNotIn("example", str(cm.exception), "")
with self.assertRaisesRegex(ValueError, "unsupported type"):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: Tensor, y: Callable) -> Tensor:
raise NotImplementedError
del foo
def test_supported_schemas(self):
# All of these should already be tested by PyTorch codegen
# (we share the same mechanism), but here's a sanity check.
schemas = [
"(Tensor x) -> Tensor",
"(Tensor x) -> Tensor y",
"(Tensor[] x) -> Tensor y",
"(Tensor x) -> (Tensor, Tensor)",
"(Tensor x) -> (Tensor y, Tensor z)",
"(Tensor x) -> (Tensor y, Tensor z)",
]
other_schemas = [
"(Tensor x, Tensor w) -> (Tensor y, Tensor z)",
"(Tensor x, Tensor w) -> (Tensor, Tensor)",
"(Tensor x, Tensor w) -> Tensor",
"(Tensor? x, Tensor w) -> Tensor",
"(Tensor? x, Tensor[] w) -> Tensor",
"(Tensor x, int[] w) -> Tensor",
"(Tensor x, SymInt[] w) -> Tensor",
"(Tensor x, Scalar w) -> Tensor",
"(Tensor x, float w) -> Tensor",
"(Tensor x, float? w) -> Tensor",
"(Tensor x, bool[] w) -> Tensor",
]
for schema in schemas:
custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo", schema)
custom_ops._destroy(f"{TestCustomOp.test_ns}::foo")
for schema in other_schemas:
custom_ops.custom_op(f"{TestCustomOp.test_ns}::bar", schema)
custom_ops._destroy(f"{TestCustomOp.test_ns}::bar")
def test_reserved_ns(self):
from torch._custom_op.impl import RESERVED_NS
for ns in RESERVED_NS:
with self.assertRaisesRegex(ValueError, "is a reserved namespace"):
custom_ops.custom_op(f"{ns}::foo", "(Tensor x) -> Tensor")
with self.assertRaisesRegex(ValueError, "is a reserved namespace"):
@custom_ops.custom_op(f"{ns}::foo2")
def foo2(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
def test_private_ctor(self):
with self.assertRaisesRegex(RuntimeError, "CustomOp constructor is private"):
CustomOp(None, None, None, None, None)
def test_lifetime(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
custom_op = torch._custom_op.impl.get_op(f"{TestCustomOp.test_ns}::foo")
# We can't define an op multiple times,
with self.assertRaisesRegex(RuntimeError, "multiple times"):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor: # noqa: F811
raise NotImplementedError
# Unless we delete the original op.
custom_ops._destroy(f"{TestCustomOp.test_ns}::foo")
# Smoke test
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor: # noqa: F811
raise NotImplementedError
custom_ops._destroy(f"{TestCustomOp.test_ns}::foo")
def test_autograd_notimplemented(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor: # noqa: F811
raise NotImplementedError
x = torch.randn(3, requires_grad=True)
op = self.get_op(f"{self.test_ns}::foo")
with self.assertRaisesRegex(RuntimeError, "Autograd has not been implemented"):
op(x)
custom_ops._destroy(f"{TestCustomOp.test_ns}::foo")
del foo
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: Sequence[torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
x = torch.randn(3, requires_grad=True)
y = torch.randn(3)
op = self.get_op(f"{self.test_ns}::foo")
with self.assertRaisesRegex(RuntimeError, "Autograd has not been implemented"):
op([y, x])
custom_ops._destroy(f"{TestCustomOp.test_ns}::foo")
del foo
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
x = torch.randn(3, requires_grad=True)
y = torch.randn(3)
op = self.get_op(f"{self.test_ns}::foo")
with self.assertRaisesRegex(RuntimeError, "Autograd has not been implemented"):
op(y, x)
custom_ops._destroy(f"{TestCustomOp.test_ns}::foo")
def test_autograd_notimplemented_gradmode(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x, y):
return x * y
x = torch.randn(3, requires_grad=True)
y = torch.randn(3)
op = self.get_op(f"{self.test_ns}::foo")
with torch.no_grad():
# Shouldn't raise, because we are in no_grad
op(y, x)
def test_impl_cpu(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo", device_types="cpu")
def foo_cpu(x):
return x.sin()
x = torch.randn(3)
op = self.get_op(f"{self.test_ns}::foo")
result = op(x)
self.assertEqual(result, foo_cpu(x))
def test_impl_invalid_devices(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
def foo_impl(x):
return x.sin()
from torch._custom_op.impl import SUPPORTED_DEVICE_TYPE_TO_KEY
for device_type in SUPPORTED_DEVICE_TYPE_TO_KEY.keys():
# Smoke test: should not raise error
custom_ops.impl(f"{TestCustomOp.test_ns}::foo", device_types=device_type)(
foo_impl
)
# Not supported by this API: we can either support them in the future
# or provide some other CustomOp.def_* function. This depends on how
# common the use cases are.
for invalid_type in ["hip", "xla", "mkldnn", ["cpu", "hip"]]:
with self.assertRaisesRegex(ValueError, "we only support device_type"):
custom_ops.impl(
f"{TestCustomOp.test_ns}::foo", device_types=invalid_type
)(foo_impl)
def test_backward_partially_registered(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x):
return x.sin()
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return grad * saved.cos()
x = torch.randn([], requires_grad=True)
op = self.get_op(f"{self.test_ns}::foo")
with self.assertRaisesRegex(
RuntimeError, "unable to find a 'save_for_backward'"
):
y = op(x)
y.backward()
def test_save_for_backward_inputs_are_namedtuple(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x):
return x.sin()
hit = 0
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
nonlocal hit
hit += 1
self.assertTrue(isinstance(inputs, tuple))
self.assertEqual(list(inputs._asdict().keys()), ["x"])
return inputs.x
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return {"x": grad * saved.cos()}
x = torch.randn([], requires_grad=True)
op = self.get_op(f"{self.test_ns}::foo")
y = op(x)
self.assertEqual(hit, 1)
y.backward()
self.assertEqual(hit, 1)
def test_backward_returns_dict(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x):
return x.sin()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return inputs.x
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return grad * saved.cos()
x = torch.randn([], requires_grad=True)
op = self.get_op(f"{self.test_ns}::foo")
y = op(x)
with self.assertRaisesRegex(RuntimeError, "to be a dict"):
y.backward()
def test_backward_dict_invalid_keys(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x):
return x.sin()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return inputs.x
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return {"x": grad * saved.cos(), "y": None}
x = torch.randn([], requires_grad=True)
op = self.get_op(f"{self.test_ns}::foo")
y = op(x)
with self.assertRaisesRegex(RuntimeError, "to have keys {'x'}"):
y.backward()
def test_backward_dict_grad_for_nontensor(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor, dim: int) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x, dim):
return x.sin()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return inputs.x
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return {"x": grad * saved.cos(), "dim": None}
x = torch.randn([], requires_grad=True)
op = self.get_op(f"{self.test_ns}::foo")
y = op(x, 32)
with self.assertRaisesRegex(RuntimeError, "non-Tensor-like types"):
y.backward()
def test_backward_dict_requires_keys_for_input_tensors(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x, y):
return x.sin()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return inputs.x
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return {"x": grad * saved.cos()}
x = torch.randn([], requires_grad=True)
op = self.get_op(f"{self.test_ns}::foo")
y = op(x, x)
with self.assertRaisesRegex(RuntimeError, r"to have keys {.*'y'.*}"):
y.backward()
def test_backward_dict_requires_keys_for_input_optional_tensors(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor, y: Optional[torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x, y):
return x.sin()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return inputs.x
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return {"x": grad * saved.cos()}
x = torch.randn([], requires_grad=True)
op = self.get_op(f"{self.test_ns}::foo")
y = op(x, None)
with self.assertRaisesRegex(RuntimeError, r"to have keys {.*'y'.*}"):
y.backward()
def test_backward_grads_are_tensor_or_none(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x):
return x.sin()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return inputs.x
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return {"x": (grad * saved.cos(),)}
x = torch.randn([], requires_grad=True)
op = self.get_op(f"{self.test_ns}::foo")
y = op(x)
with self.assertRaisesRegex(RuntimeError, "either None or a Tensor"):
y.backward()
def test_backward_tensorlist_input_requires_list_grads_with_same_numel(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(xs: Sequence[torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(xs):
return xs[0].sin()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return inputs.xs[0]
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return {"xs": [grad * saved.cos(), None]}
xs = [torch.randn([], requires_grad=True) for _ in range(3)]
op = self.get_op(f"{self.test_ns}::foo")
y = op(xs)
with self.assertRaisesRegex(RuntimeError, "3 gradients but got 2"):
y.backward()
def test_backward_tensorlist_input_requires_list_grads_none_or_Tensor(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(xs: Sequence[torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(xs):
return xs[0].sin()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return inputs.xs[0]
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return {"xs": [grad * saved.cos(), None, (None,)]}
xs = [torch.randn([], requires_grad=True) for _ in range(3)]
op = self.get_op(f"{self.test_ns}::foo")
y = op(xs)
with self.assertRaisesRegex(RuntimeError, "None or Tensor"):
y.backward()
def test_backward_tensorlist_input_requires_list_grads(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(xs: Sequence[torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(xs):
return xs[0].sin()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return inputs.xs[0]
@custom_ops.impl_backward(f"{TestCustomOp.test_ns}::foo")
def foo_backward(ctx, saved, grad):
return {"xs": None}
xs = [torch.randn([], requires_grad=True) for _ in range(3)]
op = self.get_op(f"{self.test_ns}::foo")
y = op(xs)
with self.assertRaisesRegex(RuntimeError, "list of gradients"):
y.backward()
def test_backward_output_differentiability_type(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(xs: Sequence[torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
with self.assertRaisesRegex(RuntimeError, "output_differentiability"):
@custom_ops.impl_backward(
f"{TestCustomOp.test_ns}::foo", output_differentiability=True
)
def foo_backward(ctx, saved, grad):
return {"xs": None}
def test_backward_output_differentiability_numel(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(xs: Sequence[torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
raise NotImplementedError
with self.assertRaisesRegex(RuntimeError, "output_differentiability"):
@custom_ops.impl_backward(
f"{TestCustomOp.test_ns}::foo", output_differentiability=[True]
)
def foo_backward(ctx, saved, grad):
return {"xs": None}
def test_backward_output_differentiability_tensorlist(self):
@custom_ops.custom_op(f"{self.test_ns}::foo")
def foo(x: Tensor) -> Tuple[List[Tensor], Tensor]:
raise NotImplementedError
@custom_ops.impl(f"{self.test_ns}::foo")
def foo_impl(x):
return [x.clone(), x.clone()], x.clone()
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return []
@custom_ops.impl_backward(
f"{TestCustomOp.test_ns}::foo", output_differentiability=[False, True]
)
def foo_backward(ctx, saved, grad_lst, grad):
return {"x": grad}
op = self.get_op(f"{self.test_ns}::foo")
x = torch.randn(3, requires_grad=True)
[a, b], c = op(x)
self.assertFalse(a.requires_grad)
self.assertFalse(b.requires_grad)
self.assertTrue(c.requires_grad)
def test_backward_output_differentiability_non_tensor(self):
@custom_ops.custom_op(f"{self.test_ns}::foo")
def foo(x: Tensor) -> Tuple[Tensor, int]:
raise NotImplementedError
@custom_ops.impl(f"{self.test_ns}::foo")
def foo_impl(x):
return x.clone(), 3
@custom_ops.impl_save_for_backward(f"{TestCustomOp.test_ns}::foo")
def foo_save_for_backward(inputs, output):
return []
@custom_ops.impl_backward(
f"{TestCustomOp.test_ns}::foo", output_differentiability=[True, True]
)
def foo_backward(ctx, saved, grad0, grad1):
return {"x": grad0}
op = self.get_op(f"{self.test_ns}::foo")
x = torch.randn(3, requires_grad=True)
with self.assertRaisesRegex(RuntimeError, "is not a Tensor"):
op(x)
@unittest.skipIf(not TEST_CUDA, "requires CUDA")
def test_impl_separate(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo", device_types="cpu")
def foo_cpu(x):
return x.sin()
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo", device_types="cuda")
def foo_cuda(x):
return x.cos()
x = torch.randn(3)
op = self.get_op(f"{self.test_ns}::foo")
result = op(x)
self.assertEqual(result, foo_cpu(x))
x_cuda = x.cuda()
op = self.get_op(f"{self.test_ns}::foo")
result = op(x_cuda)
self.assertEqual(result, foo_cuda(x_cuda))
@unittest.skipIf(not TEST_CUDA, "requires CUDA")
def test_impl_multiple(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@custom_ops.impl(f"{TestCustomOp.test_ns}::foo")
def foo_impl(x):
return x.cos()
op = self.get_op(f"{self.test_ns}::foo")
x = torch.randn(3)
result = op(x)
self.assertEqual(result, foo_impl(x))
x_cuda = x.cuda()
result = op(x_cuda)
self.assertEqual(result, foo_impl(x_cuda))
def test_impl_abstract_overload(self):
lib = self.lib()
lib.define("sin.blah(Tensor x) -> Tensor")
torch.library.impl_abstract(
f"{self.test_ns}::sin.blah", torch.empty_like, lib=lib
)
op = self.ns().sin.blah
x = torch.randn(3, device="meta")
op(x)
def test_impl_meta(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor, dim: int) -> torch.Tensor:
raise NotImplementedError
@torch.library.impl_abstract(f"{TestCustomOp.test_ns}::foo", lib=self.lib())
def foo_meta(x, dim):
output_shape = list(x.shape)
del output_shape[dim]
return x.new_empty(output_shape)
x = torch.randn(2, 3, device="meta")
op = self.get_op(f"{self.test_ns}::foo")
result = op(x, 1)
self.assertEqual(result.shape, foo_meta(x, 1).shape)
def test_duplicate_impl(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor, dim: int) -> torch.Tensor:
raise NotImplementedError
@torch.library.impl_abstract(f"{TestCustomOp.test_ns}::foo", lib=self.lib())
def foo_meta(x, dim):
output_shape = list(x.shape)
del output_shape[dim]
return x.new_empty(output_shape)
with self.assertRaisesRegex(RuntimeError, r"test_custom_ops.py:\d+"):
@torch.library.impl_abstract(f"{TestCustomOp.test_ns}::foo", lib=self.lib())
def foo_meta2(x, dim):
output_shape = list(x.shape)
del output_shape[dim]
return x.new_empty(output_shape)
def test_new_data_dependent_symint(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@torch.library.impl_abstract(f"{TestCustomOp.test_ns}::foo", lib=self.lib())
def foo_meta(x):
ctx = torch.library.get_ctx()
r = ctx.new_dynamic_size(min=1)
with self.assertRaisesRegex(ValueError, "greater than or equal to 0"):
ctx.new_dynamic_size(min=-1)
with self.assertRaisesRegex(ValueError, "SymInt"):
ctx.new_dynamic_size(max=x.numel())
# NB: You must return dynamic sizes!
return x.new_empty(r)
x = torch.randn(2, 3, device="cpu")
op = self.get_op(f"{self.test_ns}::foo")
make_fx(op, tracing_mode="symbolic")(x)
def test_meta_for_data_dependent_shape_operation(self):
x = torch.randn(10, device="meta")
with self.assertRaisesRegex(RuntimeError, "data-dependent shape"):
numpy_nonzero(x)
def test_basic_make_fx(self):
# More serious tests are in our CustomOp opinfo db,
# this one is just a sanity check.
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@torch.library.impl_abstract(f"{TestCustomOp.test_ns}::foo", lib=self.lib())
def foo_meta(x):
return x.sum()
x = torch.randn(3)
op = self.get_op(f"{self.test_ns}::foo")
gm = make_fx(op, tracing_mode="symbolic")(x)
self.assertTrue(f"{TestCustomOp.test_ns}.foo" in gm.code)
def test_not_implemented_error(self):
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::foo")
def foo(x: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
x = torch.randn(3)
op = self.get_op(f"{self.test_ns}::foo")
with self.assertRaisesRegex(NotImplementedError, "cpu impl registered"):
op(x)
x = torch.randn(3, device="meta")
with self.assertRaisesRegex(NotImplementedError, "no fake impl or Meta kernel"):
op(x)
@custom_ops.custom_op(f"{TestCustomOp.test_ns}::bar")
def bar(sizes: Sequence[int]) -> torch.Tensor:
raise NotImplementedError
op = self.get_op(f"{self.test_ns}::bar")
with self.assertRaisesRegex(NotImplementedError, "no Tensor inputs"):
op((1, 2, 3))
def test_data_dependent_basic(self):
x = torch.randn(5, 5)
gm = make_fx(numpy_nonzero, tracing_mode="symbolic")(x)
self.assertTrue("nonzero" in gm.code)
def test_data_dependent_fake_tracing(self):
x = torch.randn(5, 5)
# We've updated to attempt to use unbacked symints even for fake
# tracing
make_fx(numpy_nonzero, tracing_mode="fake")(x)
def test_symints(self):
def f(x):
return torch.ops._torch_testing.numpy_view_copy(x, x.shape)
x = torch.randn(2, 3, 4)
gm = make_fx(f, tracing_mode="symbolic")(x)
result = gm(x)
self.assertEqual(result, f(x))
self.assertExpectedInline(
gm.code.strip(),
"""\
def forward(self, x_1):
sym_size_int = torch.ops.aten.sym_size.int(x_1, 0)
sym_size_int_1 = torch.ops.aten.sym_size.int(x_1, 1)
sym_size_int_2 = torch.ops.aten.sym_size.int(x_1, 2)
numpy_view_copy = torch.ops._torch_testing.numpy_view_copy.default(x_1, [sym_size_int, sym_size_int_1, sym_size_int_2]); x_1 = sym_size_int = sym_size_int_1 = sym_size_int_2 = None
return numpy_view_copy""", # noqa: B950
)
@unittest.skipIf(IS_WINDOWS, "torch.compile doesn't work on windows")
def test_data_dependent_compile(self):
import torch._dynamo.testing
from torch._dynamo.utils import counters
counters.clear()
cnt = torch._dynamo.testing.CompileCounter()
@torch.compile(backend=cnt)
def f(x):
return numpy_nonzero(x.clone()).clone()
f(torch.randn(10))
self.assertEqual(len(counters["graph_break"]), 1)
self.assertEqual(next(iter(counters["graph_break"].values())), 1)
self.assertExpectedInline(
next(iter(counters["graph_break"].keys())).replace(";", "\n"),
"""\
dynamic shape operator: _torch_testing.numpy_nonzero.default
to enable, set torch._dynamo.config.capture_dynamic_output_shape_ops = True""",
)
# pre-existing problem: torch.compile(dynamic=True) will, by default,
# graph break on data-dependent operations. Eventually we'll make it so
# that it never graph breaks on data-dependent operations.
@unittest.expectedFailure
def test_data_dependent_nms_dynamic_compile(self):
import torch._dynamo.testing
from torch._dynamo.utils import counters
counters.clear()
cnt = torch._dynamo.testing.CompileCounter()
@torch.compile(backend=cnt, dynamic=True)
def f(x, s, i):
return torch.ops._torch_testing.numpy_nms(x.clone(), s, i).clone()
f(torch.randn(20, 4), torch.randn(20), 0.1)
self.assertEqual(len(counters["graph_break"]), 0)
def test_impl_on_existing_op(self):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
qualname = f"{self.test_ns}::foo"
@torch._custom_ops.impl(qualname)
def foo_impl(x):
return x.sin()
op = self.get_op(qualname)
x = torch.randn(3)
result = op(x)
self.assertEqual(result, x.sin())
@parametrize(
"key", ["CPU", "CUDA", "CompositeImplicitAutograd", "CompositeExplicitAutograd"]
)
def test_impl_on_existing_op_with_cpu_registration(self, key):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
qualname = f"{self.test_ns}::foo"
def foo_impl(x):
return x.sin()
lib.impl("foo", foo_impl, key)
op = self.get_op(qualname)
with self.assertRaisesRegex(RuntimeError, "already has an implementation"):
custom_ops.impl(qualname, func=foo_impl)
def test_abstract_impl_on_existing_op(self):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
qualname = f"{self.test_ns}::foo"
@torch.library.impl_abstract(qualname, lib=self.lib())
def foo_impl(x):
return x.sin()
op = self.get_op(qualname)
with torch._subclasses.FakeTensorMode():
x = torch.randn(3)
result = op(x)
self.assertEqual(result.shape, x.shape)
self.assertEqual(result.stride(), x.stride())
def test_abstract_impl_on_existing_op_with_meta(self):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
qualname = f"{self.test_ns}::foo"
def foo_impl(x):
return x.sin()
lib.impl("foo", foo_impl, "Meta")
op = self.get_op(qualname)
with self.assertRaisesRegex(RuntimeError, r"already has .*Meta implementation"):
torch.library.impl_abstract(qualname, func=foo_impl, lib=self.lib())
def test_abstract_impl_on_existing_op_with_CompositeImplicitAutograd(self):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
qualname = f"{self.test_ns}::foo"
def foo_impl(x):
return x.sin()
lib.impl("foo", foo_impl, "CompositeImplicitAutograd")
op = self.get_op(qualname)
with self.assertRaisesRegex(RuntimeError, "CompositeImplicitAutograd"):
torch.library.impl_abstract(qualname, func=foo_impl, lib=self.lib())
def test_abstract_impl_on_existing_op_with_CompositeExplicitAutograd(self):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
qualname = f"{self.test_ns}::foo"
def foo_impl(x):
return x.sin()
lib.impl("foo", foo_impl, "CompositeExplicitAutograd")
op = self.get_op(qualname)
torch.library.impl_abstract(qualname, func=lambda x: x.sum(), lib=self.lib())
with torch._subclasses.FakeTensorMode():
x = torch.randn(10)
result = op(x)
self.assertEqual(result.shape, ())
def _test_backward_impl_raises(self, qualname, err_regex):
with self.assertRaisesRegex(RuntimeError, err_regex):
@custom_ops.impl_save_for_backward(qualname)
def foo2(x):
return
with self.assertRaisesRegex(RuntimeError, err_regex):
@custom_ops.impl_backward(qualname)
def foo3(x):
return
def test_backward_impl_on_existing_op_incorrect_schema_views(self):
lib = self.lib()
lib.define("foo(Tensor(a) x) -> Tensor(a)")
qualname = f"{self.test_ns}::foo"
self._test_backward_impl_raises(qualname, "operator that returns views")
def test_backward_impl_on_existing_op_incorrect_schema_mutable(self):
lib = self.lib()
lib.define("foo(Tensor(a!) x) -> Tensor")
qualname = f"{self.test_ns}::foo"
self._test_backward_impl_raises(qualname, "non-functional")
def test_backward_impl_on_existing_op_incorrect_schema_no_output(self):
lib = self.lib()
lib.define("foo(Tensor x) -> ()")
qualname = f"{self.test_ns}::foo"
self._test_backward_impl_raises(qualname, "no returns")
def test_backward_impl_on_existing_op_CompositeImplicitAutograd(self):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
qualname = f"{self.test_ns}::foo"
lib.impl("foo", lambda x: x.sin().cos(), "CompositeImplicitAutograd")
self._test_backward_impl_raises(qualname, "CompositeImplicitAutograd")
@parametrize("key", ["Autograd", "AutogradCPU", "AutogradCUDA"])
def test_backward_impl_on_existing_op_with_key(self, key):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
qualname = f"{self.test_ns}::foo"
lib.impl("foo", lambda x: x.sin().cos(), key)
self._test_backward_impl_raises(qualname, key)
def test_is_functional_schema(self):
tests = {
"foo(Tensor x) -> Tensor": True,
"foo(Tensor(a) x) -> Tensor": True,
"foo(Tensor(a!) x) -> Tensor": False,
"foo(Tensor(a) x) -> Tensor(a)": False,
"foo(Tensor x) -> ()": False,
}
for schema_str, expected in tests.items():
res = torch._library.utils.is_functional_schema(schema_str)
self.assertEqual(res, expected)
from torchgen.model import FunctionSchema
schema = FunctionSchema.parse(schema_str)
res = torch._library.utils.is_functional_schema(schema)
self.assertEqual(res, expected)
schema = torch._C.parse_schema(schema_str)
res = torch._library.utils.is_functional_schema(schema)
self.assertEqual(res, expected)
def test_incorrect_schema_types(self):
with torch.library._scoped_library("mylib", "FRAGMENT") as lib:
with self.assertRaisesRegex(RuntimeError, "unknown type specifier"):
lib.define("foo12(Tensor a) -> asdfasdf")
with self.assertRaisesRegex(RuntimeError, "unknown type specifier"):
lib.define("foo12(asdf a) -> Tensor")
with self.assertRaisesRegex(RuntimeError, "Use `SymInt` or `int`"):
lib.define("foo12(int64_t a) -> Tensor")
with self.assertRaisesRegex(RuntimeError, "Use `float`"):
lib.define("foo12(double a) -> Tensor")
def test_is_tensorlist_like_type(self):
tensorlists = [
# Tensor[]
torch.ops.aten.where.default._schema.returns[0].type,
# Tensor?[]
torch.ops.aten.index.Tensor._schema.arguments[1].type,
# Tensor[]?
torch._C.parse_schema("foo(Tensor[]? x) -> ()").arguments[0].type,
# Tensor?[]?
torch._C.parse_schema("foo(Tensor?[]? x) -> ()").arguments[0].type,
]
non_tensorlists = [
# Tensor
torch.ops.aten.sin.default._schema.arguments[0].type,
# IntList
torch.ops.aten.sum.dim_IntList._schema.arguments[1].type,
]
for a in tensorlists:
self.assertTrue(torch._library.utils.is_tensorlist_like_type(a))
for a in non_tensorlists:
self.assertFalse(torch._library.utils.is_tensorlist_like_type(a))
def test_backward_impl_on_existing_op(self):
lib = self.lib()
lib.define("foo(Tensor x) -> Tensor")
qualname = f"{self.test_ns}::foo"
@custom_ops.impl(qualname)
def foo_impl(x):
with torch.no_grad():
return x.sin()
@custom_ops.impl_save_for_backward(qualname)
def foo_save_for_backward(inputs, output):
return inputs.x
@custom_ops.impl_backward(qualname)
def foo_backward(ctx, saved, grad_out):
return {"x": grad_out * saved.cos()}
op = self.get_op(qualname)
x = torch.randn([], requires_grad=True)
y = op(x)
(gx,) = torch.autograd.grad(y, x)
self.assertEqual(gx, x.cos())
@parametrize(
"tags",
[
subtest(torch.Tag.pointwise, "single"),
subtest((torch.Tag.pointwise,), "tuple"),
subtest([torch.Tag.pointwise], "list"),
],
)
def test_define_with_tags(self, tags):
lib = self.lib()
tags = (torch.Tag.pointwise,)
torch.library.define(
f"{self.test_ns}::foo", "(Tensor x) -> Tensor", lib=lib, tags=tags
)
actual = self.ns().foo.default.tags
self.assertTrue(isinstance(actual, list))
self.assertEqual(actual, list(tags))
def test_builtin_aten_ops_are_pt2_compliant(self):
for op in [torch.ops.aten.sin.default, torch.ops.aten.sum.dim_IntList]:
self.assertIn(torch.Tag.pt2_compliant_tag, op.tags)
def test_builtin_torchscript_ops(self):
for op in [torch.ops.aten.sub.complex, torch.ops.aten.mul.complex]:
self.assertIn(torch.Tag.pt2_compliant_tag, op.tags)
def test_autogen_aten_ops_are_pt2_compliant(self):
for op in [torch.ops.aten.fill.Tensor_out]:
self.assertIn(torch.Tag.generated, op.tags)
self.assertIn(torch.Tag.pt2_compliant_tag, op.tags)
def test_resolve_packet(self):
x = torch.randn(3)
result = torch._C._jit_resolve_packet("aten::sum", x)
self.assertEqual(result, "default")
result = torch._C._jit_resolve_packet("aten::sum", x, dim=1)
self.assertEqual(result, "dim_IntList")
with self.assertRaisesRegex(RuntimeError, "failed to match any schema"):
result = torch._C._jit_resolve_packet("aten::sum", x, x, x)
def test_define_bad_schema(self):
lib = self.lib()
with self.assertRaisesRegex(ValueError, "expected schema to look like"):
torch.library.define(f"{self.test_ns}::foo", "foo(Tensor x) -> Tensor")
def test_define_and_impl(self):
lib = self.lib()
torch.library.define(f"{self.test_ns}::foo", "(Tensor x) -> Tensor", lib=lib)
@torch.library.impl(f"{self.test_ns}::foo", "CPU", lib=lib)
def f(x):
return torch.from_numpy(np.sin(x.numpy()))
x = torch.randn(3)
y = self.ns().foo(x)
assert torch.allclose(y, x.sin())
def test_define_validation(self):
with self.assertRaisesRegex(ValueError, "namespace"):
torch.library.define("foo", "(Tensor x) -> Tensor")
def test_legacy_define(self):
lib = self.lib()
@torch.library.define(lib, "foo(Tensor x) -> Tensor")
def f(x):
return torch.from_numpy(np.sin(x.numpy()))
x = torch.randn(3)
y = self.ns().foo(x)
assert torch.allclose(y, x.sin())
def test_impl_function(self):
lib = self.lib()
torch.library.define(f"{self.test_ns}::foo", "(Tensor x) -> Tensor", lib=lib)
def f(x):
return torch.from_numpy(np.sin(x.numpy()))
torch.library.impl(f"{self.test_ns}::foo", "CPU", f, lib=lib)
x = torch.randn(3)
y = self.ns().foo(x)
assert torch.allclose(y, x.sin())
def test_legacy_impl(self):
lib = self.lib()
torch.library.define(f"{self.test_ns}::foo", "(Tensor x) -> Tensor", lib=lib)
@torch.library.impl(lib, "foo", "CPU")
def f(x):
return torch.from_numpy(np.sin(x.numpy()))
x = torch.randn(3)
y = self.ns().foo(x)
assert torch.allclose(y, x.sin())
def test_defined_in_python(self):
self.assertFalse(torch.ops.aten.sin.default._defined_in_python)
self.assertFalse(torch.ops.aten.sum.dim_IntList._defined_in_python)
lib = self.lib()
torch.library.define("{self._test_ns}::foo", "(Tensor x) -> Tensor", lib=lib)
ns = self.ns()
self.assertTrue(ns.foo.default._defined_in_python)
torch.library.define(
"{self._test_ns}::bar.overload", "(Tensor x) -> Tensor", lib=lib
)
self.assertTrue(ns.bar.overload._defined_in_python)
def _test_impl_device(self, name, types, device):
lib = self.lib()
torch.library.define(f"{self.test_ns}::{name}", "(Tensor x) -> Tensor", lib=lib)
@torch.library.impl(f"{self.test_ns}::{name}", types)
def f(x):
x_np = x.cpu().numpy()
y = torch.from_numpy(np.sin(x_np))
return y.to(device=x.device)
x = torch.randn(3, device=device)
y = getattr(self.ns(), name)(x)
assert torch.allclose(y, x.sin())
def test_impl_device_cpu(self):
self._test_impl_device("foo1", "default", "cpu")
self._test_impl_device("foo2", ["cpu"], "cpu")
self._test_impl_device("foo3", ["cpu", "cuda"], "cpu")
@unittest.skipIf(not TEST_CUDA, "requires cuda")
def test_impl_device_cuda(self):
self._test_impl_device("foo4", "default", "cuda")
self._test_impl_device("foo5", ["cuda"], "cuda")
self._test_impl_device("foo6", ["cpu", "cuda"], "cuda")
def test_impl_device_function(self):
lib = self.lib()
torch.library.define(f"{self.test_ns}::foo", "(Tensor x) -> Tensor", lib=lib)
def f(x):
x_np = x.cpu().numpy()
y = torch.from_numpy(np.sin(x_np))
return y.to(device=x.device)
torch.library.impl(f"{self.test_ns}::foo", "default", f, lib=lib)
x = torch.randn(3)
y = self.ns().foo(x)
assert torch.allclose(y, x.sin())
def test_impl_device_invalid(self):
with self.assertRaisesRegex(RuntimeError, "Expected one of cpu, cuda"):
torch.library.impl("blah::blah", "somethingsomething")
@scoped_load_inline
def test_autograd_function_backed_op(self, load_inline):
cpp_source = """
struct CustomOpAutogradFunction : public torch::autograd::Function<CustomOpAutogradFunction> {
static constexpr bool is_traceable = true;
static torch::Tensor forward(
torch::autograd::AutogradContext* ctx,
const torch::Tensor& x) {
return x;
}
static torch::autograd::variable_list backward(
torch::autograd::AutogradContext *ctx,
torch::autograd::variable_list grad_output) {
return grad_output;
}
};
torch::Tensor custom_op_backed_by_autograd_fn(const torch::Tensor& x) {
return CustomOpAutogradFunction::apply(x);
}
TORCH_LIBRARY(test_autograd_function_backed_op, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
}
"""
module = load_inline(
name="test_autograd_function_backed_op",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
x = torch.ones(2, 2, requires_grad=True)
temp = x.detach().clone()
out = (
torch.ops.test_autograd_function_backed_op.custom_op_backed_by_autograd_fn(
x
)
)
loss = out.sum()
loss.backward()
self.assertEqual(x.grad, temp)
def op_with_incorrect_schema(testcase, name):
lib = testcase.lib()
lib.define(f"{name}(Tensor x) -> Tensor")
qualname = f"{testcase.test_ns}::{name}"
lib.impl(name, lambda x: x[:], "CompositeExplicitAutograd")
return testcase.get_op(qualname)
class MiniOpTest(CustomOpTestCaseBase):
test_ns = "mini_op_test"
def _init_op_delayed_backward_error(self):
name = "delayed_error"
qualname = f"{self.test_ns}::{name}"
lib = self.lib()
lib.define(f"{name}(Tensor x) -> Tensor")
lib.impl(name, lambda x: x.clone(), "CompositeExplicitAutograd")
op = self.get_op(qualname)
class Op(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
with torch._C._AutoDispatchBelowAutograd():
return op(x)
@staticmethod
def backward(ctx, grad):
raise NotImplementedError
def autograd_impl(x):
return Op.apply(x)
lib.impl(name, autograd_impl, "Autograd")
return op
def _init_op_with_no_abstract_impl(self):
name = "no_abstract"
qualname = f"{self.test_ns}::{name}"
lib = self.lib()
lib.define(f"{name}(Tensor x) -> Tensor", tags=(torch.Tag.pt2_compliant_tag,))
lib.impl(name, lambda x: x.clone(), "CPU")
return torch._library.utils.lookup_op(qualname)
def setUp(self):
super().setUp()
self._op_with_no_abstract_impl = self._init_op_with_no_abstract_impl()
self._op_delayed_backward_error = self._init_op_delayed_backward_error()
@optests.dontGenerateOpCheckTests("Testing this API")
def test_dont_generate(self):
op = op_with_incorrect_schema(self, "incorrect_schema")
x = torch.randn(3)
op(x)
def test_mm(self):
x = torch.randn(2, 3, requires_grad=True)
y = torch.randn(3, 5)
result = torch.ops.aten.mm.default(x, y)
self.assertEqual(result, x @ y)
def test_mm_meta(self):
x = torch.randn(2, 3, requires_grad=True, device="meta")
y = torch.randn(3, 5, device="meta")
result = torch.ops.aten.mm.default(x, y)
self.assertEqual(result.shape, (x @ y).shape)
def test_mm_fake(self):
with torch._subclasses.fake_tensor.FakeTensorMode():
x = torch.randn(2, 3, requires_grad=True, device="cpu")
y = torch.randn(3, 5, device="cpu")
result = torch.ops.aten.mm.default(x, y)
self.assertEqual(result.shape, (x @ y).shape)
def test_mm_errors(self):
x = torch.randn(2, 3, requires_grad=True)
y = torch.randn(4, 5)
with self.assertRaisesRegex(RuntimeError, "cannot be multiplied"):
result = torch.ops.aten.mm.default(x, y)
def test_nonzero(self):
x = torch.tensor([0, 1, 2, 0, 0])
y = torch.ops.aten.nonzero.default(x)
self.assertEqual(y, torch.tensor([[1], [2]]))
def test_inplace(self):
x = torch.randn(3)
x_clone = x.clone()
y = torch.ops.aten.sin_(x)
self.assertEqual(x, x_clone.sin())
def test_incorrect_schema(self):
op = op_with_incorrect_schema(self, "incorrect_schema")
x = torch.randn(3)
op(x)
def test_no_abstract(self):
op = self._op_with_no_abstract_impl
x = torch.randn(3)
op(x)
def test_delayed_error(self):
op = self._op_delayed_backward_error
x = torch.randn([], requires_grad=True)
y = op(x)
with self.assertRaises(NotImplementedError):
y.sum().backward()
def test_delayed_error_no_requires_grad(self):
op = self._op_delayed_backward_error
x = torch.randn([])
y = op(x)
class TestCustomOpAPI(TestCase):
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_basic(self):
@torch.library.custom_op("_torch_testing::add", mutates_args=())
def add(x: Tensor, y: float) -> Tensor:
x_np = x.numpy(force=True)
out_np = x_np + y
return torch.from_numpy(out_np).to(x.device)
x = torch.randn(3)
y = 3.14
z = add(x, y)
self.assertEqual(z, x + y)
cpu_called = False
@add.register_kernel("cpu")
def _(x, y):
nonlocal cpu_called
cpu_called = True
x_np = x.numpy()
out_np = x_np + y
return torch.from_numpy(out_np)
z = add(x, y)
self.assertEqual(z, x + y)
self.assertTrue(cpu_called)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_no_grad_skips_autograd(self):
@torch.library.custom_op("_torch_testing::add", mutates_args=())
def add(x: Tensor, y: float) -> Tensor:
x_np = x.numpy(force=True)
out_np = x_np + y
return torch.from_numpy(out_np).to(x.device)
called = 0
def setup_context(ctx, inputs, output):
nonlocal called
called += 1
def backward(ctx, grad):
raise AssertionError("should not be reached")
add.register_autograd(backward, setup_context=setup_context)
x = torch.randn(3, requires_grad=True)
with torch.no_grad():
y = add(x, 2.0)
self.assertEqual(called, 0)
self.assertEqual(y, x + 2.0)
x.requires_grad_(False)
y = add(x, 2.0)
self.assertEqual(called, 0)
self.assertEqual(y, x + 2.0)
x = torch.randn(3, requires_grad=True)
y = add(x, 2.0)
self.assertEqual(called, 1)
self.assertEqual(y, x + 2.0)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_manual_schema(self):
@torch.library.custom_op(
"_torch_testing::add",
mutates_args=(),
schema="(Tensor x, float y) -> Tensor",
)
def add(x, y):
x_np = x.numpy(force=True)
out_np = x_np + y
return torch.from_numpy(out_np).to(x.device)
x = torch.randn(3)
y = 3.14
z = add(x, y)
self.assertEqual(z, x + y)
@torch.library.custom_op(
"_torch_testing::sin_",
mutates_args=["x"],
schema="(Tensor(a!) x) -> ()",
)
def sin_(x):
x_np = x.numpy()
np.sin(x_np, out=x_np)
x = torch.randn(3)
expected = x.sin()
sin_(x)
self.assertEqual(x, expected)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_kwarg_only_tensors(self):
with self.assertRaisesRegex(NotImplementedError, "kwarg-only Tensor args"):
@torch.library.custom_op("_torch_testing::foo", mutates_args=())
def foo(x: Tensor, *, y: int, z: Tensor) -> Tensor:
pass
with self.assertRaisesRegex(NotImplementedError, "kwarg-only Tensor args"):
@torch.library.custom_op("_torch_testing::foo", mutates_args=())
def foo2(x: Tensor, *, y: int, z: Optional[Tensor]) -> Tensor:
pass
with self.assertRaisesRegex(NotImplementedError, "kwarg-only Tensor args"):
@torch.library.custom_op("_torch_testing::foo", mutates_args=())
def foo3(x: Tensor, *, y: int, z: List[Tensor]) -> Tensor:
pass
with torch.library._scoped_library("_torch_testing", "FRAGMENT") as lib:
lib.define("foo(Tensor x, *, Tensor y) -> Tensor")
with self.assertRaisesRegex(NotImplementedError, "kwarg-only Tensor args"):
torch.library.register_autograd(
"_torch_testing::foo",
lambda grad: grad,
setup_context=lambda ctx, inputs, keyword_only_inputs, output: None,
)
with self.assertRaisesRegex(NotImplementedError, "kwarg-only Tensor args"):
torch.library.register_vmap(
"_torch_testing::foo",
lambda info, in_dims, x, *, y: (x, 0),
)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_register_autograd_kwargonly_low_level(self):
with torch.library._scoped_library("_torch_testing", "FRAGMENT") as lib:
lib.define("foo(Tensor x, *, float y) -> Tensor")
called = False
def foo_impl(x, *, y):
return x * y
lib.impl("foo", foo_impl, "CPU")
def backward(ctx, grad):
nonlocal called
called = True
return grad * ctx.y
def setup_context(ctx, inputs, keyword_only_inputs, output):
assert tuple(keyword_only_inputs.keys()) == ("y",)
ctx.y = keyword_only_inputs["y"]
torch.library.register_autograd(
"_torch_testing::foo", backward, setup_context=setup_context, lib=lib
)
x = torch.randn(3, requires_grad=True)
torch.ops._torch_testing.foo(x, y=3.14).sum().backward()
self.assertTrue(called)
self.assertEqual(x.grad, torch.tensor([3.14, 3.14, 3.14]))
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_register_autograd_defaults(self):
with torch.library._scoped_library("_torch_testing", "FRAGMENT") as lib:
lib.define("foo(Tensor w, int x = 2, *, int y = 3, int z) -> Tensor")
def foo_impl(w, x=2, *, y=3, z):
return w * x * y * z
lib.impl("foo", foo_impl, "CPU")
called = False
def backward(ctx, grad):
nonlocal called
called = True
return grad * ctx.c
def setup_context(ctx, inputs, keyword_only_inputs, output):
assert len(inputs) == 2
assert inputs[1] == 2
assert keyword_only_inputs == {"y": 3, "z": 42}
ctx.c = keyword_only_inputs["y"] * keyword_only_inputs["z"] * inputs[1]
torch.library.register_autograd(
"_torch_testing::foo", backward, setup_context=setup_context, lib=lib
)
w = torch.randn(3, requires_grad=True)
torch.ops._torch_testing.foo(w, z=42).sum().backward()
self.assertTrue(called)
self.assertEqual(w.grad, torch.full_like(w, 2 * 3 * 42))
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_manual_schema_error(self):
with self.assertRaisesRegex(ValueError, "the op mutates {'x'}"):
@torch.library.custom_op(
"_torch_testing::sin_",
mutates_args=(),
schema="(Tensor(a!) x) -> ()",
)
def sin_(x):
x_np = x.numpy()
np.sin(x_np, out=x_np)
def test_supports_tensorlist(self):
@torch._library.autograd.supports_tensorlist
class Stack(torch.autograd.Function):
@staticmethod
def forward(ctx, xs):
ctx.num_xs = len(xs)
return torch.stack(xs)
@staticmethod
def backward(ctx, grad):
expected = ([True] * ctx.num_xs,)
self.assertEqual(ctx.needs_input_grad, expected)
return list(grad.unbind(0))
# call two applys, do a backward on the first
def t():
return torch.randn([], requires_grad=True)
xs0 = [t(), t(), t()]
xs1 = [t(), t(), t(), t()]
y0 = Stack.apply(xs0)
y1 = Stack.apply(xs1)
grads = torch.autograd.grad(y0.sum(), xs0)
self.assertEqual(grads, [torch.tensor(1.0) for _ in range(3)])
# call one apply, do multiple backwards
xs = [t(), t(), t()]
y = Stack.apply(xs)
_ = torch.autograd.grad(y.sum(), xs, retain_graph=True)
_ = torch.autograd.grad(y.sum(), xs, retain_graph=True)
grads = torch.autograd.grad(y.sum(), xs, retain_graph=True)
self.assertEqual(grads, [torch.tensor(1.0) for _ in range(3)])
# error: on access forward, backward directly
with self.assertRaisesRegex(NotImplementedError, "Function.forward directly"):
Stack.forward(None, xs)
with self.assertRaisesRegex(NotImplementedError, "Function.backward directly"):
Stack.backward(None, xs)
# the recursive case
@torch._library.autograd.supports_tensorlist
class Foo(torch.autograd.Function):
@staticmethod
def forward(ctx, xs):
if len(xs) > 1:
return Foo.apply(xs[1:])
ctx.len_xs = len(xs)
return xs[0].sin()
@staticmethod
def backward(ctx, grad):
result = [None] * ctx.len_xs
result[-1] = grad.cos()
return result
# should work
result = Foo.apply(xs)
expected = xs[-1].sin()
self.assertEqual(result, expected)
# recursive on backward
@torch._library.autograd.supports_tensorlist
class Bar(torch.autograd.Function):
@staticmethod
def forward(ctx, xs):
return [xs[i] + i for i in range(len(xs))]
@staticmethod
def backward(ctx, grads):
f1 = Bar.apply(grads[:2])
f2 = Bar.apply(grads[2:])
return f1 + f2
xs = [torch.tensor(0.0, requires_grad=True) for _ in range(5)]
ys = Bar.apply(xs)
sum(ys).backward()
result = [xi.grad for xi in xs]
self.assertEqual(result, torch.tensor([1.0, 2, 1, 2, 3]).unbind(0))
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_default_values(self):
defaults = []
@torch.library.custom_op("_torch_testing::f", mutates_args=())
def f(
x: Tensor,
a: Optional[int] = None,
b: float = 3.14,
c: bool = True,
d: int = 3,
e: str = "foo",
f: torch.dtype = torch.float,
g: torch.dtype = torch.float32,
h: torch.dtype = torch.int,
i: torch.device = torch.device("cpu:0"),
j: torch.device = "cpu",
) -> Tensor:
defaults.extend([a, b, c, d, e, f, g, h, i, j])
return x.clone()
x = torch.randn(3)
f(x)
self.assertEqual(
defaults,
[
None,
3.14,
True,
3,
"foo",
torch.float,
torch.float32,
torch.int,
torch.device("cpu:0"),
"cpu",
],
)
default_values = [
arg.default_value
for arg in torch.ops._torch_testing.f.default._schema.arguments
]
# enum values taken from c10/core/ScalarType.h
type_enum = {
"float": 6,
"int": 3,
}
self.assertEqual(
default_values,
[
None,
None,
3.14,
True,
3,
"foo",
type_enum["float"],
type_enum["float"],
type_enum["int"],
torch.device("cpu:0"),
torch.device("cpu"),
],
)
def test_mutated_error(self):
with self.assertRaisesRegex(
ValueError, r".*{'y'} in mutates_args were not found"
):
@torch.library.custom_op(
"_torch_testing::numpy_sin_inplace",
mutates_args={"y"},
device_types="cpu",
)
def numpy_sin_inplace(x: Tensor) -> None:
x_np = x.numpy()
np.sin(x_np, out=x_np)
def test_mutated(self):
@torch.library.custom_op(
"_torch_testing::numpy_sin_inplace", mutates_args={"x"}, device_types="cpu"
)
def numpy_sin_inplace(x: Tensor) -> None:
x_np = x.numpy()
np.sin(x_np, out=x_np)
x = torch.randn(3)
version = x._version
expected = x.sin()
numpy_sin_inplace(x)
self.assertEqual(x, expected)
self.assertGreater(x._version, version)
@torch.library.custom_op("_torch_testing::f", mutates_args={"y", "z", "w"})
def f(
x: Tensor, y: Optional[Tensor], z: List[Tensor], w: List[Optional[Tensor]]
) -> None:
return
x = torch.randn(3)
y = torch.randn(3)
z = [torch.randn(3), torch.randn(3)]
w = [torch.randn(3), None, torch.randn(3)]
initial_versions = pytree.tree_map_only(
torch.Tensor, lambda x: x._version, (x, y, z, w)
)
f(x, y, z, w)
new_versions = pytree.tree_map_only(
torch.Tensor, lambda x: x._version, (x, y, z, w)
)
self.assertEqual(initial_versions[0], new_versions[0])
initial_versions, _ = pytree.tree_flatten(initial_versions[1:])
new_versions, _ = pytree.tree_flatten(new_versions[1:])
for prev, after in zip(initial_versions, new_versions):
if prev is None and after is None:
continue
self.assertGreater(after, prev)
def test_mutated_unknown(self):
@torch.library.custom_op(
"_torch_testing::f", mutates_args="unknown", device_types="cpu"
)
def f(x: Tensor) -> None:
x_np = x.numpy()
np.sin(x_np, out=x_np)
x = torch.randn(3)
version = x._version
expected = x.sin()
f(x)
self.assertEqual(x, expected)
self.assertGreater(x._version, version)
@torch.library.custom_op("_torch_testing::f2", mutates_args="unknown")
def f2(
x: Tensor, y: Optional[Tensor], z: List[Tensor], w: List[Optional[Tensor]]
) -> None:
return
x = torch.randn(3)
y = torch.randn(3)
z = [torch.randn(3), torch.randn(3)]
w = [torch.randn(3), None, torch.randn(3)]
initial_versions = pytree.tree_map_only(
torch.Tensor, lambda x: x._version, (x, y, z, w)
)
f2(x, y, z, w)
new_versions = pytree.tree_map_only(
torch.Tensor, lambda x: x._version, (x, y, z, w)
)
initial_versions, _ = pytree.tree_flatten(initial_versions)
new_versions, _ = pytree.tree_flatten(new_versions)
for prev, after in zip(initial_versions, new_versions):
if prev is None and after is None:
continue
self.assertGreater(after, prev)
with self.assertRaisesRegex(ValueError, "string"):
@torch.library.custom_op("_torch_testing::f3", mutates_args="x")
def f3(x: Tensor) -> None:
return
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_torch_dispatch_rule_subclass(self):
from torch.testing._internal.two_tensor import TwoTensor
@torch.library.custom_op("mylib::foo", mutates_args={})
def f(x: torch.Tensor) -> torch.Tensor:
return x.sin()
x = torch.randn(3)
y = torch.randn(3)
z = TwoTensor(x, y)
with torch.library._scoped_library("mylib", "FRAGMENT") as m:
called = 0
def TwoTensor_foo(cls, func, types, args, kwargs):
nonlocal called
assert cls is TwoTensor
called += 1
return x.sin()
m._register_torch_dispatch_rule("foo", TwoTensor, TwoTensor_foo)
out = f(z)
out2 = z.cos()
self.assertEqual(called, 1)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_torch_dispatch_rule_mode(self):
from torch.testing._internal.two_tensor import TwoTensorMode
@torch.library.custom_op("mylib::foo", mutates_args={})
def f(x: torch.Tensor) -> torch.Tensor:
return x.sin()
x = torch.randn(3)
with torch.library._scoped_library("mylib", "FRAGMENT") as m:
called = 0
def TwoTensor_foo(mode, func, types, args, kwargs):
nonlocal called
called += 1
return x.sin()
m._register_torch_dispatch_rule("foo", TwoTensorMode, TwoTensor_foo)
with TwoTensorMode():
out = f(x)
out2 = x.cos()
self.assertEqual(called, 1)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
@parametrize("idx", [0, 1, 2, 3, 4, 5])
def test_library_register_fake_source(self, idx):
opname = f"source{idx}"
op = getattr(torch.ops._torch_testing, opname).default
entry = torch._library.simple_registry.singleton.find(op._name)
source = entry.fake_impl.kernel.source
assert source is not None
self.assertTrue("custom_op_db.py" in source)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_fake(self):
for mode in ["function", "qualname", "opoverload"]:
@torch.library.custom_op("_torch_testing::add", mutates_args=())
def add(x: Tensor, y: float) -> Tensor:
x_np = x.cpu().numpy()
out_np = x_np + y
return torch.from_numpy(out_np).to(x.device)
called = False
if mode == "function":
dec = torch.library.register_fake(add)
self.assertIsNotNone(dec)
elif mode == "qualname":
dec = torch.library.register_fake("_torch_testing::add")
self.assertIsNotNone(dec)
elif mode == "opoverload":
dec = torch.library.register_fake(torch.ops._torch_testing.add.default)
self.assertIsNotNone(dec)
else:
raise AssertionError("should not get here")
@dec
def _(x, y):
nonlocal called
called = True
return torch.empty_like(x)
with torch._subclasses.fake_tensor.FakeTensorMode():
x = torch.randn(3)
y = 3.14
z = add(x, y)
self.assertEqual(z.shape, x.shape)
self.assertTrue(called)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_torch_dispatch(self):
for mode in ["function", "qualname", "opoverload"]:
class MyMode(torch.utils._python_dispatch.TorchDispatchMode):
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
return func(*args, **kwargs)
@torch.library.custom_op("_torch_testing::add", mutates_args=())
def add(x: Tensor, y: float) -> Tensor:
x_np = x.cpu().numpy()
out_np = x_np + y
return torch.from_numpy(out_np).to(x.device)
called = False
if mode == "function":
dec = torch.library.register_torch_dispatch(add, MyMode)
self.assertIsNotNone(dec)
elif mode == "qualname":
dec = torch.library.register_torch_dispatch(
"_torch_testing::add", MyMode
)
self.assertIsNotNone(dec)
elif mode == "opoverload":
dec = torch.library.register_torch_dispatch(
torch.ops._torch_testing.add.default, MyMode
)
self.assertIsNotNone(dec)
else:
raise AssertionError("should not get here")
@dec
def _(mode, func, types, args, kwargs):
nonlocal called
called = True
return func(*args, **kwargs)
with MyMode():
x = torch.randn(3)
y = 3.14
z = add(x, y)
self.assertEqual(z.shape, x.shape)
self.assertTrue(called)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_torch_dispatch_low_level(self):
modes = ["qualname", "opoverload"]
calls = ["decorator", "function"]
device_types_options = [("cpu", "cuda"), "cpu", None]
for mode, call, device_types in itertools.product(
modes, calls, device_types_options
):
with torch.library._scoped_library("_torch_testing", "FRAGMENT") as lib:
lib.define("add10(Tensor x, float y) -> Tensor")
if mode == "qualname":
op = "_torch_testing::add10"
else:
assert mode == "opoverload"
op = torch.ops._torch_testing.add10.default
called = False
class MyMode(torch.utils._python_dispatch.TorchDispatchMode):
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
return func(*args, **kwargs)
if call == "decorator":
@torch.library.register_torch_dispatch(op, MyMode, lib=lib)
def _(mode, func, types, args, kwargs):
x, y = args
nonlocal called
called = True
return x + y
else:
assert call == "function"
def add_stuff(mode, func, types, args, kwargs):
x, y = args
nonlocal called
called = True
return x + y
torch.library.register_torch_dispatch(
op, MyMode, add_stuff, lib=lib
)
x = torch.randn(3)
y = 3.14
with MyMode():
z = torch.ops._torch_testing.add10.default(x, y)
self.assertEqual(z, x + y)
self.assertTrue(called)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_kernel(self):
modes = ["function", "qualname", "opoverload"]
calls = ["decorator", "function"]
device_types_options = ["cpu", None]
for mode, call, device_types in itertools.product(
modes, calls, device_types_options
):
@torch.library.custom_op(
"_torch_testing::add", mutates_args=(), device_types="cuda"
)
def add(x: Tensor, y: float) -> Tensor:
x_np = x.cpu().numpy()
out_np = x_np + y
return torch.from_numpy(out_np).to(x.device)
if mode == "function":
op = add
elif mode == "qualname":
op = "_torch_testing::add"
else:
assert mode == "opoverload"
op = torch.ops._torch_testing.add.default
called = False
if call == "decorator":
@torch.library.register_kernel(op, device_types)
def _(x, y):
nonlocal called
called = True
x_np = x.numpy()
out_np = x_np + y
return torch.from_numpy(out_np)
else:
assert call == "function"
def add_cpu(x, y):
nonlocal called
called = True
x_np = x.numpy()
out_np = x_np + y
return torch.from_numpy(out_np)
torch.library.register_kernel(op, device_types, add_cpu)
x = torch.randn(3)
y = 3.14
z = add(x, y)
self.assertEqual(z, x + y)
self.assertTrue(called)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_kernel_low_level(self):
modes = ["qualname", "opoverload"]
calls = ["decorator", "function"]
device_types_options = [("cpu", "cuda"), "cpu", None]
for mode, call, device_types in itertools.product(
modes, calls, device_types_options
):
with torch.library._scoped_library("_torch_testing", "FRAGMENT") as lib:
lib.define("add9(Tensor x, float y) -> Tensor")
if mode == "qualname":
op = "_torch_testing::add9"
else:
assert mode == "opoverload"
op = torch.ops._torch_testing.add9.default
called = False
if call == "decorator":
@torch.library.register_kernel(op, device_types, lib=lib)
def _(x, y):
nonlocal called
called = True
x_np = x.numpy()
out_np = x_np + y
return torch.from_numpy(out_np)
else:
assert call == "function"
def add_cpu(x, y):
nonlocal called
called = True
x_np = x.numpy()
out_np = x_np + y
return torch.from_numpy(out_np)
torch.library.register_kernel(op, device_types, add_cpu, lib=lib)
x = torch.randn(3)
y = 3.14
z = torch.ops._torch_testing.add9.default(x, y)
self.assertEqual(z, x + y)
self.assertTrue(called)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_autograd(self):
for mode in ["function", "qualname", "opoverload"]:
@torch.library.custom_op("mylib::numpy_sin", mutates_args=())
def numpy_sin(x: Tensor) -> Tensor:
x_np = x.cpu().numpy()
y_np = np.sin(x_np)
return torch.from_numpy(y_np).to(device=x.device)
def setup_context(ctx, inputs, output) -> Tensor:
(x,) = inputs
ctx.save_for_backward(x)
called = False
def backward(ctx, grad):
nonlocal called
called = True
(x,) = ctx.saved_tensors
return grad * x.cos()
if mode == "function":
torch.library.register_autograd(
numpy_sin, backward, setup_context=setup_context
)
elif mode == "qualname":
torch.library.register_autograd(
"mylib::numpy_sin", backward, setup_context=setup_context
)
elif mode == "opoverload":
torch.library.register_autograd(
torch.ops.mylib.numpy_sin.default,
backward,
setup_context=setup_context,
)
x = torch.randn(3, requires_grad=True)
y = numpy_sin(x)
(grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y))
self.assertTrue(called)
self.assertEqual(grad_x, x.cos())
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_autograd_low_level(self):
for mode in ["qualname", "opoverload"]:
with torch.library._scoped_library("_torch_testing", "FRAGMENT") as lib:
lib.define("sin5(Tensor x) -> Tensor")
def numpy_sin(x: Tensor) -> Tensor:
x_np = x.cpu().detach().numpy()
y_np = np.sin(x_np)
return torch.from_numpy(y_np).to(device=x.device)
def setup_context(ctx, inputs, output) -> Tensor:
(x,) = inputs
ctx.save_for_backward(x)
called = False
def backward(ctx, grad):
nonlocal called
called = True
(x,) = ctx.saved_tensors
return grad * x.cos()
lib.impl("sin5", numpy_sin, "CPU")
called = False
if mode == "qualname":
torch.library.register_autograd(
"_torch_testing::sin5",
backward,
setup_context=setup_context,
lib=lib,
)
elif mode == "opoverload":
torch.library.register_autograd(
torch.ops._torch_testing.sin5.default,
backward,
setup_context=setup_context,
lib=lib,
)
x = torch.randn(3, requires_grad=True)
y = torch.ops._torch_testing.sin5(x)
(grad_x,) = torch.autograd.grad(y, x, torch.ones_like(y))
self.assertTrue(called)
self.assertEqual(grad_x, x.cos())
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_fake(self):
@torch.library.custom_op("_torch_testing::add", mutates_args=())
def add(x: Tensor, y: float) -> Tensor:
x_np = x.cpu().numpy()
out_np = x_np + y
return torch.from_numpy(out_np).to(x.device)
x = torch.randn(3)
y = 3.14
z = add(x, y)
self.assertEqual(z, x + y)
try:
with torch._subclasses.fake_tensor.FakeTensorMode():
x = torch.randn(3)
add(x, y)
raise AssertionError("should not be hit")
except RuntimeError as e:
abstract_impl_error_msg = str(e)
abstract_impl_error_msg = re.sub(
r"0x.*>\)>", "0xDEADBEEF>)>", abstract_impl_error_msg
).replace(". ", ".\n")
self.assertExpectedInline(
abstract_impl_error_msg,
"""\
There was no fake impl registered for <CustomOpDef(_torch_testing::add)>.
This is necessary for torch.compile/export/fx tracing to work.
Please use `add.register_fake` to add an fake impl.""",
)
if not IS_WINDOWS:
@torch.compile(backend="eager")
def f(x, y):
return add(x, y)
x = torch.randn(3)
with self.assertRaisesRegex(RuntimeError, "no fake impl"):
f(x, y)
abstract_called = False
@add.register_fake
def _(x, y):
nonlocal abstract_called
abstract_called = True
return torch.empty_like(x)
with torch._subclasses.fake_tensor.FakeTensorMode():
x = torch.randn(3)
z = add(x, y)
self.assertEqual(z.shape, x.shape)
self.assertTrue(abstract_called)
@skipIfTorchDynamo("recursive dynamo")
@unittest.skipIf(IS_WINDOWS, "torch.compile doesn't work on windows")
def test_compile(self):
called_impl = False
called_abstract = False
@torch.library.custom_op("_torch_testing::linear", mutates_args=())
def custom_linear(x: Tensor, weight: Tensor, bias: Tensor) -> Tensor:
nonlocal called_impl
called_impl = True
x_np = x.numpy()
w_np = weight.numpy()
b_np = bias.numpy()
out_np = np.add(x_np @ w_np.T, bias)
return out_np
@custom_linear.register_fake
def _(x, weight, bias):
nonlocal called_abstract
called_abstract = True
assert x.dim() == 2
assert weight.dim() == 2
assert bias.dim() == 1
assert x.shape[1] == weight.shape[1]
assert weight.shape[0] == bias.shape[0]
assert x.device == weight.device
return x.new_empty(x.size(0), weight.size(0))
x = torch.randn(2, 2)
weight = torch.randn(2, 2)
bias = torch.randn(2)
out = torch.compile(custom_linear, backend="eager", fullgraph=True)(
x, weight, bias
)
self.assertEqual(out, torch.nn.functional.linear(x, weight, bias))
self.assertTrue(called_impl)
self.assertTrue(called_abstract)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_register_autograd_error_cases(self):
@torch.library.custom_op("_torch_testing::g", mutates_args=())
def g(x: Tensor) -> Tensor:
return x.sin()
x = torch.randn(3, requires_grad=True)
y = g(x)
with self.assertRaisesRegex(RuntimeError, "no autograd formula"):
y.sum().backward()
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_replacement(self):
@torch.library.custom_op("_torch_testing::f", mutates_args=())
def f(x: Tensor) -> Tensor:
return x.sin()
x = torch.randn(3)
y = f(x)
self.assertEqual(y, x.sin())
@torch.library.custom_op("_torch_testing::f", mutates_args=())
def f(x: Tensor) -> Tensor:
return x.cos()
y = f(x)
self.assertEqual(y, x.cos())
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
@unittest.skipIf(not TEST_CUDA, "requires CUDA")
def test_split_device(self):
cpu_call_count = 0
cuda_call_count = 0
@torch.library.custom_op(
"_torch_testing::f", mutates_args=(), device_types="cpu"
)
def f(x: Tensor) -> Tensor:
nonlocal cpu_call_count
cpu_call_count += 1
x_np = x.numpy()
out_np = np.sin(x_np)
return torch.from_numpy(out_np)
@f.register_kernel("cuda")
def _(x: Tensor) -> Tensor:
nonlocal cuda_call_count
cuda_call_count += 1
x_np = x.cpu().numpy()
out_np = np.sin(x_np)
return torch.from_numpy(out_np).to(x.device)
x = torch.randn(3)
y = f(x)
self.assertEqual(y, x.sin())
self.assertEqual(cpu_call_count, 1)
self.assertEqual(cuda_call_count, 0)
x = x.cuda()
y = f(x)
self.assertEqual(y, x.sin())
self.assertEqual(cpu_call_count, 1)
self.assertEqual(cuda_call_count, 1)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
@unittest.skipIf(not TEST_CUDA, "requires CUDA")
def test_multi_types(self):
@torch.library.custom_op(
"_torch_testing::f", mutates_args=(), device_types=("cpu", "cuda")
)
def f(x: Tensor) -> Tensor:
x_np = x.cpu().numpy()
out_np = np.sin(x_np)
return torch.from_numpy(out_np).to(x.device)
x = torch.randn(3)
y = f(x)
self.assertEqual(y, x.sin())
x = x.cuda()
y = f(x)
self.assertEqual(y, x.sin())
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_overloading(self):
called_f = 0
called_f1 = 0
@torch.library.custom_op("_torch_testing::f", mutates_args=())
def f(x: Tensor) -> Tensor:
nonlocal called_f
called_f += 1
return x.clone()
x = torch.randn(2, 3)
torch.ops._torch_testing.f(x)
self.assertEqual(called_f, 1)
@torch.library.custom_op("_torch_testing::f.overload", mutates_args=())
def f1(x: Tensor, y: Tensor) -> Tensor:
nonlocal called_f1
called_f1 += 1
return x.clone()
torch.ops._torch_testing.f(x, x)
self.assertEqual(called_f1, 1)
def test_disallows_output_aliasing(self):
@torch.library.custom_op("_torch_testing::f", mutates_args=())
def f(x: Tensor) -> Tensor:
return x.view(-1)
x = torch.randn(3)
with self.assertRaisesRegex(RuntimeError, "may not alias"):
f(x)
@torch.library.custom_op("_torch_testing::f", mutates_args=())
def f(x: Tensor) -> Tensor:
return x
x = torch.randn(3)
with self.assertRaisesRegex(RuntimeError, "may not alias"):
f(x)
@torch.library.custom_op(
"_torch_testing::f", mutates_args={"x"}, device_types="cpu"
)
def numpy_sin_inplace(x: Tensor) -> Tensor:
x_np = x.numpy()
np.sin(x_np, out=x_np)
return x
x = torch.randn(3)
with self.assertRaisesRegex(RuntimeError, "may not alias"):
numpy_sin_inplace(x)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_factory_function(self):
@torch.library.custom_op(
"_torch_testing::f", mutates_args={}, device_types="cpu"
)
def f(device: torch.device) -> Tensor:
return torch.ones(3)
result = f(device="cpu")
self.assertEqual(result.device, torch.device("cpu"))
self.assertEqual(result, torch.ones(3))
with self.assertRaisesRegex(
RuntimeError, "f does not have a kernel registered for cuda"
):
f("cuda")
with self.assertRaisesRegex(
ValueError,
"Functions without tensor inputs are required to have a `device: torch.device` argument",
):
@torch.library.custom_op(
"_torch_testing::f2", mutates_args={}, device_types="cpu"
)
def f2() -> Tensor:
return torch.ones(3)
@torch.library.custom_op("_torch_testing::f3", mutates_args={})
def f3() -> Tensor:
raise NotImplementedError("NYI")
with self.assertRaisesRegex(
ValueError,
"Functions without tensor inputs are required to have a `device: torch.device` argument",
):
@f3.register_kernel("cpu")
def _():
return torch.zeros(3)
result = f(x)
@torch.library.custom_op("_torch_testing::f4", mutates_args={})
def f4(device: torch.device) -> Tensor:
raise NotImplementedError("NYI")
@f4.register_kernel("cpu")
def _(device: torch.device):
return torch.zeros(3)
result = f(device="cpu")
self.assertEqual(result.device, torch.device("cpu"))
self.assertEqual(result, torch.ones(3))
def test_library_schema_infer(self):
def foo_impl(x: torch.Tensor) -> torch.Tensor:
return x.sin()
schema = torch.library.infer_schema(foo_impl, op_name="myop", mutates_args={})
self.assertExpectedInline(schema, "myop(Tensor x) -> Tensor")
schema = torch.library.infer_schema(foo_impl, mutates_args={})
self.assertExpectedInline(schema, "(Tensor x) -> Tensor")
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_set_kernel_enabled(self):
x = torch.ones(1)
@torch.library.custom_op("mylib::f", mutates_args=())
def f(x: Tensor) -> Tensor:
return x + 1
self.assertEqual(f(x), x + 1)
with self.assertLogs("torch._library.custom_ops") as captured:
with f.set_kernel_enabled("gpu", enabled=False):
self.assertEqual(f(x), x + 1)
self.assertIn(
"no kernel was registered for this device type", captured.output[0]
)
@f.register_kernel("cpu")
def _(x):
return x + 2
self.assertEqual(f(x), x + 2)
with self.assertLogs("torch._library.custom_ops") as captured:
with f.set_kernel_enabled("cpu", enabled=True):
self.assertEqual(f(x), x + 2)
self.assertIn("already enabled", captured.output[0])
with f.set_kernel_enabled("cpu", enabled=False):
self.assertEqual(f(x), x + 1)
with self.assertLogs("torch._library.custom_ops") as captured:
with f.set_kernel_enabled("cpu", enabled=False):
self.assertEqual(f(x), x + 1)
self.assertIn("already disabled", captured.output[0])
self.assertEqual(f(x), x + 1)
with f.set_kernel_enabled("cpu", enabled=True):
self.assertEqual(f(x), x + 2)
with f.set_kernel_enabled("cpu", enabled=False):
self.assertEqual(f(x), x + 1)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_register_vmap_kwargonly_low_level(self):
with torch.library._scoped_library("_torch_testing", "FRAGMENT") as lib:
lib.define("foo(Tensor x, *, float y) -> Tensor")
called = False
def foo_impl(x, *, y):
return x * y
lib.impl("foo", foo_impl, "CPU")
def vmap(info, in_dims, x, *, y):
nonlocal called
called = True
return x * y, 0
torch.library.register_vmap("_torch_testing::foo", vmap, lib=lib)
x = torch.ones(3)
result = torch.vmap(torch.ops._torch_testing.foo)(x, y=3.14)
self.assertTrue(called)
self.assertEqual(result, torch.tensor([3.14, 3.14, 3.14]))
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_register_vmap_defaults(self):
with torch.library._scoped_library("_torch_testing", "FRAGMENT") as lib:
lib.define("foo(Tensor w, int x = 2, *, int y = 3, int z) -> Tensor")
def foo_impl(w, x=2, *, y=3, z):
return w * x * y * z
lib.impl("foo", foo_impl, "CPU")
called = False
def vmap(info, in_dims, w, x=2, *, y=3, z):
nonlocal called
called = True
return w * x * y * z, 0
torch.library.register_vmap("_torch_testing::foo", vmap, lib=lib)
w = torch.ones(3)
result = torch.vmap(torch.ops._torch_testing.foo)(w, z=42)
self.assertTrue(called)
self.assertEqual(result, w * 2 * 3 * 42)
def test_layout_constraint_tags(self):
needs_fixed_stride_order = torch._C.Tag.needs_fixed_stride_order
flexible_layout = torch._C.Tag.flexible_layout
# (tags, the result of the tag inference)
tests = [
({needs_fixed_stride_order}, needs_fixed_stride_order),
({flexible_layout}, flexible_layout),
# If no tags are provided, then the following is the default
(set(), needs_fixed_stride_order),
# If multiple tags are provided, then we use the most constrained tag.
({flexible_layout, needs_fixed_stride_order}, needs_fixed_stride_order),
]
from torch._inductor.lowering import get_layout_constraint_tag
for tags, expected in tests:
with torch.library._scoped_library("mylib", "FRAGMENT") as m:
m.define("foobar(Tensor x) -> Tensor", tags=tags)
result = get_layout_constraint_tag(torch.ops.mylib.foobar.default)
self.assertEqual(result, expected)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_vmap(self):
for mode in ["function", "qualname", "opoverload", "c_opdef"]:
@torch.library.custom_op("mylib::f", mutates_args=())
def f(x: Tensor, y: Tensor) -> Tensor:
return x * y
called = False
def fvmap(info, in_dims, x, y):
nonlocal called
called = True
x_bdim, y_bdim = in_dims
x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
result = x * y
result = result.movedim(-1, 0)
return result, 0
if mode == "function":
torch.library.register_vmap(f, fvmap)
elif mode == "qualname":
torch.library.register_vmap("mylib::f", fvmap)
elif mode == "opoverload":
torch.library.register_vmap(torch.ops.mylib.f.default, fvmap)
elif mode == "c_opdef":
f.register_vmap(fvmap)
x = torch.randn(2, 2)
y = torch.randn(2, 2)
result = torch.vmap(f)(x, y)
self.assertTrue(called)
self.assertEqual(result, x * y)
called = False
result = torch.vmap(f, out_dims=1)(x, y)
self.assertEqual(result, (x * y).T)
self.assertTrue(called)
called = False
result = torch.vmap(f, in_dims=1)(x, y)
self.assertEqual(result, (x * y).T)
self.assertTrue(called)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_vmap_library_decorator(self):
@torch.library.custom_op("mylib::f", mutates_args=())
def f(x: Tensor, y: Tensor) -> Tensor:
return x * y
called = False
@torch.library.register_vmap("mylib::f")
def fvmap(info, in_dims, x, y):
nonlocal called
called = True
x_bdim, y_bdim = in_dims
x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
result = x * y
result = result.movedim(-1, 0)
return result, 0
x = torch.randn(2, 2)
y = torch.randn(2, 2)
result = torch.vmap(f)(x, y)
self.assertTrue(called)
self.assertEqual(result, x * y)
x = torch.randn(3)
y = torch.randn(3)
result = torch.vmap(torch.vmap(f, in_dims=(0, None)), in_dims=(None, 0))(x, y)
self.assertEqual(result, y.unsqueeze(-1) * x)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_vmap_op_decorator(self):
@torch.library.custom_op("mylib::f", mutates_args=())
def f(x: Tensor, y: Tensor) -> Tensor:
return x * y
called = False
@f.register_vmap
def fvmap(info, in_dims, x, y):
nonlocal called
called = True
x_bdim, y_bdim = in_dims
x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
result = x * y
result = result.movedim(-1, 0)
return result, 0
x = torch.randn(2, 2)
y = torch.randn(2, 2)
result = torch.vmap(f)(x, y)
self.assertTrue(called)
self.assertEqual(result, x * y)
x = torch.randn(3)
y = torch.randn(2)
result = torch.vmap(torch.vmap(f, in_dims=(0, None)), in_dims=(None, 0))(x, y)
self.assertEqual(result, y.unsqueeze(-1) * x)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_vmap_register_multiple_times(self):
@torch.library.custom_op("mylib::f", mutates_args=())
def f(x: Tensor, y: Tensor) -> Tensor:
return x * y
called = False
@f.register_vmap
def fvmap(info, in_dims, x, y):
nonlocal called
called = True
x_bdim, y_bdim = in_dims
x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
result = x * y
result = result.movedim(-1, 0)
return result, 0
x = torch.randn(2, 2)
y = torch.randn(2, 2)
result = torch.vmap(f)(x, y)
self.assertTrue(called)
self.assertEqual(result, x * y)
called = False
@f.register_vmap
def fvmap2(info, in_dims, x, y):
nonlocal called
called = True
x_bdim, y_bdim = in_dims
x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
result = x + y
result = result.movedim(-1, 0)
return result, 0
result = torch.vmap(f)(x, y)
self.assertTrue(called)
self.assertEqual(result, x + y)
@skipIfTorchDynamo("Expected to fail due to no FakeTensor support; not a bug")
def test_library_register_vmap_register_multiple_times_2(self):
@torch.library.custom_op("mylib::f", mutates_args=())
def f(x: Tensor, y: Tensor) -> Tensor:
return x * y
called = False
@torch.library.register_vmap("mylib::f")
def fvmap(info, in_dims, x, y):
nonlocal called
called = True
x_bdim, y_bdim = in_dims
x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
result = x * y
result = result.movedim(-1, 0)
return result, 0
x = torch.randn(2, 2)
y = torch.randn(2, 2)
result = torch.vmap(f)(x, y)
self.assertTrue(called)
self.assertEqual(result, x * y)
called = False
@torch.library.register_vmap("mylib::f")
def fvmap2(info, in_dims, x, y):
nonlocal called
called = True
x_bdim, y_bdim = in_dims
x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
result = x + y
result = result.movedim(-1, 0)
return result, 0
result = torch.vmap(f)(x, y)
self.assertTrue(called)
self.assertEqual(result, x + y)
class MiniOpTestOther(CustomOpTestCaseBase):
test_ns = "mini_op_test"
def test_nonzero_again(self):
x = torch.tensor([0, 1, 2, 0, 0])
y = torch.ops.aten.nonzero.default(x)
self.assertEqual(y, torch.tensor([[1], [2]]))
optests.generate_opcheck_tests(
MiniOpTest,
["aten", "mini_op_test"],
get_file_path_2(os.path.dirname(__file__), "minioptest_failures_dict.json"),
additional_decorators={
"test_pt2_compliant_tag_mini_op_test_no_abstract": [unittest.expectedFailure]
},
test_utils=optests.generate_tests.DEPRECATED_DEFAULT_TEST_UTILS,
)
optests.generate_opcheck_tests(
MiniOpTestOther,
["aten", "mini_op_test"],
get_file_path_2(os.path.dirname(__file__), "minioptest_failures_dict.json"),
test_utils=optests.generate_tests.DEPRECATED_DEFAULT_TEST_UTILS,
)
class TestGenerateOpcheckTests(CustomOpTestCaseBase):
def test_MiniOpTest(self):
for orig_test in ["test_mm", "test_nonzero"]:
for (
test
) in torch.testing._internal.optests.generate_tests.DEFAULT_TEST_UTILS:
expected_test = f"{test}__{orig_test}"
self.assertTrue(hasattr(MiniOpTest, expected_test), msg=expected_test)
def test_generate_repro_save_data(self):
from torch.testing._internal.optests.generate_tests import generate_repro
args = (torch.ones(2, 2),)
kwargs = {"mat2": torch.zeros(2, 2)}
actual = generate_repro(
"test_schema",
torch.ops.aten.sin.default,
args,
kwargs,
save_data=True,
dry_run=True,
)
actual = re.sub(r"torch.load\(\".*\.pt\"\)", 'torch.load("repro.pt")', actual)
self.assertExpectedInline(
actual,
"""\
# =========================================================
# BEGIN REPRO SCRIPT
# =========================================================
import torch
from torch.testing._internal.optests import opcheck
# Make sure you have loaded the library that contains the op
# via an import or torch.ops.load_library(...)
op = torch.ops.aten.sin.default
args, kwargs = torch.load("repro.pt")
opcheck(op, args, kwargs, test_utils="test_schema")
# =========================================================
# END REPRO SCRIPT
# =========================================================
""",
)
def test_generate_repro_no_save_data(self):
from torch.testing._internal.optests.generate_tests import generate_repro
args = (torch.ones(2, 2),)
kwargs = {"mat2": torch.zeros(2, 2)}
actual = generate_repro(
"test_schema",
torch.ops.aten.sin.default,
args,
kwargs,
save_data=False,
dry_run=True,
)
self.assertExpectedInline(
actual,
"""\
# =========================================================
# BEGIN REPRO SCRIPT
# =========================================================
import torch
from torch.testing._internal.optests import opcheck
# Make sure you have loaded the library that contains the op
# via an import or torch.ops.load_library(...)
op = torch.ops.aten.sin.default
# If you rerun your test with PYTORCH_OPCHECK_PRINT_BETTER_REPRO=1
# we will fill them in same (args, kwargs) as in your test
args = () # args to the operator
kwargs = {} # kwargs to the operator
opcheck(op, args, kwargs, test_utils="test_schema")
# =========================================================
# END REPRO SCRIPT
# =========================================================
""",
)
def test_failures_dict_validation(self):
from torch.testing._internal.optests.generate_tests import (
FailuresDict,
validate_failures_dict_structure,
)
failures = {
"mini_op_test::incorrect_schema": {
"MiniOpTest.test_aot_dispatch_dynamic__test_delayed_error": {
"comment": "",
"status": "success",
}
}
}
with self.assertRaisesRegex(RuntimeError, "got status=success"):
validate_failures_dict_structure(
FailuresDict("", failures),
torch.testing._internal.optests.generate_tests.DEFAULT_TEST_UTILS,
MiniOpTest,
)
failures = {
"mini_op_test::incorrect_schema": {
"MiniOpTest.test_aot_dispatch__test_delayed_error": {
"comment": "",
"status": "xfail",
},
}
}
with self.assertRaisesRegex(RuntimeError, "should begin with one of"):
validate_failures_dict_structure(
FailuresDict("", failures),
torch.testing._internal.optests.generate_tests.DEFAULT_TEST_UTILS,
MiniOpTest,
)
failures = {
"mini_op_test::incorrect_schema": {
"MiniOpTest.test_aot_dispatch_dynamic__test_delayed_error_nopenopenope": {
"comment": "",
"status": "xfail",
},
}
}
with self.assertRaisesRegex(RuntimeError, "does not exist on the TestCase"):
validate_failures_dict_structure(
FailuresDict("", failures),
torch.testing._internal.optests.generate_tests.DEFAULT_TEST_UTILS,
MiniOpTest,
)
def test_dont_generate_decorator(self):
self.assertTrue(hasattr(MiniOpTest, "test_dont_generate"))
self.assertFalse(hasattr(MiniOpTest, "test_schema__test_dont_generate"))
def test_opcheck(self):
x = torch.randn(3, requires_grad=True)
with self.assertRaisesRegex(ValueError, "OpOverload"):
torch.library.opcheck(torch.sin, (x,))
with self.assertRaisesRegex(ValueError, "test_utils to be subset of"):
torch.library.opcheck(torch.ops.aten.sin.default, (x,), test_utils="blah")
result = torch.library.opcheck(torch.ops.aten.sin.default, (x,))
self.assertEqual(
result,
{
"test_schema": "SUCCESS",
"test_autograd_registration": "SUCCESS",
"test_faketensor": "SUCCESS",
"test_aot_dispatch_dynamic": "SUCCESS",
},
)
result = torch.library.opcheck(
torch.ops.aten.sin.default, (x,), test_utils="test_schema"
)
self.assertEqual(result, {"test_schema": "SUCCESS"})
result = torch.library.opcheck(
torch.ops.aten.sin.default,
(x,),
test_utils=["test_schema", "test_faketensor"],
)
self.assertEqual(
result,
{
"test_schema": "SUCCESS",
"test_faketensor": "SUCCESS",
},
)
def test_opcheck_customopdef(self):
sample_inputs = [
(torch.randn(3),),
(torch.randn(3, requires_grad=True),),
]
if torch.cuda.is_available():
sample_inputs.extend(
[
(torch.randn(3, device="cuda"),),
(torch.randn(3, device="cuda", requires_grad=True),),
]
)
for args in sample_inputs:
torch.library.opcheck(custom_op_db.numpy_cube, args)
def test_is_inside_opcheck_mode(self):
self.assertFalse(optests.is_inside_opcheck_mode())
with optests.generate_tests.OpCheckMode(
["foo"], "bar", lambda x: x, None, "baz", "brr"
):
self.assertTrue(optests.is_inside_opcheck_mode())
def test_opcheck_bad_op(self):
op = op_with_incorrect_schema(self, "foo")
x = torch.randn(3)
with self.assertRaisesRegex(Exception, "is not defined to alias output"):
torch.library.opcheck(op, (x,))
result = torch.library.opcheck(op, (x,), raise_exception=False)
self.assertTrue(isinstance(result["test_schema"], RuntimeError))
del result["test_schema"]
self.assertEqual(
result,
{
"test_autograd_registration": "SUCCESS",
"test_faketensor": "SUCCESS",
"test_aot_dispatch_dynamic": "SUCCESS",
},
)
def test_opcheck_does_not_require_extra_deps(self):
# torch.testing._internal.common_utils comes with a lot of additional
# test-time dependencies. Since opcheck is public API, it should be
# usable only with pytorch install-time dependencies.
cmd = [
sys.executable,
"-c",
"import torch; import sys; \
x = torch.randn(3, requires_grad=True); \
torch.library.opcheck(torch.ops.aten.sin.default, (x,)); \
assert 'expecttest' not in sys.modules; \
assert 'torch.testing._internal.common_utils' not in sys.modules",
]
subprocess.check_output(cmd, shell=False)
class TestTypeConversion(TestCase):
"""In infer_schema(), we try to suggest a correct type when the type annotation is wrong."""
def setUp(self):
self.supported_base_types = [
int,
float,
bool,
str,
torch.device,
torch.Tensor,
torch.dtype,
torch.types.Number,
]
def test_simple_tuple(self):
self.assertEqual(List, tuple_to_list(Tuple))
def test_supported_types(self):
for t in self.supported_base_types:
result_type = tuple_to_list(Tuple[t, t, t])
self.assertEqual(result_type, List[t])
result_type = tuple_to_list(Tuple[t])
self.assertEqual(result_type, List[t])
def test_optional(self):
for t in self.supported_base_types:
result_type = tuple_to_list(Tuple[t, Optional[t]])
self.assertEqual(result_type, List[Optional[t]])
result_type = tuple_to_list(Tuple[t, t, Optional[t]])
self.assertEqual(result_type, List[Optional[t]])
result_type = tuple_to_list(Tuple[t, ...])
self.assertEqual(result_type, List[t])
def test_mixed_types(self):
result_type = tuple_to_list(Tuple[int, float])
self.assertEqual(result_type, List[typing.Union[int, float]])
result_type = tuple_to_list(Tuple[int, float, str])
self.assertEqual(result_type, List[typing.Union[int, float, str]])
only_for = ("cpu", "cuda")
instantiate_device_type_tests(TestCustomOpTesting, globals(), only_for=only_for)
instantiate_parametrized_tests(TestCustomOp)
instantiate_parametrized_tests(TestCustomOpAPI)
if __name__ == "__main__":
run_tests()
|