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
|
# Owner(s): ["module: inductor"]
import contextlib
import dataclasses
import functools
import io
import itertools
import logging
import os
import re
import subprocess
import sys
import unittest
from importlib.machinery import SourceFileLoader
from pathlib import Path
from unittest import mock
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import _inductor as inductor
from torch._dynamo import compiled_autograd, config
from torch._dynamo.backends.debugging import aot_eager
from torch._dynamo.device_interface import get_interface_for_device
from torch._dynamo.utils import counters
from torch._inductor import config as inductor_config
from torch._inductor.test_case import run_tests, TestCase
from torch.testing._internal.common_utils import (
scoped_load_inline,
skipIfWindows,
xfailIfS390X,
)
from torch.testing._internal.inductor_utils import GPU_TYPE, HAS_CPU, HAS_CUDA, HAS_GPU
from torch.testing._internal.logging_utils import logs_to_string
# note: these tests are not run on windows due to inductor_utils.HAS_CPU
def make_compiler_fn(fullgraph=True, dynamic=True, backend="inductor"):
assert backend in ["inductor", "aot_eager"]
def _compiler_fn(gm):
"""Same as torch.compile() but counts number of compiles"""
def _inner_compiler(gm_, example_inputs_):
counters["compiled_autograd"]["compiles"] += 1
if backend == "inductor":
return inductor.compile(gm_, example_inputs_)
elif backend == "aot_eager":
return aot_eager(gm_, example_inputs_)
return torch.compile(
gm, backend=_inner_compiler, fullgraph=fullgraph, dynamic=dynamic
)
return _compiler_fn
compiler_fn = make_compiler_fn()
# TODO(jansel): hooks as lambdas creates recompiles in dynamo, we should fix that
def hook1(grad):
return grad * 2
def hook2(grads):
return (grads[0] + 1,)
def hook3(gI, gO):
return (torch.sin(gI[0]) + gO[0],)
class TestCompiledAutograd(TestCase):
def setUp(self) -> None:
super().setUp()
torch._logging.set_logs(compiled_autograd_verbose=False)
config.compiled_autograd = False
compiled_autograd.reset()
def tearDown(self) -> None:
super().tearDown()
torch._logging.set_logs(compiled_autograd_verbose=False)
config.compiled_autograd = False
compiled_autograd.reset()
def check_output_and_recompiles(
self, fn, count=1, compiler_fn=compiler_fn, compile_fn=False
):
if isinstance(count, list):
captures, compiles = count
else:
captures, compiles = count, count
with torch.autograd.set_multithreading_enabled(False):
torch._dynamo.reset()
counters["compiled_autograd"].clear()
torch.manual_seed(123)
expected = list(fn())
torch.manual_seed(123)
with compiled_autograd._enable(compiler_fn):
opt_fn = torch.compile(fn) if compile_fn else fn
actual = list(opt_fn())
self.assertEqual(expected, actual)
self.assertEqual(counters["compiled_autograd"]["captures"], captures)
self.assertEqual(counters["compiled_autograd"]["compiles"], compiles)
def run_as_subprocess(self, script) -> bytes:
try:
return 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__)),
)
except subprocess.CalledProcessError as e:
self.fail(f"Subprocess exited with return code: {e.returncode}")
def test_dynamo_flaky_segfault(self):
script = """
import torch
def main():
def compiler_fn(gm):
return torch.compile(gm, backend="eager")
def inner():
x = torch.randn(1000, 3000)
w = torch.randn(1000, 3000, requires_grad=True)
def model(i):
return torch.nn.functional.linear(i, w)
out = model(x)
loss = out.sum()
with torch._dynamo.compiled_autograd._enable(compiler_fn):
loss.backward()
assert(w.grad is not None)
inner()
torch._dynamo.reset()
inner()
main()
"""
# Run it three times to catch bad dynamo state resets
for _ in range(3):
self.run_as_subprocess(script)
def test_basic(self):
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
x = torch.randn([2, 4])
result = model(x).sum()
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
yield model[2].weight.grad
yield model[2].bias.grad
self.check_output_and_recompiles(fn)
def test_cache_hit(self):
def fn():
for _ in range(3):
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
x = torch.randn([2, 4])
result = model(x).sum()
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
yield model[2].weight.grad
yield model[2].bias.grad
self.check_output_and_recompiles(fn)
def test_graph_break_custom_op(self):
@torch.library.custom_op("mylib::sin", mutates_args={})
def sin(x: torch.Tensor) -> torch.Tensor:
return x.sin()
def setup_context(ctx, inputs, output):
(x,) = inputs
ctx.save_for_backward(x)
def backward(ctx, grad):
(x,) = ctx.saved_tensors
return grad * x.cos()
sin.register_autograd(backward, setup_context=setup_context)
x = torch.randn(3, requires_grad=True)
y = sin(x.clone()).sum()
with compiled_autograd._enable(compiler_fn):
y.backward()
def test_tensor_grad_hook1(self):
def fn():
for _ in range(3):
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
x = torch.randn([2, 4])
model[0].weight.register_hook(hook1)
result = model(x).sum()
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
self.check_output_and_recompiles(fn)
def test_tensor_grad_hook2(self):
def fn():
for _ in range(3):
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
x = torch.randn([1, 4])
result = model(x).sum()
result.grad_fn.register_prehook(hook2)
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
self.check_output_and_recompiles(fn)
def test_tensor_grad_hook3(self):
def fn():
for _ in range(3):
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
x = torch.randn([1, 4])
result = model(x).sum()
result.grad_fn.register_hook(hook3)
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
self.check_output_and_recompiles(fn)
def test_reorder_acc_grad(self):
model = torch.nn.Sequential(
torch.nn.Conv2d(4, 4, 3, bias=True),
torch.nn.Conv2d(4, 4, 3, bias=True),
)
compiled_model = torch.compile(model)
x = torch.randn([1, 4, 32, 32])
model(x).sum().backward()
ref_res = [
model[0].weight.grad,
model[0].bias.grad,
model[1].weight.grad,
model[1].bias.grad,
]
model[0].weight.grad = None
model[0].bias.grad = None
model[1].weight.grad = None
model[1].bias.grad = None
with compiled_autograd._enable(compiler_fn):
compiled_model(x).sum().backward(retain_graph=True)
res = [
model[0].weight.grad,
model[0].bias.grad,
model[1].weight.grad,
model[1].bias.grad,
]
self.assertEqual(res[0], ref_res[0])
self.assertEqual(res[1], ref_res[1])
self.assertEqual(res[2], ref_res[2])
self.assertEqual(res[3], ref_res[3])
def test_reorder_post_hook1(self):
def grad_div(param):
param.grad = param.grad / 4.0
class Module(torch.nn.Module):
def __init__(self, ioc):
super().__init__()
self.fc1 = torch.nn.Linear(ioc, ioc, bias=False)
self.fc2 = torch.nn.Linear(ioc, ioc, bias=False)
self.grad_acc_hooks = []
self.grad_acc = []
self.params = [self.fc1.weight, self.fc2.weight]
for i, param in enumerate(self.params):
def wrapper(param):
param_tmp = param.expand_as(param)
grad_acc = param_tmp.grad_fn.next_functions[0][0]
def grad_acc_hook(*notneeded):
grad_div(param)
self.grad_acc.append(grad_acc)
self.grad_acc_hooks.append(
grad_acc.register_hook(grad_acc_hook)
)
wrapper(param)
def forward(self, x):
x = self.fc1(x)
x = self.fc2(x)
return x.sum()
bs = 8
ioc = 16
model = Module(ioc)
input = torch.randn([bs, ioc])
# eager ref
model(input).backward()
ref_res = [model.fc1.weight.grad, model.fc2.weight.grad]
# cag
model.fc1.weight.grad = None
model.fc2.weight.grad = None
model_to_train = torch.compile(model, backend="inductor")
with compiled_autograd._enable(compiler_fn):
model_to_train(input).backward()
res = [model_to_train.fc1.weight.grad, model_to_train.fc2.weight.grad]
self.assertEqual(res[0], ref_res[0])
self.assertEqual(res[1], ref_res[1])
def test_reorder_post_hook2(self):
x = torch.randn([1, 4, 32, 32], requires_grad=True)
y = torch.sigmoid(x)
z = torch.tanh(y)
assert isinstance(z.grad_fn, torch.autograd.graph.Node)
assert isinstance(y.grad_fn, torch.autograd.graph.Node)
handle_z = z.grad_fn.register_hook(lambda gI, gO: (gO[0] * 2,))
handle_y = y.grad_fn.register_hook(lambda gI, gO: (gI[0] * 2,))
z.sum().backward(retain_graph=True)
ref_res = x.grad
x.grad = None
with compiled_autograd._enable(compiler_fn):
z.sum().backward(retain_graph=True)
res = x.grad
self.assertEqual(res, ref_res)
def test_reorder_post_hook3(self):
conv = torch.nn.Conv2d(4, 4, 3, bias=False)
x = torch.randn([1, 4, 32, 32])
y = conv(x)
assert isinstance(y.grad_fn, torch.autograd.graph.Node)
# this hook will mul 2.0 to the conv weight gradient
handle_y = y.grad_fn.register_hook(lambda gI, gO: (gI[0], gI[1] * 2, gI[2]))
y.sum().backward(retain_graph=True)
ref_res = x.grad
x.grad = None
with compiled_autograd._enable(compiler_fn):
y.sum().backward(retain_graph=True)
res = x.grad
self.assertEqual(res, ref_res)
def test_reorder_all_bwd_hooks(self):
def tensor_hook(grad):
return grad.sub(2.0)
def acc_grad_node_pre_hook(grad_out):
return (grad_out[0].div(5.0),)
def post_acc_grad_hook(tensor):
tensor.grad.add_(3.0)
class TestModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1 = torch.nn.Conv2d(4, 4, 3, bias=False)
self.conv2 = torch.nn.Conv2d(4, 4, 3, bias=False)
self.acc_grad1 = self.conv1.weight.view_as(
self.conv1.weight
).grad_fn.next_functions[0][0]
self.conv1.weight.register_hook(tensor_hook)
self.conv1.weight.register_post_accumulate_grad_hook(post_acc_grad_hook)
self.acc_grad1.register_prehook(acc_grad_node_pre_hook)
def acc_grad_node_post_hook1(grad_in, grad_out):
self.conv1.weight.grad.mul_(0.5)
self.acc_grad1.register_hook(acc_grad_node_post_hook1)
self.acc_grad2 = self.conv2.weight.view_as(
self.conv2.weight
).grad_fn.next_functions[0][0]
self.conv2.weight.register_hook(tensor_hook)
self.conv2.weight.register_post_accumulate_grad_hook(post_acc_grad_hook)
self.acc_grad2.register_prehook(acc_grad_node_pre_hook)
def acc_grad_node_post_hook2(grad_in, grad_out):
self.conv2.weight.grad.mul_(0.5)
self.acc_grad2.register_hook(acc_grad_node_post_hook2)
def forward(self, x):
y = self.conv1(x)
y = self.conv2(y)
return y.sum()
input = torch.randn([1, 4, 32, 32])
# eager ref
model = TestModel()
model(input).backward()
ref_results = [model.conv1.weight.grad, model.conv2.weight.grad]
# cag
model.conv1.weight.grad = None
model.conv2.weight.grad = None
compiled_model = torch.compile(model, backend="inductor")
with compiled_autograd._enable(compiler_fn):
compiled_model(input).backward()
results = [compiled_model.conv1.weight.grad, compiled_model.conv2.weight.grad]
self.assertEqual(results[0], ref_results[0])
self.assertEqual(results[1], ref_results[1])
def test_reorder_multi_post_hooks(self):
class TestModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1 = torch.nn.Conv2d(4, 4, 3, bias=False)
self.conv2 = torch.nn.Conv2d(4, 4, 3, bias=False)
self.acc_grad1 = self.conv1.weight.view_as(
self.conv1.weight
).grad_fn.next_functions[0][0]
def acc_grad_node1_post_hook1(grad_in, grad_out):
self.conv1.weight.grad.mul_(0.5)
def acc_grad_node1_post_hook2(grad_in, grad_out):
self.conv1.weight.grad.sub_(0.3)
self.acc_grad1.register_hook(acc_grad_node1_post_hook1)
self.acc_grad1.register_hook(acc_grad_node1_post_hook2)
self.acc_grad2 = self.conv2.weight.view_as(
self.conv2.weight
).grad_fn.next_functions[0][0]
def acc_grad_node2_post_hook1(grad_in, grad_out):
self.conv2.weight.grad.mul_(0.3)
def acc_grad_node2_post_hook2(grad_in, grad_out):
self.conv2.weight.grad.sub_(0.5)
self.acc_grad2.register_hook(acc_grad_node2_post_hook1)
self.acc_grad2.register_hook(acc_grad_node2_post_hook2)
def forward(self, x):
y = self.conv1(x)
y = self.conv2(y)
return y.sum()
input = torch.randn([1, 4, 32, 32])
# eager ref
model = TestModel()
model(input).backward()
ref_results = [model.conv1.weight.grad, model.conv2.weight.grad]
# cag
model.conv1.weight.grad = None
model.conv2.weight.grad = None
compiled_model = torch.compile(model, backend="inductor")
with compiled_autograd._enable(compiler_fn):
compiled_model(input).backward()
results = [compiled_model.conv1.weight.grad, compiled_model.conv2.weight.grad]
self.assertEqual(results[0], ref_results[0])
self.assertEqual(results[1], ref_results[1])
def test_reorder_multi_pre_hooks(self):
def acc_grad_node_pre_hook1(grad_out):
return (grad_out[0].div(5.0),)
def acc_grad_node_pre_hook2(grad_out):
return (grad_out[0].sub(0.3),)
class TestModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1 = torch.nn.Conv2d(4, 4, 3, bias=False)
self.conv2 = torch.nn.Conv2d(4, 4, 3, bias=False)
self.acc_grad1 = self.conv1.weight.view_as(
self.conv1.weight
).grad_fn.next_functions[0][0]
self.acc_grad1.register_prehook(acc_grad_node_pre_hook1)
self.acc_grad1.register_prehook(acc_grad_node_pre_hook2)
self.acc_grad2 = self.conv2.weight.view_as(
self.conv2.weight
).grad_fn.next_functions[0][0]
self.acc_grad2.register_prehook(acc_grad_node_pre_hook1)
self.acc_grad2.register_prehook(acc_grad_node_pre_hook2)
def forward(self, x):
y = self.conv1(x)
y = self.conv2(y)
return y.sum()
input = torch.randn([1, 4, 32, 32])
# eager ref
model = TestModel()
model(input).backward()
ref_results = [model.conv1.weight.grad, model.conv2.weight.grad]
# cag
model.conv1.weight.grad = None
model.conv2.weight.grad = None
compiled_model = torch.compile(model, backend="inductor")
with compiled_autograd._enable(compiler_fn):
compiled_model(input).backward()
results = [compiled_model.conv1.weight.grad, compiled_model.conv2.weight.grad]
self.assertEqual(results[0], ref_results[0])
self.assertEqual(results[1], ref_results[1])
def test_reorder_multi_tensor_pre_hooks(self):
def tensor_hook1(grad):
return grad.sub(2.0)
def tensor_hook2(grad):
return grad.mul(0.5)
class TestModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1 = torch.nn.Conv2d(4, 4, 3, bias=False)
self.conv2 = torch.nn.Conv2d(4, 4, 3, bias=False)
self.acc_grad1 = self.conv1.weight.view_as(
self.conv1.weight
).grad_fn.next_functions[0][0]
self.conv1.weight.register_hook(tensor_hook1)
self.conv1.weight.register_hook(tensor_hook2)
self.acc_grad2 = self.conv2.weight.view_as(
self.conv2.weight
).grad_fn.next_functions[0][0]
self.conv2.weight.register_hook(tensor_hook1)
self.conv2.weight.register_hook(tensor_hook2)
def forward(self, x):
y = self.conv1(x)
y = self.conv2(y)
return y.sum()
input = torch.randn([1, 4, 32, 32])
# eager ref
model = TestModel()
model(input).backward()
ref_results = [model.conv1.weight.grad, model.conv2.weight.grad]
# cag
model.conv1.weight.grad = None
model.conv2.weight.grad = None
compiled_model = torch.compile(model, backend="inductor")
with compiled_autograd._enable(compiler_fn):
compiled_model(input).backward()
results = [compiled_model.conv1.weight.grad, compiled_model.conv2.weight.grad]
self.assertEqual(results[0], ref_results[0])
self.assertEqual(results[1], ref_results[1])
def test_torch_compile(self):
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.Sigmoid(),
)
opt_model = torch.compile(model, fullgraph=True)
for _ in range(3):
x = torch.randn([1, 4])
result = opt_model(x).sum()
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
model.zero_grad()
self.check_output_and_recompiles(fn)
def test_torch_compile_api_inductor(self):
def fn():
torch.manual_seed(123)
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.Sigmoid(),
)
res = []
for _ in range(3):
x = torch.randn([1, 4])
result = model(x).sum()
result.backward()
res.append(model[0].weight.grad)
res.append(model[0].bias.grad)
model.zero_grad()
return res
expected = fn()
with config.patch(compiled_autograd=True):
compiled_fn = torch.compile(fn)
actual = compiled_fn()
self.assertEqual(expected, actual)
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
def test_torch_compile_api_aot_eager(self):
def fn():
torch.manual_seed(123)
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.Sigmoid(),
)
res = []
for _ in range(3):
x = torch.randn([1, 4])
result = model(x).sum()
result.backward()
res.append(model[0].weight.grad)
res.append(model[0].bias.grad)
model.zero_grad()
return res
expected = fn()
with config.patch(compiled_autograd=True):
compiled_fn = torch.compile(fn, backend="aot_eager")
actual = compiled_fn()
self.assertEqual(expected, actual)
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
def test_torch_compile_api_eager(self):
def fn():
torch.manual_seed(123)
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.Sigmoid(),
)
res = []
for _ in range(3):
x = torch.randn([1, 4])
result = model(x).sum()
result.backward()
res.append(model[0].weight.grad)
res.append(model[0].bias.grad)
model.zero_grad()
return res
expected = fn()
with config.patch(compiled_autograd=True):
compiled_fn = torch.compile(fn, backend="eager")
actual = compiled_fn()
self.assertEqual(expected, actual)
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
def test_multiple_torch_compile(self):
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.Sigmoid(),
)
x = torch.randn([1, 4])
def fn():
result = model(x).sum()
result.backward()
model2 = torch.nn.Linear(4, 4)
x2 = torch.randn([1, 4])
def fn2():
result = model2(x2).sum()
result.backward()
no_ca1 = torch.compile(fn)
no_ca1()
self.assertEqual(counters["compiled_autograd"]["captures"], 0)
counters.clear()
with config.patch(compiled_autograd=True):
with_ca = torch.compile(fn2)
with_ca()
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
counters.clear()
no_ca2 = torch.compile(fn)
no_ca2()
self.assertEqual(counters["compiled_autograd"]["captures"], 0)
def test_torch_compile_graph_break(self):
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.Sigmoid(),
)
x = torch.randn([1, 4])
@torch._dynamo.disable()
def fn():
result = model(x).sum()
result.backward()
with config.patch(compiled_autograd=True):
opt_fn = torch.compile(fn)
opt_fn()
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
def test_torch_compile_graph_break2(self):
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.Sigmoid(),
)
x = torch.randn([1, 4])
@torch._dynamo.disable()
def inner_fn(loss):
loss.backward()
def fn():
result = model(x).sum()
inner_fn(result)
with config.patch(compiled_autograd=True):
opt_fn = torch.compile(fn)
opt_fn()
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
def test_torch_compile_only_backward_call(self):
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.Sigmoid(),
)
x = torch.randn([1, 4])
result = model(x).sum()
with config.patch(compiled_autograd=True):
opt_bwd = torch.compile(lambda: result.backward())
opt_bwd()
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
def test_dynamo_boxed(self):
def get_placeholders(gm_):
placeholders = []
for node in gm_.graph.nodes:
if node.op == "placeholder":
placeholders.append(node)
return placeholders
def eager_with_check(gm, is_bwd):
def inner_compiler(gm_, example_inputs_):
placeholders = get_placeholders(gm_)
if is_bwd:
# should be boxed inputs
assert len(placeholders) == 1
else:
assert len(placeholders) > 1
return gm_
return torch.compile(gm, backend=inner_compiler)
fwd_compiler_fn = functools.partial(eager_with_check, is_bwd=False)
bwd_compiler_fn = functools.partial(eager_with_check, is_bwd=True)
def fn(inputs):
args_0, args_1, args_2 = inputs
out = torch.mm(args_0, args_1)
out = torch.mm(out, args_2)
loss = out.sum()
with compiled_autograd._enable(bwd_compiler_fn):
loss.backward()
yield args_0.grad
yield args_1.grad
yield args_2.grad
inputs = [
torch.randn([1, 2], requires_grad=True),
torch.randn([2, 3], requires_grad=True),
torch.randn([3, 4], requires_grad=True),
]
compiled_fn = eager_with_check(fn, is_bwd=False)
grads = list(compiled_fn(inputs))
self.assertEqual(len(grads), 3)
self.assertNotEqual(grads[0], None)
self.assertNotEqual(grads[1], None)
self.assertNotEqual(grads[2], None)
def test_inputs_aliasing_bytecode_attr_mutations(self):
# Freeze compiled autograd graph
compiler = torch._dynamo.compiled_autograd.AutogradCompilerInstance(compiler_fn)
param = torch.ones(100)
activ = torch.ones(100) * 2
inputs = [param, activ]
proxies, _, _ = compiler.begin_capture(
inputs=inputs, sizes=[], scalars=[], origins=[[], [], []]
)
param_proxy, activ_proxy = proxies
buf = activ_proxy * 2
torch.ops.inductor.accumulate_grad_.default(param_proxy, buf)
runtime_wrapper, compiled_fn = compiler.end_capture(buf)
def bytecode_hook(code, out_code):
import dis
import sys
if sys.version_info < (3, 11):
call_op = "CALL_FUNCTION"
else:
call_op = "CALL"
insts = list(dis.get_instructions(out_code))
call_graph_idx = next(
i for i, inst in enumerate(insts) if inst.opname == call_op
)
# pre-graph should alias: inputs_ref_0 = inputs[0]
matches = [
inst
for inst in insts[:call_graph_idx]
if inst.opname == "STORE_FAST" and inst.argval == "inputs_ref_0"
]
self.assertTrue(len(matches) == 1)
# post-graph should access inputs_ref_0 instead of inputs
matches = [
inst for inst in insts[call_graph_idx:] if inst.argval == "inputs"
]
self.assertTrue(len(matches) == 0)
matches = [
inst
for inst in insts[call_graph_idx:]
if inst.opname == "LOAD_FAST" and inst.argval == "inputs_ref_0"
]
self.assertTrue(len(matches) == 1)
torch._dynamo.reset()
handle = torch._dynamo.convert_frame.register_bytecode_hook(bytecode_hook)
try:
runtime_wrapper(
compiled_fn=compiled_fn,
inputs=[param, activ],
sizes=(),
scalars=(),
hooks=(),
)
finally:
handle.remove()
def test_inputs_aliasing_bytecode_stack_restore(self):
logging.getLogger().setLevel(logging.WARNING)
from torch.testing._internal.logging_tensor import LoggingTensor
# Create a graph that allows inputs stealing
def forward(inputs):
add = inputs[0] + 1
add_1 = add + inputs[1] # handled in suffix for tensor subclass
out = add_1.cpu()
return (out,)
gm = torch.fx.symbolic_trace(forward)
torch._dynamo.utils.set_locals_to_steal(gm, ["inputs"])
compiled_fn = torch.compile(gm)
inputs = [
torch.ones(1000000, dtype=torch.float32),
LoggingTensor(torch.ones(1)),
]
def bytecode_hook(code, out_code):
import dis
import sys
if sys.version_info < (3, 11):
call_op = "CALL_FUNCTION"
else:
call_op = "CALL"
insts = list(dis.get_instructions(out_code))
call_graph_idx = next(
i for i, inst in enumerate(insts) if inst.opname == call_op
)
# pre-graph should alias: inputs_ref_0 = inputs[0]
matches = [
inst
for inst in insts[:call_graph_idx]
if inst.opname == "STORE_FAST" and inst.argval == "inputs_ref_0"
]
self.assertTrue(len(matches) == 1)
# post-graph should access inputs_ref_0 instead of inputs
matches = [
inst for inst in insts[call_graph_idx:] if inst.argval == "inputs"
]
self.assertTrue(len(matches) == 0)
matches = [
inst
for inst in insts[call_graph_idx:]
if inst.opname == "LOAD_FAST" and inst.argval == "inputs_ref_0"
]
self.assertTrue(len(matches) == 1)
torch._dynamo.reset()
handle = torch._dynamo.convert_frame.register_bytecode_hook(bytecode_hook)
try:
out = compiled_fn(inputs)
self.assertTrue(len(inputs) == 0)
finally:
handle.remove()
def test_implicit_add(self):
def fn():
y = torch.randn(1, 4, requires_grad=True)
def model(x):
# y is used multiple times, gradients get added
return torch.sigmoid(x * y + torch.sin(y) + torch.cos(y))
for _ in range(3):
x = torch.randn([1, 4])
result = model(x).sum()
result.backward()
yield result
yield y.grad
y.grad = None
self.check_output_and_recompiles(fn)
def test_output_nodes_all_leaves(self):
def fn():
y = torch.randn(1, 4, requires_grad=True)
z = torch.randn(1, 4, requires_grad=True)
def model(x):
return torch.sigmoid(x * z + torch.sin(y) + torch.cos(y))
for _ in range(3):
x = torch.randn([1, 4])
result = model(x).sum()
gy, gz = torch.autograd.grad(result, inputs=[y, z])
assert y.grad is None
assert z.grad is None
yield gy
yield gz
self.check_output_and_recompiles(fn)
def test_output_nodes_some_leaves(self):
def fn():
class UnreachableBwd(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x
@staticmethod
def backward(ctx, gO):
raise RuntimeError
y = torch.randn(1, 4, requires_grad=True)
z = torch.randn(1, 4, requires_grad=True)
def model(x):
return torch.sigmoid(UnreachableBwd.apply(y) * z)
for _ in range(3):
x = torch.randn([1, 4])
result = model(x).sum()
gz = torch.autograd.grad(result, inputs=[z])
assert y.grad is None
assert z.grad is None
yield gz
self.check_output_and_recompiles(fn)
def test_no_output_nodes_all_leaves(self):
def fn():
y = torch.randn(1, 4, requires_grad=True)
z = torch.randn(1, 4, requires_grad=True)
def model(x):
return torch.sigmoid(x * z + torch.sin(y) + torch.cos(y))
for _ in range(3):
x = torch.randn([1, 4])
result = model(x).sum()
out = result.backward()
assert out is None
assert y.grad is not None
assert z.grad is not None
yield y.grad
yield z.grad
y.grad = None
z.grad = None
self.check_output_and_recompiles(fn)
def test_no_output_nodes_some_leaves(self):
def fn():
class UnreachableBwd(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x
@staticmethod
def backward(ctx, gO):
raise RuntimeError
y = torch.randn(1, 4, requires_grad=True)
z = torch.randn(1, 4, requires_grad=True)
a = torch.randn(1, 4, requires_grad=True)
def model(x):
return torch.sigmoid(x * y * z * UnreachableBwd.apply(a))
for _ in range(3):
x = torch.randn([1, 4])
result = model(x).sum()
out = result.backward(inputs=[y, z])
assert out is None
assert y.grad is not None
assert z.grad is not None
assert a.grad is None
yield y.grad
yield z.grad
y.grad = None
z.grad = None
self.check_output_and_recompiles(fn)
def test_no_output_nodes_different_leaves_will_recompile(self):
def fn():
def fwd(x, y, z):
out = x * y # MulBackward0
out2 = out * z # MulBackward0
return out2.sum() # SumBackward0
x = torch.randn(5, requires_grad=True)
y = torch.randn(5, requires_grad=True)
z = torch.randn(5, requires_grad=True)
loss = fwd(x, y, z)
torch.compile(lambda: torch.autograd.backward(loss, inputs=[x]))()
yield x.grad
x.grad = None
loss = fwd(x, y, z)
torch.compile(lambda: torch.autograd.backward(loss, inputs=[y]))()
yield y.grad
# Guarded by TensorArg id, mismatch on last MulBackward0
self.check_output_and_recompiles(fn, 2)
def test_dynamic_shapes(self):
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
opt_model = torch.compile(model, dynamic=True)
for b in range(10, 100, 10):
x = torch.randn([b, 4])
result = opt_model(x).sum()
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
yield model[2].weight.grad
yield model[2].bias.grad
model.zero_grad()
# TODO(jansel): we should be able to get this count to 1
self.check_output_and_recompiles(fn, count=2)
def test_dynamic_shapes_eager_node(self):
# Here, we have no way of marking the symbolic sizes using in SumBackward as dynamic
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
opt_model = torch.compile(model, dynamic=True)
for b, s in zip([10, 20, 30], [2, 4, 8]):
x = torch.randn([b, 4])
result = opt_model(x)
view = result.view(s, -1)
# sum will save dynamic sizes
loss = view.sum()
loss.backward()
yield model[0].weight.grad
yield model[0].bias.grad
yield model[2].weight.grad
yield model[2].bias.grad
model.zero_grad()
self.check_output_and_recompiles(fn, count=3)
def test_torch_compile_api_dynamic_shapes(self):
# Here, we have no way of marking the symbolic sizes using in SumBackward as dynamic
def fn(call_backward):
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
for b, s in zip([10, 20, 30], [2, 4, 8]):
x = torch.randn([b, 4])
result = model(x)
view = result.view(s, -1)
# sum will save dynamic sizes
loss = view.sum()
call_backward(loss)
yield model[0].weight.grad
yield model[0].bias.grad
yield model[2].weight.grad
yield model[2].bias.grad
model.zero_grad()
def call_backward(loss):
loss.backward()
eager_out = list(fn(call_backward))
with config.patch(compiled_autograd=True):
compiled_out = list(fn(torch.compile(call_backward, dynamic=True)))
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
def test_accumulate_without_zero(self):
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
opt_model = torch.compile(model, dynamic=True)
for _ in range(10):
x = torch.randn([10, 4])
result = opt_model(x).sum()
result.backward()
yield model[0].weight.grad.clone()
yield model[0].bias.grad.clone()
yield model[2].weight.grad.clone()
yield model[2].bias.grad.clone()
self.check_output_and_recompiles(fn, count=2)
def test_inplace_grad_update(self):
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
opt_model = torch.compile(model, dynamic=True)
for _ in range(10):
w_grad = torch.rand_like(model[0].weight)
b_grad = torch.rand_like(model[0].bias)
model[0].weight.grad = w_grad
model[0].bias.grad = b_grad
x = torch.randn([10, 4])
result = opt_model(x).sum()
result.backward()
assert model[0].weight.grad is w_grad
assert model[0].bias.grad is b_grad
yield w_grad.clone()
yield b_grad.clone()
self.check_output_and_recompiles(fn, count=1)
@unittest.skipIf(not HAS_GPU, "requires gpu")
def test_issue106555(self):
DEVICE = torch.device(GPU_TYPE, 0)
NUM_FEATURES = 256
def bias_sigmoid_mul(x1, x2, bias):
x2 = torch.sigmoid(x2 + bias)
y = x1 * x2
return y
bias_sigmoid_mul_jit = torch.compile(bias_sigmoid_mul)
class ModuleWithJit(nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear_1 = nn.Linear(NUM_FEATURES, NUM_FEATURES, bias=True)
self.linear_2 = nn.Linear(NUM_FEATURES, NUM_FEATURES, bias=False)
self.linear_2_bias = nn.Parameter(torch.zeros(NUM_FEATURES))
def forward(self, input_tensor):
x1 = self.linear_1(input_tensor)
x2 = self.linear_2(input_tensor)
output = bias_sigmoid_mul_jit(x1, x2, self.linear_2_bias)
return output
class Model(nn.Module):
def __init__(self) -> None:
super().__init__()
self.module_with_jit_1 = ModuleWithJit()
self.module_with_jit_2 = ModuleWithJit()
def forward(self, x, gradient_checkpointing: bool):
if gradient_checkpointing:
y = torch.utils.checkpoint.checkpoint(
self._forward, x, use_reentrant=True
)
else:
y = self._forward(x)
return y
def _forward(self, x):
x = x + self.module_with_jit_1(x)
x = x + self.module_with_jit_2(x.transpose(-2, -3)).transpose(-2, -3)
return x
device_interface = get_interface_for_device(GPU_TYPE)
device_interface.set_device(device=DEVICE)
torch.manual_seed(1234567890)
model = Model()
model.train()
model.to(device=DEVICE)
model_parameters = list(model.parameters())
torch.manual_seed(1234567890)
input_tensor = torch.randn(1, 128, 256, NUM_FEATURES).to(device=DEVICE)
input_tensor.requires_grad = True
target_tensor = torch.randn(1, 128, 256, NUM_FEATURES).to(
dtype=input_tensor.dtype, device=DEVICE
)
for iteration in range(10):
for param in model_parameters:
param.grad = None
output_tensor = model(
x=input_tensor.clone(),
gradient_checkpointing=True,
)
loss = torch.mean(torch.abs(target_tensor - output_tensor))
loss.backward()
def test_keep_graph_simple(self):
x = torch.tensor([2.0], requires_grad=True)
y = x**2
# First backward pass; keep the computation graph
y.backward(retain_graph=True)
self.assertEqual(x.grad, torch.Tensor([4])) # dy/dx at x=2 is 4
# Note - this will run under both the eager and compiled regime.
def fn():
# Reset the gradients
x.grad = torch.tensor([0.0])
# Second and Third backward pass; keep the computation graph
y.backward(retain_graph=True)
self.assertEqual(x.grad, torch.Tensor([4])) # dy/dx at x=2 is 4
return x.grad
self.check_output_and_recompiles(fn, count=1)
def test_keep_graph_usage_after_compiled(self):
x = torch.tensor([2.0], requires_grad=True)
y = x**2
# First backward pass; keep the computation graph
def eager_check():
y.backward(retain_graph=True)
self.assertEqual(x.grad, torch.Tensor([4])) # dy/dx at x=2 is 4
x.grad = torch.tensor([0.0])
eager_check()
for i in range(0, 5):
with compiled_autograd._enable(compiler_fn):
eager_check()
eager_check()
def test_custom_fn_saved_tensors(self):
def fn():
class MySin(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return torch.sin(x)
@staticmethod
def backward(ctx, gO):
(x,) = ctx.saved_tensors
return gO * torch.cos(x)
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
out = MySin.apply(x)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(fn, count=2)
def test_custom_fn_saved_multiple_tensors(self):
def fn():
class MyFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x, y):
ctx.save_for_backward(x, y)
return torch.sin(x), torch.sin(y)
@staticmethod
def backward(ctx, gO_x, gO_y):
(x, y) = ctx.saved_tensors
return gO_x * torch.cos(x), gO_y * torch.cos(y)
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
y = torch.arange(0.0, i, requires_grad=True)
out1, out2 = MyFn.apply(x, y)
loss = (out1 * out2).sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(fn, count=2)
def test_custom_fn_saved_multiple_tensors_dedup(self):
def fn():
class MyFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x, x)
return torch.sin(x)
@staticmethod
def backward(ctx, gO):
(x1, x2) = ctx.saved_tensors
return gO * torch.cos(x1) * torch.cos(x2)
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
out = MyFn.apply(x)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(fn, count=2)
def test_custom_fn_saved_shape_tensor(self):
def fn():
class MyFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return x
@staticmethod
def backward(ctx, gO):
(x,) = ctx.saved_tensors
return gO * x.shape[0]
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
out = MyFn.apply(x)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(fn, count=2)
def test_custom_fn_saved_attr(self):
def fn():
class MyFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.shape = x.shape
return x
@staticmethod
def backward(ctx, gO):
x_shape = ctx.shape[0]
return gO * x_shape
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
out = MyFn.apply(x)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(
fn, count=2, compiler_fn=make_compiler_fn(fullgraph=False)
)
def test_custom_fn_multiple_grads(self):
def fn():
class MyFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x, y):
return x + y, y
@staticmethod
def backward(ctx, gO_1, gO_2):
return gO_1, gO_2
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
y = torch.arange(0.0, i, requires_grad=True)
out1, out2 = MyFn.apply(x, y)
loss = (out1 + out2).sum()
loss.backward()
yield x.grad
yield y.grad
self.check_output_and_recompiles(fn, count=2)
def test_custom_fn_non_variable_input(self):
def fn():
class MyFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x, y, z):
return x * 2, y * 3, z * 4
@staticmethod
def backward(ctx, gO_1, gO_2, gO_3):
return gO_1, gO_2, gO_3
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
y = 1
z = torch.arange(0.0, i, requires_grad=True)
out1, out2, out3 = MyFn.apply(x, y, z)
loss = (out1 + out2 + out3).sum()
loss.backward()
yield x
yield y
yield z
self.check_output_and_recompiles(fn, count=2)
@unittest.skipIf(not HAS_GPU, "requires gpu")
def test_logging_tensor_flaky(self) -> None:
# when you first run some test using triton and then run test_inputs_aliasing_bytecode_stack_restore
# resulting in:
# - pytest: `TypeError: unsupported operand type(s) for +: 'Tensor' and 'LoggingTensor'`
# - python: `TypeError: not all arguments converted during string formatting`
# 1. some triton involving test
def fn():
def _fn(x):
return x
x = torch.arange(
1, 10, requires_grad=True, dtype=torch.float16, device=GPU_TYPE
)
out = _fn(x)
loss = out.sum()
loss.backward()
with compiled_autograd._enable(compiler_fn):
fn()
logging.getLogger().setLevel(
logging.WARNING
) # triton setup overwrote it to INFO
# 2. test_inputs_aliasing_bytecode_stack_restore
from torch.testing._internal.logging_tensor import LoggingTensor
def forward(inputs):
add = inputs[0] + 1
add_1 = add + inputs[1]
out = add_1.cpu()
return (out,)
gm = torch.fx.symbolic_trace(forward)
print(gm.print_readable())
torch._dynamo.utils.set_locals_to_steal(gm, ["inputs"])
compiled_fn = torch.compile(gm)
inputs = [
torch.ones(1000000, dtype=torch.float32),
LoggingTensor(torch.ones(1)),
]
compiled_fn(inputs)
@unittest.skipIf(not HAS_GPU, "requires gpu")
def test_custom_fn_output_metadata(self):
def my_compiler_fn(gm):
for node in gm.graph.nodes:
if isinstance(node.target, torch._ops.OpOverload):
assert (
node.target._name != "aten::_to_copy"
), "there should be no implicit copies (e.g. dtype casting)"
def inner_compiler(gm_, example_inputs_):
counters["compiled_autograd"]["compiles"] += 1
return inductor.compile(gm_, example_inputs_)
return torch.compile(
gm, backend=inner_compiler, fullgraph=True, dynamic=True
)
def fn():
class MyFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x
@staticmethod
def backward(ctx, gO):
return gO
x = torch.arange(
1, 10, requires_grad=True, dtype=torch.float16, device=GPU_TYPE
)
x_view = x.view(3, 3)
out = MyFn.apply(x_view)
loss = out.sum()
loss.backward()
yield x.dtype
yield x.device
yield x.grad
self.check_output_and_recompiles(fn, count=1)
def test_custom_fn_with_same_graph(self):
def fn():
class MyFn1(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x
@staticmethod
def backward(ctx, gO):
return gO
# same as MyFn1, but different autograd function id
# should not be using same graph as MyFn1
class MyFn2(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x
@staticmethod
def backward(ctx, gO):
return gO
for myfn in [MyFn1, MyFn2, MyFn1, MyFn2]:
x = torch.arange(0.0, 10, requires_grad=True)
out = myfn.apply(x)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(
fn, count=2
) # should compile once for MyFn1 and once for MyFn2
def test_custom_fn_dynamically_defined_class(self):
def fn():
def create_class(multiplier: int):
class DynamicFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x * multiplier
@staticmethod
def backward(ctx, gO):
return gO * multiplier
return DynamicFn
for multiplier in [10, 20, 30]:
x = torch.arange(0.0, 10, requires_grad=True)
out = create_class(multiplier).apply(x)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(fn, count=3)
def test_custom_fn_bw_graph_break(self):
def fn():
class MySin(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return torch.sin(x)
@staticmethod
def backward(ctx, gO):
print("graph break")
(x,) = ctx.saved_tensors
print("graph break")
return gO * torch.cos(x)
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
out = MySin.apply(x)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(
fn, count=[2, 6], compiler_fn=make_compiler_fn(fullgraph=False)
)
def test_custom_fn_compiled_fw_graph_break(self):
def fn():
class MySin(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
print("graph break")
ctx.save_for_backward(x)
return torch.sin(x)
@staticmethod
def backward(ctx, gO):
(x,) = ctx.saved_tensors
return gO * torch.cos(x)
opt_model = torch.compile(MySin.apply)
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
out = opt_model(x)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(
fn, count=2, compiler_fn=make_compiler_fn(fullgraph=False)
)
self.assertEqual(counters["stats"]["unique_graphs"], 5) # 3 fw, 2 bw
def test_custom_fn_compiled_fw_bw_graph_break(self):
def fn():
class MySin(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
print("graph break")
ctx.save_for_backward(x)
return torch.sin(x)
@staticmethod
def backward(ctx, gO):
print("graph break")
(x,) = ctx.saved_tensors
return gO * torch.cos(x)
opt_model = torch.compile(MySin.apply)
for i in [10, 100, 10, 15, 20, 25]:
x = torch.arange(0.0, i, requires_grad=True)
out = opt_model(x)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(
fn, count=[2, 6], compiler_fn=make_compiler_fn(fullgraph=False)
)
self.assertEqual(counters["stats"]["unique_graphs"], 9) # 3 fw, 6 bw
def test_mismatch_fake_tensor_mode(self, dynamic_shape=False):
"""
Repro the failure of training nanogpt with both compiled-autograd
and _LazyGraphModule. Check https://github.com/pytorch/pytorch/pull/118981
for more context.
"""
B = 8
x = torch.rand(B, 16)
y = torch.rand(B, 16, requires_grad=True)
if dynamic_shape:
torch._dynamo.mark_dynamic(x, 0)
torch._dynamo.mark_dynamic(y, 0)
def f():
y.grad = None
out = x + y
# make sure the backward call does not trigger any error when
# compiling the backward graph
out.sum().backward()
return out, y.grad
self.check_output_and_recompiles(f, compile_fn=True)
def test_mismatch_fake_tensor_mode_dynamic_shape(self):
self.test_mismatch_fake_tensor_mode(dynamic_shape=True)
def test_accumulate_grad_accuracy(self):
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(2, 1, bias=False),
torch.nn.Linear(1, 2, bias=False),
)
x = torch.randn(2, 2)
out = model(x)
loss = out.sum()
torch.manual_seed(0)
loss.backward()
yield model[0].weight.grad
yield model[1].weight.grad
self.check_output_and_recompiles(fn, 1)
def test_trace_run_with_rng_state(self):
def sdpa(xq, xk):
return F.scaled_dot_product_attention(xq, xk, xk, is_causal=True)
def g(xq_1, xk_1, xq_2, xk_2):
# xq: (bs, n_local_heads, seqlen, head_dim)
# xk: (bs, n_local_heads, cache_len + seqlen, head_dim)
y1 = sdpa(xq_1, xk_1)
y2 = torch.utils.checkpoint.checkpoint(
sdpa, xq_2, xk_2, use_reentrant=False
)
y = torch.mul(y1, y2)
z = torch.matmul(y, y)
return z
def f():
bs = 1
n_local_heads = 1
seqlen = 2
head_dim = 2
cache_len = 2
xq_list = [
torch.ones(
(bs, n_local_heads, seqlen, head_dim),
requires_grad=True,
device="cpu",
)
for _ in range(2)
]
xk_list = [
torch.ones(
(bs, n_local_heads, cache_len + seqlen, head_dim),
requires_grad=True,
device="cpu",
)
for _ in range(2)
]
out = torch.compile(g, fullgraph=True)(
xq_list[0], xk_list[0], xq_list[1], xk_list[1]
)
out.sum().backward()
return out, *[x.grad for x in xq_list + xk_list]
"""
Walkthrough of what happens with `run_with_rng_state`:
1. `run_with_rng_state` only shows up in the backward graph (this op is inserted by the partitioner).
2. The Dynamo graph captured by Compiled Autograd looks like:
```
===== __compiled_fn_3 =====
torch/fx/_lazy_graph_module.py class GraphModule(torch.nn.Module):
def forward(self, L_inputs_ : list):
...
run_with_rng_state = torch.ops.higher_order.run_with_rng_state(
getitem_8,
torch.ops.aten._scaled_dot_product_flash_attention_for_cpu.default,
getitem_3, getitem_4, getitem_4, 0.0, True,
)
...
```
3. We want to preserve this `run_with_rng_state` op when going through AOTAutograd. We do it by having special handling
in `run_with_rng_state` op's py_functionalize_impl.
"""
def _run_with_rng_state_op_check(inductor_post_grad_graph):
# Checks that `run_with_rng_state` op exists in Compiled Autograd's Inductor post-grad graph.
op_set = {node.target for node in inductor_post_grad_graph.nodes}
if torch.ops.higher_order.run_and_save_rng_state not in op_set:
# This is backward graph, so check existence of `run_with_rng_state` op
self.assertTrue(torch.ops.higher_order.run_with_rng_state in op_set)
with torch._inductor.config.patch(
post_grad_custom_post_pass=_run_with_rng_state_op_check
):
compiler_fn = make_compiler_fn(fullgraph=True)
def make_compiler_fn_with_op_check():
def _compiler_fn(gm):
# Checks that `run_with_rng_state` op exists in Compiled Autograd's Dynamo graph.
self.assertTrue(
any(
node.target is torch.ops.higher_order.run_with_rng_state
for node in gm.graph.nodes
)
)
return compiler_fn(gm)
return _compiler_fn
compiler_fn_with_op_check = make_compiler_fn_with_op_check()
self.check_output_and_recompiles(
f, compiler_fn=compiler_fn_with_op_check, compile_fn=False
)
@torch._inductor.config.patch(enable_auto_functionalized_v2=True)
def test_trace_auto_functionalized_v2(self):
self.trace_auto_functionalized_base()
@torch._inductor.config.patch(enable_auto_functionalized_v2=False)
def test_trace_auto_functionalized(self):
self.trace_auto_functionalized_base()
def trace_auto_functionalized_base(self):
with torch.library._scoped_library("testlib", "FRAGMENT") as lib:
torch.library.define(
"testlib::foo",
"(Tensor(a!) x) -> (Tensor)",
tags=torch.Tag.pt2_compliant_tag,
lib=lib,
)
torch.library.define(
"testlib::foo_mutated",
"(Tensor(a!) x) -> (Tensor)",
tags=torch.Tag.pt2_compliant_tag,
lib=lib,
)
@torch.library.impl("testlib::foo", "cpu", lib=lib)
def foo(x):
x.add_(5)
return x
@torch.library.impl("testlib::foo", "Meta", lib=lib)
def foo_meta(x):
return x
@torch.library.impl(
"testlib::foo_mutated", "CompositeImplicitAutograd", lib=lib
)
def foo_mutated(x):
return torch.ops.testlib.foo(x)
def _get_custom_policy(must_recompute_list=None):
def _custom_policy(ctx, func, *args, **kwargs):
if must_recompute_list is not None and func in must_recompute_list:
return torch.utils.checkpoint.CheckpointPolicy.MUST_RECOMPUTE
else:
return torch.utils.checkpoint.CheckpointPolicy.PREFER_RECOMPUTE
return _custom_policy
def context_fn():
must_recompute_list = [
torch.ops.higher_order.auto_functionalized,
]
return torch.utils.checkpoint.create_selective_checkpoint_contexts(
_get_custom_policy(
must_recompute_list=must_recompute_list,
),
)
def g(x):
x = torch.matmul(x, x)
torch.ops.testlib.foo_mutated(x)
return torch.matmul(x, x)
def g_cp(x):
return torch.utils.checkpoint.checkpoint(
g, x, use_reentrant=False, context_fn=context_fn
)
def f():
inps = (torch.randn(4, 4, requires_grad=True),)
output = torch.compile(g_cp, backend="aot_eager", fullgraph=True)(*inps)
output.sum().backward()
return output, inps[0].grad
"""
Walkthrough of what happens with `auto_functionalized`:
1. `auto_functionalized` op is inserted into the graph during AOTAutograd functionalization.
We force the op to be recomputed (by using SAC), so it appears in the backward graph.
2. The AOT backward graph looks like:
```
===== Backward graph 0 =====
def forward(self, primals_1: "f32[4, 4][4, 1]cpu", tangents_1: "f32[4, 4][4, 1]cpu"):
...
X = torch.ops.higher_order.auto_functionalized(torch.ops.testlib.foo.default, x = mm)
...
return (add_1,)
```
3. The Compiled Autograd graph looks like:
```
===== Compiled autograd graph =====
def forward(self, inputs, sizes, scalars, hooks):
...
X = torch.ops.higher_order.auto_functionalized(torch.ops.testlib.foo.default, x = aot0_mm)
...
return []
```
4. The Dynamo graph captured by Compiled Autograd looks like:
```
===== __compiled_fn_3 =====
def forward(self, L_inputs_ : list):
...
X = torch.ops.higher_order.auto_functionalized(torch.ops.testlib.foo.default, x = aot0_mm)
...
return (new_grad,)
```
5. The Compiled Autograd's AOT "forward-only" graph looks like:
```
===== Forward graph 1 =====
def forward(self, arg0_1: "f32[][]cpu", arg1_1: "f32[4, 4][4, 1]cpu"):
...
X = torch.ops.higher_order.auto_functionalized(torch.ops.testlib.foo.default, x = mm)
...
return (clone_1,)
```
6. The `auto_functionalized` op should then be lowered using the normal lowering path in Inductor.
"""
compiler_fn = make_compiler_fn(fullgraph=True, backend="aot_eager")
def make_compiler_fn_with_op_check():
def _compiler_fn(gm):
auto_functionalize_func = (
torch.ops.higher_order.auto_functionalized
if not torch._inductor.config.enable_auto_functionalized_v2
else torch.ops.higher_order.auto_functionalized_v2
)
# Checks that `auto_functionalized` op exists in Compiled Autograd's Dynamo graph.
self.assertTrue(
any(
node.target is auto_functionalize_func
for node in gm.graph.nodes
),
f"{auto_functionalize_func} op not found in {gm.graph}",
)
return compiler_fn(gm)
return _compiler_fn
compiler_fn_with_op_check = make_compiler_fn_with_op_check()
self.check_output_and_recompiles(
f, compiler_fn=compiler_fn_with_op_check, compile_fn=False
)
@scoped_load_inline
def test_non_traceable_autograd_cpp_node(self, load_inline):
cpp_source = """
struct CustomOpAutogradFunction : public torch::autograd::Function<CustomOpAutogradFunction> {
static constexpr bool is_traceable = false;
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(torch::Tensor x) {
return CustomOpAutogradFunction::apply(x);
}
TORCH_LIBRARY(test_non_traceable_autograd_cpp_node, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
}
"""
module = load_inline(
name="test_non_traceable_autograd_cpp_node",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
def fn():
x = torch.ones(10, 10, requires_grad=True)
out = torch.ops.test_non_traceable_autograd_cpp_node.custom_op_backed_by_autograd_fn(
x
)
loss = out.sum()
loss.backward()
with self.assertRaisesRegex(
RuntimeError,
"https://docs.google.com/document/d/11VucFBEewzqgkABIjebZIzMvrXr3BtcY1aGKpX61pJY/",
), compiled_autograd._enable(compiler_fn):
fn()
@scoped_load_inline
def test_autograd_cpp_node(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(torch::Tensor x) {
return CustomOpAutogradFunction::apply(x);
}
TORCH_LIBRARY(test_autograd_cpp_node, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
}
"""
module = load_inline(
name="test_autograd_cpp_node",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
def fn():
for i in [10, 100, 10, 20, 10]:
x = torch.ones(i, i, requires_grad=True)
out = torch.ops.test_autograd_cpp_node.custom_op_backed_by_autograd_fn(
x
)
loss = out.sum()
loss.backward()
yield x.grad
# compiles for 10 (static) and 100 (dynamic)
self.check_output_and_recompiles(fn, 2)
@scoped_load_inline
def test_autograd_cpp_node_id(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;
}
};
struct CustomOpAutogradFunction2 : public torch::autograd::Function<CustomOpAutogradFunction2> {
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(torch::Tensor x) {
return CustomOpAutogradFunction::apply(x);
}
torch::Tensor custom_op_backed_by_autograd_fn2(torch::Tensor x) {
return CustomOpAutogradFunction2::apply(x);
}
TORCH_LIBRARY(test_autograd_cpp_node_id, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
m.def("custom_op_backed_by_autograd_fn2", custom_op_backed_by_autograd_fn2);
}
"""
module = load_inline(
name="test_autograd_cpp_node_id",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
def same_autograd_fn():
def fn():
x = torch.ones(10, 10, requires_grad=True)
out = (
torch.ops.test_autograd_cpp_node_id.custom_op_backed_by_autograd_fn(
x
)
)
loss = out.sum()
loss.backward()
yield x.grad
yield from fn() # compile
yield from fn() # reuse
yield from fn() # reuse
yield from fn() # reuse
self.check_output_and_recompiles(same_autograd_fn, 1)
def different_autograd_fn():
def fn(op):
x = torch.ones(10, 10, requires_grad=True)
out = op(x)
loss = out.sum()
loss.backward()
yield x.grad
op1 = torch.ops.test_autograd_cpp_node_id.custom_op_backed_by_autograd_fn
op2 = torch.ops.test_autograd_cpp_node_id.custom_op_backed_by_autograd_fn2
yield from fn(op1) # compile
yield from fn(op2) # compile
yield from fn(op1) # reuse
yield from fn(op2) # reuse
self.check_output_and_recompiles(different_autograd_fn, 2)
@scoped_load_inline
def test_autograd_cpp_node_saved(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,
const torch::Tensor& y,
const torch::Tensor& fixed) {
ctx->save_for_backward({x, y});
ctx->saved_data["fixed_tensor"] = fixed;
ctx->saved_data["bool"] = true;
ctx->saved_data["int"] = 1;
c10::List<std::string> list({"string"});
ctx->saved_data["list"] = std::move(list);
c10::Dict<std::string, double> dict;
dict.insert("string", 1.0);
ctx->saved_data["dict"] = std::move(dict);
return x;
}
static torch::autograd::variable_list backward(
torch::autograd::AutogradContext *ctx,
torch::autograd::variable_list grad_output) {
const auto& saved_variables = ctx->get_saved_variables();
assert(saved_variables.size() == 2);
torch::Tensor x = saved_variables[0];
torch::Tensor y = saved_variables[1];
torch::Tensor fixed = ctx->saved_data["fixed_tensor"].toTensor();
assert(ctx->saved_data["bool"].isBool());
c10::SymInt i = ctx->saved_data["int"].toSymInt();
c10::List<c10::IValue> list = ctx->saved_data["list"].toList();
assert(list.size() == 1);
assert(list.get(0).toStringRef() == "string");
c10::Dict<c10::IValue, c10::IValue> dict = ctx->saved_data["dict"].toGenericDict();
assert(dict.size() == 1);
assert(dict.at("string") == 1.0);
torch::autograd::variable_list grad_inputs(3);
grad_inputs[0] = x + y + torch::sum(fixed) + i;
return grad_inputs;
}
};
torch::Tensor custom_op_backed_by_autograd_fn(const torch::Tensor& x, const torch::Tensor& y, const torch::Tensor& fixed) {
return CustomOpAutogradFunction::apply(x, y, fixed);
}
TORCH_LIBRARY(test_autograd_cpp_node_saved, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
}
"""
module = load_inline(
name="test_autograd_cpp_node_saved",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
def fn():
fixed = torch.ones(2, 2)
for i in [10, 100, 10, 20, 10]:
x = torch.ones(i, i, requires_grad=True)
y = torch.randn(i, i)
out = torch.ops.test_autograd_cpp_node_saved.custom_op_backed_by_autograd_fn(
x, y, fixed
)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(fn, 2)
@scoped_load_inline
def test_autograd_cpp_node_saved_dynamic(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) {
ctx->save_for_backward({x});
ctx->saved_data["dynamic"] = x.view(-1);
return x;
}
static torch::autograd::variable_list backward(
torch::autograd::AutogradContext *ctx,
torch::autograd::variable_list grad_output) {
const auto& saved_variables = ctx->get_saved_variables();
assert(saved_variables.size() == 1);
torch::Tensor x = saved_variables[0];
torch::Tensor z = ctx->saved_data["dynamic"].toTensor();
torch::autograd::variable_list grad_inputs(1);
grad_inputs[0] = x + torch::sum(z);
return grad_inputs;
}
};
torch::Tensor custom_op_backed_by_autograd_fn(const torch::Tensor& x) {
return CustomOpAutogradFunction::apply(x);
}
TORCH_LIBRARY(test_autograd_cpp_node_saved_dynamic, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
}
"""
module = load_inline(
name="test_autograd_cpp_node_saved_dynamic",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
def fn():
for i in [10, 100, 10, 20, 10]:
x = torch.ones(i, i, requires_grad=True)
out = torch.ops.test_autograd_cpp_node_saved_dynamic.custom_op_backed_by_autograd_fn(
x
)
loss = out.sum()
loss.backward()
yield x.grad
# compiles for 10 (static) and 100 (dynamic)
self.check_output_and_recompiles(fn, 2)
@scoped_load_inline
def test_autograd_cpp_node_saved_int(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,
int64_t y) {
ctx->save_for_backward({x});
ctx->saved_data["int"] = y;
ctx->saved_data["symint"] = c10::SymInt(y);
return x;
}
static torch::autograd::variable_list backward(
torch::autograd::AutogradContext *ctx,
torch::autograd::variable_list grad_output) {
const auto& saved_variables = ctx->get_saved_variables();
assert(saved_variables.size() == 1);
torch::Tensor x = saved_variables[0];
c10::SymInt y = ctx->saved_data["int"].toSymInt();
c10::SymInt ys = ctx->saved_data["symint"].toSymInt();
torch::autograd::variable_list grad_inputs(2);
grad_inputs[0] = x + y + ys;
return grad_inputs;
}
};
torch::Tensor custom_op_backed_by_autograd_fn(const torch::Tensor& x, int64_t y) {
return CustomOpAutogradFunction::apply(x, y);
}
TORCH_LIBRARY(test_autograd_cpp_node_saved_int, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
}
"""
module = load_inline(
name="test_autograd_cpp_node_saved_int",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
def fn():
for y in [1, 2, 3, 1]:
x = torch.ones(10, 10, requires_grad=True)
out = torch.ops.test_autograd_cpp_node_saved_int.custom_op_backed_by_autograd_fn(
x, y
)
loss = out.sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(fn, 1)
@scoped_load_inline
def test_autograd_cpp_node_saved_float(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,
double z) {
ctx->save_for_backward({x});
ctx->saved_data["float"] = z;
ctx->saved_data["symfloat"] = c10::SymFloat(z);
return x;
}
static torch::autograd::variable_list backward(
torch::autograd::AutogradContext *ctx,
torch::autograd::variable_list grad_output) {
const auto& saved_variables = ctx->get_saved_variables();
assert(saved_variables.size() == 1);
torch::Tensor x = saved_variables[0];
c10::SymFloat z = ctx->saved_data["float"].toSymFloat();
c10::SymFloat zs = ctx->saved_data["symfloat"].toSymFloat();
torch::autograd::variable_list grad_inputs(2);
grad_inputs[0] = x + z + zs;
return grad_inputs;
}
};
torch::Tensor custom_op_backed_by_autograd_fn(const torch::Tensor& x, double z) {
return CustomOpAutogradFunction::apply(x, z);
}
TORCH_LIBRARY(test_autograd_cpp_node_saved_float, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
}
"""
module = load_inline(
name="test_autograd_cpp_node_saved_float",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
def fn():
for z in [1.1, 2.2, 3.3, 1.1]:
x = torch.ones(10, 10, requires_grad=True)
out = torch.ops.test_autograd_cpp_node_saved_float.custom_op_backed_by_autograd_fn(
x, z
)
loss = out.sum()
loss.backward()
yield x.grad
# compiled autograd and dynamo both support symfloat, but not backend
self.check_output_and_recompiles(fn, [1, 3])
@scoped_load_inline
def test_autograd_cpp_node_data_dependent(self, load_inline):
cpp_source = """
struct CustomOpAutogradFunction : public torch::autograd::Function<CustomOpAutogradFunction> {
static constexpr bool is_traceable = true;
static int iteration;
static torch::autograd::variable_list forward(
torch::autograd::AutogradContext* ctx,
const torch::Tensor& x,
const torch::Tensor& y) {
ctx->save_for_backward({x, y});
ctx->saved_data["bool"] = true;
ctx->saved_data["int"] = 1;
switch (iteration) {
case 0: {
break;
}
case 1: {
// recompile
ctx->saved_data["forces_recompile"] = iteration;
break;
}
case 2: {
// recompile
ctx->set_materialize_grads(false);
break;
}
case 3: {
// reuse
break;
}
default: {
throw std::runtime_error("unexpected iteration");
}
}
iteration++;
return {x, y};
}
static torch::autograd::variable_list backward(
torch::autograd::AutogradContext *ctx,
torch::autograd::variable_list grad_output) {
const auto& saved_variables = ctx->get_saved_variables();
assert(saved_variables.size() == 2);
torch::Tensor x = saved_variables[0];
torch::Tensor y = saved_variables[1];
c10::SymInt i = ctx->saved_data["int"].toSymInt();
torch::autograd::variable_list grad_inputs(2);
grad_inputs[0] = x + y + i;
return grad_inputs;
}
};
int CustomOpAutogradFunction::iteration = 0;
torch::autograd::variable_list custom_op_backed_by_autograd_fn(const torch::Tensor& x, const torch::Tensor& y) {
return CustomOpAutogradFunction::apply(x, y);
}
void reset() {
CustomOpAutogradFunction::iteration = 0;
}
TORCH_LIBRARY(test_autograd_cpp_node_data_dependent, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
m.def("reset", reset);
}
"""
module = load_inline(
name="test_autograd_cpp_node_data_dependent",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
def fn():
torch.ops.test_autograd_cpp_node_data_dependent.reset()
for i in [10, 10, 10, 10]:
x = torch.ones(i, i, requires_grad=True)
y = torch.randn(i, i)
(
out1,
out2,
) = torch.ops.test_autograd_cpp_node_data_dependent.custom_op_backed_by_autograd_fn(
x, y
)
loss = (out1 + out2).sum()
loss.backward()
yield x.grad
self.check_output_and_recompiles(fn, 3)
@unittest.skipIf(not HAS_GPU, "requires gpu")
def test_free_activation_memory(self):
script = """
import torch
from torch._dynamo.device_interface import get_interface_for_device
from torch.testing._internal.inductor_utils import GPU_TYPE
def main():
device_interface = get_interface_for_device(GPU_TYPE)
assert(device_interface.memory_allocated() == 0)
# Use an op to check that the memory is freed by the time the op is executed
def assertion_impl(to_clone):
mem_allocated = device_interface.memory_allocated()
assert mem_allocated < 4000000 # some activations should be freed
return to_clone.clone()
with torch.library._scoped_library("test_compiled_autograd", "FRAGMENT") as lib:
lib.define(
"assertion_op(Tensor x) -> Tensor", tags=(torch.Tag.pt2_compliant_tag,)
)
lib.impl("assertion_op", assertion_impl, "CPU")
lib.impl("assertion_op", lambda x: x.clone(), "Meta")
# Create a graph that allows inputs stealing
def forward(activations):
add = activations[0] + 1
out = add.cpu()
cloned_out = torch.ops.test_compiled_autograd.assertion_op(out)
return (cloned_out,)
gm = torch.fx.symbolic_trace(forward)
torch._dynamo.utils.set_locals_to_steal(gm, ["activations"])
compiled_fn = torch.compile(gm)
# allocate at least 4,000,000 bytes (1,000,000 * 4 bytes)
activations = [torch.ones(1000000, dtype=torch.float32, device=GPU_TYPE)]
assert device_interface.memory_allocated() > 4000000
out = compiled_fn(activations)
assert len(activations) == 0
main()
"""
self.run_as_subprocess(script)
@unittest.skipIf(not HAS_GPU, "requires gpu")
def test_free_activation_memory_subclass(self):
# cover the case when aot inputs have subclasses, resulting in a different runtime wrapper
script = """
import torch
from torch._dynamo.device_interface import get_interface_for_device
from torch.testing._internal.inductor_utils import GPU_TYPE
def main():
device_interface = get_interface_for_device(GPU_TYPE)
assert device_interface.memory_allocated() == 0
# Use an op to check that the memory is freed by the time the op is executed
def assertion_impl(to_clone):
mem_allocated = device_interface.memory_allocated()
assert mem_allocated < 1200000 # some activations should be freed
assert mem_allocated > 800000 # currently subclasses don't seem to be freed in inductor
return to_clone.clone()
with torch.library._scoped_library("test_compiled_autograd", "FRAGMENT") as lib:
lib.define(
"assertion_op(Tensor x) -> Tensor", tags=(torch.Tag.pt2_compliant_tag,)
)
lib.impl("assertion_op", assertion_impl, "CPU")
lib.impl("assertion_op", lambda x: x.clone(), "Meta")
lib.impl("assertion_op", lambda x: x.clone(), "NestedTensor")
def fn(inputs):
_, y = inputs
out = y.cpu()
cloned_out = torch.ops.test_compiled_autograd.assertion_op(out)
return cloned_out
gm = torch.fx.symbolic_trace(fn)
torch._dynamo.utils.set_locals_to_steal(gm, ["inputs"])
compiled_fn = torch.compile(gm)
from torch.nested._internal.nested_tensor import jagged_from_list
activations = [
jagged_from_list(
[
torch.ones((1, 100000), device=GPU_TYPE), # 400,000 bytes
torch.ones((1, 100000), device=GPU_TYPE), # 400,000 bytes
],
None,
)[
0
], # NestedTensor
torch.ones((1, 100000), device=GPU_TYPE), # 400,000 bytes
]
# 1,200,000 bytes (3 * 4 * 100,000 bytes)
assert device_interface.memory_allocated() > 1200000
out = compiled_fn(activations)
assert len(activations) == 0
main()
"""
self.run_as_subprocess(script)
def test_callback_graph_break_throws_error(self):
called = [0]
def callback_final():
called[0] += 1
class MyFunc(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
return input
@staticmethod
@torch.autograd.function.once_differentiable
def backward(ctx, grad):
torch.autograd.Variable._execution_engine.queue_callback(callback_final)
torch._dynamo.graph_break()
return grad
a = torch.rand((3, 3), requires_grad=True)
with self.assertRaisesRegex(
AssertionError,
"only supported when Compiled Autograd is enabled with fullgraph=True",
):
with compiled_autograd._enable(make_compiler_fn(fullgraph=False)):
b = MyFunc.apply(a)
b.sum().backward()
@unittest.skipIf(not HAS_CUDA, "requires cuda")
def test_cudagraphs_cpu_division(self):
from torch._dynamo.testing import reduce_to_scalar_loss
model = torch.nn.Linear(10, 10, dtype=torch.float16).cuda()
inputs = torch.randn(10, 10, dtype=torch.float16).cuda()
out = model(inputs)
loss = reduce_to_scalar_loss(out)
stderr_msgs = io.StringIO()
with mock.patch("sys.stderr", stderr_msgs), compiled_autograd._enable(
compiler_fn
):
torch._inductor.config.triton.cudagraphs = True
loss.backward()
torch._inductor.config.triton.cudagraphs = False
self.assertFalse("skipping cudagraphs" in stderr_msgs.getvalue())
def test_cudagraphs_cpu_graph(self):
from torch._dynamo.testing import reduce_to_scalar_loss
model = torch.nn.Linear(10, 10, dtype=torch.float16)
inputs = torch.randn(10, 10, dtype=torch.float16)
out = model(inputs)
loss = reduce_to_scalar_loss(out)
with compiled_autograd._enable(compiler_fn):
torch._inductor.config.triton.cudagraphs = True
loss.backward()
torch._inductor.config.triton.cudagraphs = False
self.assertEqual(counters["inductor"]["cudagraph_skips"], 1)
@unittest.skipIf(not HAS_CUDA, "requires cuda")
def test_cudagraphs_sdpa(self):
query = torch.rand(
32, 8, 128, 64, dtype=torch.float16, device="cuda", requires_grad=True
)
key = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
value = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
out = torch.nn.functional.scaled_dot_product_attention(query, key, value)
with config.patch(compiled_autograd=True), inductor_config.patch(
"triton.cudagraphs", True
):
opt_bwd = torch.compile(lambda: out.sum().backward())
opt_bwd()
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
self.assertEqual(counters["inductor"]["cudagraph_skips"], 0)
@unittest.skipIf(not HAS_CUDA, "requires cuda")
def test_cudagraphs_cpu_scalar_used_in_python_custom_op(self):
class MyFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
cpu_tensor = torch.tensor(5)
ctx.save_for_backward(x, cpu_tensor) # visible to c++/autograd
ctx.cpu_scalar = 5 # opaque to c++/autograd
return x.sum()
@staticmethod
def backward(ctx, gO):
x, cpu_tensor = ctx.saved_tensors
expand = gO * torch.ones_like(x)
return expand * cpu_tensor * ctx.cpu_scalar
x = torch.randn(10, requires_grad=True, device="cuda")
out = MyFn.apply(x)
with config.patch(compiled_autograd=True), inductor_config.patch(
"triton.cudagraphs", True
):
opt_bwd = torch.compile(lambda: out.backward())
opt_bwd()
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
# Compiled autograd lifts custom autograd.Function bwd instead of tracing it.
# Must skip since we do not know if the cpu scalar will be used only in ATen/prim ops.
self.assertEqual(counters["inductor"]["cudagraph_skips"], 1)
@scoped_load_inline
@unittest.skipIf(not HAS_CUDA, "requires cuda")
def test_cudagraphs_cpu_scalar_used_in_cpp_custom_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) {
const auto& cpu_tensor = torch::tensor(1);
ctx->save_for_backward({x, cpu_tensor});
ctx->saved_data["cpu_scalar"] = 1;
return x;
}
static torch::autograd::variable_list backward(
torch::autograd::AutogradContext *ctx,
torch::autograd::variable_list grad_output) {
const auto& saved_variables = ctx->get_saved_variables();
assert(saved_variables.size() == 2);
torch::Tensor x = saved_variables[0];
torch::Tensor cpu_tensor = saved_variables[1];
int cpu_scalar = ctx->saved_data["cpu_scalar"].toInt();
auto expand = grad_output[0] * torch::ones_like(x);
torch::autograd::variable_list grad_inputs(1);
grad_inputs[0] = expand * cpu_tensor * cpu_scalar; // autograd engine asserts that tensors are on same device
return grad_inputs;
}
};
torch::Tensor custom_op_backed_by_autograd_fn(const torch::Tensor& x) {
return CustomOpAutogradFunction::apply(x);
}
TORCH_LIBRARY(test_cudagraphs_cpu_scalar_used_in_cpp_custom_op, m) {
m.def("custom_op_backed_by_autograd_fn", custom_op_backed_by_autograd_fn);
}
"""
module = load_inline(
name="test_cudagraphs_cpu_scalar_used_in_cpp_custom_op",
cpp_sources=cpp_source,
functions="custom_op_backed_by_autograd_fn",
verbose=True,
)
x = torch.randn(2, 2, requires_grad=True, device="cuda")
with config.patch(compiled_autograd=True), inductor_config.patch(
"triton.cudagraphs", True
):
out = torch.ops.test_cudagraphs_cpu_scalar_used_in_cpp_custom_op.custom_op_backed_by_autograd_fn(
x
)
opt_bwd = torch.compile(lambda: out.sum().backward())
opt_bwd()
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
# always safe to move, since we trace into the autograd::function bwd and can see if it's only used by aten ops
self.assertEqual(counters["inductor"]["cudagraph_skips"], 0)
def test_logs(self):
logs, ctx = logs_to_string(
torch._dynamo.compiled_autograd.__name__, "compiled_autograd"
)
with compiled_autograd._enable(compiler_fn), ctx():
torch.randn(4, 4, requires_grad=True).sum().backward()
self.assertEqual(counters["compiled_autograd"]["captures"], 1)
self.assertEqual(counters["compiled_autograd"]["compiles"], 1)
assert "torch::autograd::AccumulateGrad (NodeCall" in logs.getvalue()
assert (
"Cache miss due to new autograd node: torch::autograd::GraphRoot"
not in logs.getvalue()
)
@xfailIfS390X
def test_verbose_logs_graph(self):
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
x = torch.randn([2, 4])
result = model(x).sum()
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
yield model[2].weight.grad
yield model[2].bias.grad
logs, ctx = logs_to_string(
torch._dynamo.compiled_autograd.__name__, "compiled_autograd_verbose"
)
with ctx():
self.check_output_and_recompiles(fn)
expected_logs = [
"torch::autograd::GraphRoot (NodeCall 0)",
"ReluBackward0 (NodeCall 2)",
"AddmmBackward0 (NodeCall 3)",
"ReluBackward0 (NodeCall 5)",
"TBackward0 (NodeCall 6)",
"torch::autograd::AccumulateGrad (NodeCall 7)",
"torch::autograd::AccumulateGrad (NodeCall 9)",
"TBackward0 (NodeCall 10)",
"torch::autograd::AccumulateGrad (NodeCall 11)",
"SumBackward0 (NodeCall 1)",
"ReluBackward0 (NodeCall 2)",
"AddmmBackward0 (NodeCall 3)",
"torch::autograd::AccumulateGrad (NodeCall 11)",
"TBackward0 (NodeCall 4)",
"torch::autograd::AccumulateGrad (NodeCall 5)",
"ReluBackward0 (NodeCall 6)",
"AddmmBackward0 (NodeCall 7)",
"torch::autograd::AccumulateGrad (NodeCall 10)",
"TBackward0 (NodeCall 8)",
"torch::autograd::AccumulateGrad (NodeCall 9)",
"torch::autograd::AccumulateGrad (NodeCall 11)",
]
found = 0
for line in logs.getvalue().split("\n"):
if found == len(expected_logs):
break
if expected_logs[found] in line:
found += 1
self.assertEqual(found, len(expected_logs))
@mock.patch(
"torch._functorch.aot_autograd.AOT_COUNTER", new_callable=itertools.count
)
@mock.patch("torch._dynamo.config.inline_inbuilt_nn_modules", True)
def test_verbose_logs_aot_id(self, _):
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
x = torch.randn([2, 4])
@torch.compile
def forward(model, x):
return model(x)
result = forward(model, x).sum()
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
yield model[2].weight.grad
yield model[2].bias.grad
logs, ctx = logs_to_string(
torch._dynamo.compiled_autograd.__name__, "compiled_autograd_verbose"
)
with ctx():
self.check_output_and_recompiles(fn)
expected_logs = [
"code: CompiledFunctionBackward (NodeCall 2)",
"aot0_primals_3",
"aot0_relu",
"aot0_le",
"aot0_permute_2",
"code: CompiledFunctionBackward0 (NodeCall 2)",
"aot0_tangents_1",
"aot0_full_default",
"aot0_where",
"aot0_mm",
"aot0_permute_3",
"aot0_mm_1",
"aot0_sum_1",
"aot0_view",
"aot0_le_1",
"aot0_where_1",
"aot0_permute_6",
"aot0_mm_2",
"aot0_sum_2",
"aot0_view_1",
]
found = 0
for line in logs.getvalue().split("\n"):
if found == len(expected_logs):
break
if expected_logs[found] in line:
found += 1
self.assertEqual(found, len(expected_logs))
@mock.patch(
"torch._functorch.aot_autograd.AOT_COUNTER", new_callable=itertools.count
)
def test_verbose_logs_aot_dispatcher_nodes(self, _):
def fn():
@torch.compile
def f(x):
tmp1 = x.sin()
tmp2 = x.cos()
torch._dynamo.graph_break()
return tmp1.sin() + tmp2.cos()
x = torch.randn(4, requires_grad=True)
out = f(x)
out.sum().backward()
yield x.grad
logs, ctx = logs_to_string(
torch._dynamo.compiled_autograd.__name__, "compiled_autograd_verbose"
)
with ctx():
self.check_output_and_recompiles(fn)
expected_logs = [
"CompiledFunctionBackward1",
"aot1_tangents_1",
"aot1_sin_1",
"aot1_primals_2",
"aot1_neg",
"aot0_tangents_2",
"aot1_cos_1",
"aot1_primals_1",
"aot0_tangents_1",
"CompiledFunctionBackward0",
"aot0_neg",
"aot0_sin",
"aot0_mul",
"aot0_mul_1",
"aot0_cos",
"aot0_add",
]
self.assertEqual(
sum(1 for e in expected_logs if e in logs.getvalue()), len(expected_logs)
)
@mock.patch(
"torch._functorch.aot_autograd.AOT_COUNTER", new_callable=itertools.count
)
def test_verbose_logs_aot_dispatcher_nodes_hop(self, _):
@dataclasses.dataclass
class CustomObj:
val: torch.Tensor
def fn(x, obj):
y = x.sin()
closure_var = y + 1
y.register_hook(lambda grad: grad + obj.val + closure_var)
z = y.sin()
return z
opt_fn = torch.compile(fn)
x = torch.ones(4, requires_grad=True)
y = torch.ones(4, requires_grad=True)
obj = CustomObj(torch.tensor(88))
fn(x, obj).sum().backward()
logs, ctx = logs_to_string(
torch._dynamo.compiled_autograd.__name__, "compiled_autograd_verbose"
)
with ctx(), compiled_autograd._enable(compiler_fn):
opt_fn(y, obj).sum().backward()
self.assertEqual(x.grad, y.grad)
expected_logs = [
"CompiledFunctionBackward0",
"aot0_primals_2",
"aot0_tangents_2",
"aot0_tangents_1",
"aot0_sin",
"aot0_cos",
"aot0_mul",
"aot0_add_1",
"aot0_trace_wrapped",
"aot0_cos_1",
"aot0_mul_1",
]
self.assertEqual(
sum(1 for e in expected_logs if e in logs.getvalue()), len(expected_logs)
)
@skipIfWindows(msg="AssertionError: Scalars are not equal!")
@xfailIfS390X
def test_verbose_logs_cpp(self):
torch._logging.set_logs(compiled_autograd_verbose=True)
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
for i in [10, 11, 12]:
model.zero_grad()
x = torch.randn([i, 4])
result = model(x).sum()
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
yield model[2].weight.grad
yield model[2].bias.grad
logs, ctx = logs_to_string(
torch._dynamo.compiled_autograd.__name__, "compiled_autograd_verbose"
)
with ctx():
self.check_output_and_recompiles(fn, count=2)
patterns1 = [
r".*Cache miss due to new autograd node: torch::autograd::GraphRoot \(NodeCall 0\) with key size (\d+), "
r"previous key sizes=\[\]\n",
]
# recompile
patterns2 = [
r".*Cache miss due to changed shapes: marking size idx (\d+) of SumBackward0 \(NodeCall 1\) as dynamic\n",
r".*Cache miss due to changed shapes: marking size idx (\d+) of SumBackward0 \(NodeCall 1\) as dynamic\n",
r".*Cache miss due to changed shapes: marking size idx (\d+) of SumBackward0 \(NodeCall 1\) as dynamic\n",
r".*Cache miss due to changed shapes: marking size idx (\d+) of ReluBackward0 \(NodeCall 2\) as dynamic\n",
r".*Cache miss due to changed shapes: marking size idx (\d+) of AddmmBackward0 \(NodeCall 3\) as dynamic\n",
r".*Cache miss due to changed shapes: marking size idx (\d+) of torch::autograd::AccumulateGrad "
r"\(NodeCall 5\) as dynamic\n",
r".*Cache miss due to changed shapes: marking size idx (\d+) of ReluBackward0 \(NodeCall 6\) as dynamic\n",
]
all_logs = logs.getvalue()
pattern1 = r"".join(patterns1)
matches1 = re.findall(pattern1, all_logs)
self.assertEqual(len(matches1), 1)
assert isinstance(
matches1[0], str
) # for a single match: matches1=['match'], for multiple matches: matches1=[('match1', 'match2')]...
self.assertEqual(len(matches1), len(patterns1))
pattern2 = r"".join(patterns2)
matches2 = re.findall(pattern2, all_logs)
self.assertEqual(len(matches2), 1)
self.assertEqual(len(matches2[0]), len(patterns2))
def test_verbose_logs_snapshot(self):
def fn():
model = torch.nn.Sequential(
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
torch.nn.Linear(4, 4),
torch.nn.ReLU(),
)
x = torch.randn([2, 4])
result = model(x).sum()
result.backward()
yield model[0].weight.grad
yield model[0].bias.grad
yield model[2].weight.grad
yield model[2].bias.grad
logs, ctx = logs_to_string(
torch._dynamo.compiled_autograd.__name__, "compiled_autograd_verbose"
)
with ctx():
with compiled_autograd._enable(compiler_fn):
# unused, verbose level already snapshot with contextmanager
torch._logging.set_logs(compiled_autograd_verbose=True)
fn()
unexpected_logs = [
"Cache miss due to new autograd node: torch::autograd::GraphRoot (NodeCall 0)"
]
self.assertEqual(sum(1 for e in unexpected_logs if e in logs.getvalue()), 0)
# https://github.com/pytorch/pytorch/issues/138920
def test_compiled_autograd_does_not_specialize_on_bw_symints(self):
class Mod(torch.nn.Module):
def __init__(self, a, b, c):
super().__init__()
self.a = a
self.c = c
self.b = b
self.lin1 = torch.nn.Linear(b * a, b * c, device="cpu")
def forward(self, x):
x = x.view(-1, self.a * self.b)
y = self.lin1(x)
y = y.view(-1, self.c, self.b).contiguous()
y = torch.flatten(y, start_dim=1)
return y
class Mod2(torch.nn.Module):
def __init__(self, a, b, c):
super().__init__()
self.mod = Mod(a, b, c)
def forward(self, s, tensor_dict):
args = tensor_dict[s]
x = torch.cat(list(args))
out = self.mod(x)
return out
class Mod3(torch.nn.Module):
def __init__(self, mods):
super().__init__()
self.mods = mods
def forward(self, strs, tensor_dict, x):
outs = [x]
for i, m in enumerate(self.mods):
s = strs[i]
print("graph break")
out = m(s, tensor_dict)
outs.append(out)
return torch.cat(outs).sum(0)
def gen_tensor_dict(sizes):
tensor_dict = {
"a": [torch.randn(sizes[0], 48, device="cpu") for _ in range(4)],
"b": [torch.randn(sizes[1], 48, device="cpu") for _ in range(7)],
}
return tensor_dict
mods = [
Mod2(192, 1, 48),
Mod2(336, 1, 48),
]
m = Mod3(mods)
strs = ["a", "b"]
m = torch.compile(m)
graphs = []
def compiler_fn(gm):
def inner_compiler(gm_, example_inputs_):
graphs.append(gm_)
return gm_
return torch.compile(
gm, backend=inner_compiler, fullgraph=True, dynamic=True
)
x = torch.zeros(100, 48, device="cpu")
tensor_dict = gen_tensor_dict([101, 102])
out = m(strs, tensor_dict, x)
with torch._dynamo.compiled_autograd._enable(compiler_fn) as ctx:
out.sum().backward()
x = torch.zeros(103, 48, device="cpu")
tensor_dict = gen_tensor_dict([104, 105])
out = m(strs, tensor_dict, x)
with torch._dynamo.compiled_autograd._enable(compiler_fn) as ctx:
out.sum().backward()
# This test is a bit fragile (I failed to create a better repro).
# The important bit is that the second CA graph has not specialized the value
# of aot4_sym_size_int_ to a constant.
# This happens via suppressing any dynamic shape guards that CA generates
# when it runs make_fx.
# Suppressing these guards is strictly better than the current state,
# because we ignore all of these guards anyway in CA.
# Once we stop using make_fx in CA, we won't have to worry about this specialization.
view_nodes = graphs[1].graph.find_nodes(
op="call_function", target=torch.ops.aten.view.default
)
# First 2 view nodes have a first argument that is a SymInt, not an int burned into the graph
self.assertTrue(isinstance(view_nodes[0].args[1][0], torch.fx.Node))
self.assertTrue(isinstance(view_nodes[1].args[1][0], torch.fx.Node))
@unittest.expectedFailure
def test_saved_tensor_unpack_hook_ordering(self):
# not the correct behaviour, I'm just preventing this from changing silently
def f(x, y):
return x * y
pack_count = 0
unpack_count = 0
def pack_hook(x):
nonlocal pack_count
pack_count += 1
return x
def unpack_hook(x):
nonlocal unpack_count
unpack_count += 1
return x
def tensor_hook(_):
# in eager, tensor_hook is fired before unpack_hook
# but in compiled autograd, tensor_hook is lifted whereas unpack_hook is not
self.assertEqual(unpack_count, 0)
x = torch.ones(4, requires_grad=True)
y = torch.ones(4, requires_grad=False)
with torch.autograd.graph.saved_tensors_hooks(
pack_hook, unpack_hook
), compiled_autograd._enable(make_compiler_fn(fullgraph=False)):
out_test = f(x, y)
self.assertEqual(pack_count, 1)
self.assertEqual(unpack_count, 0)
loss = out_test.sum()
loss.register_hook(tensor_hook)
loss.backward()
self.assertEqual(pack_count, 1)
self.assertEqual(unpack_count, 1)
def test_reentrant_checkpointing(self):
def fn(x):
y = x.sin()
z = y.cos()
return (y * z).sum()
inp = torch.rand(10, 10, requires_grad=True)
out = torch.utils.checkpoint.checkpoint(fn, inp, use_reentrant=True)
with torch._dynamo.compiled_autograd._enable(torch.compile):
out.backward()
@skipIfWindows(msg="node name demangling inconsistent on windows")
def test_backward_hook_relative_ordering_partial(self):
# test backward hooks for cases that CA matches eager
def fn():
order = []
class MyModule(nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(10, 10, bias=False)
def forward(self, x):
return self.linear(x)
x = torch.randn(10, 10)
module = MyModule()
def make_pre_hook(id):
return lambda _: order.append(f"pre_hook_{id}")
def make_post_hook(id):
return lambda _1, _2: order.append(f"post_hook_{id}")
count = 0
def register_hooks_on_all_nodes(nodes):
nonlocal count
for node, _ in nodes:
if node is None:
continue
count += 1
id = f"{node.name()}_{count}"
node.register_prehook(make_pre_hook(id))
node.register_hook(make_post_hook(id))
register_hooks_on_all_nodes(node.next_functions)
loss = module(x).sum()
register_hooks_on_all_nodes(((loss.grad_fn, None),))
def make_tensor_pre_hook(id):
return lambda _: order.append(f"tensor_pre_hook_{id}")
def make_post_acc_grad_hook(id):
return lambda _: order.append(f"post_acc_grad_hook_{id}")
module.linear.weight.register_hook(make_tensor_pre_hook("weight"))
module.linear.weight.register_post_accumulate_grad_hook(
make_post_acc_grad_hook("weight")
)
loss.backward()
yield tuple(order)
self.check_output_and_recompiles(fn)
def load_test_module(name):
testdir = Path(__file__).absolute().parent.parent
with mock.patch("sys.path", [*sys.path, str(testdir)]):
return SourceFileLoader(
name, str(testdir / f"{name.replace('.', '/')}.py")
).load_module()
def make_wrapped(fn, ctxs):
@functools.wraps(fn)
def wrapped(self):
torch._dynamo.reset()
stack = contextlib.ExitStack()
for ctx in ctxs:
stack.enter_context(ctx)
out = fn(self)
stack.close()
return out
return wrapped
def wrap_test_class(orig_cls):
dct = orig_cls.__dict__.copy()
for name in list(dct.keys()):
fn = dct[name]
if not callable(fn) or name in skipped_tests:
continue
elif known_failures_re.match(name) or name in known_failing_tests:
dct[name] = unittest.expectedFailure
elif name.startswith("test_"):
fullgraph = name not in known_graph_breaks_tests
ctxs = [
compiled_autograd._enable(make_compiler_fn(fullgraph=fullgraph)),
test_contexts.get(name, contextlib.nullcontext()),
]
dct[name] = make_wrapped(fn, ctxs)
cls = type(
orig_cls.__name__ + "WithCompiledAutograd",
orig_cls.__bases__,
dct,
)
cls.__file__ = __file__
return cls
known_graph_breaks_tests = {
"test_hook_none", # uses assert in hook
"test_post_accumulate_grad_hook_e2e", # optim.Adam manually graph breaks
"test_tensor_hooks_inplace", # uses assert in hook
"test_tensor_hooks_inplace_over_view", # uses assert in hook
"test_grad_fn_prehooks", # uses assert in hook
"test_grad_fn_prehooks_multiple_outputs", # uses assert in hook
"test_grad_fn_prehooks_remove_hooks", # uses handle.remove() in hook
"test_tensor_hooks_inplace_multiple_outputs", # uses assert in hook
"test_hooks", # uses assert in hook
"test_accumulate_grad_posthooks_can_observe_tensor_prehook", # allclose
"test_saved_tensors_hook_version_counter_not_shared", # assertEqual
"test_post_accumulate_grad_hook_returns_not_None", # throws
"test_custom_function_cycle", # assertEqual
"test_mark_non_differentiable_mixed", # assertTrue
"test_materialize_grads", # assertEqual
"test_return_leaf", # assertEqual
"test_save_none_for_backward", # assertIsNone
"test_saved_variables_deprecated", # warnings.warn
"test_autograd_node_isinstance", # assertIsInstance
"test_set_materialize_non_diff_grads", # assertIsNone
"test_backward_dict_grad_for_nontensor", # torch/_custom_op/autograd.py in skip files
"test_backward_dict_invalid_keys", # torch/_custom_op/autograd.py in skip files
"test_backward_dict_requires_keys_for_input_optional_tensors", # torch/_custom_op/autograd.py in skip files
"test_backward_dict_requires_keys_for_input_tensors", # torch/_custom_op/autograd.py in skip files
"test_backward_grads_are_tensor_or_none", # torch/_custom_op/autograd.py in skip files
"test_backward_impl_on_existing_op", # torch/_custom_op/autograd.py in skip files
"test_backward_returns_dict", # torch/_custom_op/autograd.py in skip files
"test_backward_tensorlist_input_requires_list_grads", # torch/_custom_op/autograd.py in skip files
"test_backward_tensorlist_input_requires_list_grads_none_or_Tensor", # torch/_custom_op/autograd.py in skip files
"test_backward_tensorlist_input_requires_list_grads_with_same_numel", # torch/_custom_op/autograd.py in skip files
"test_save_for_backward_inputs_are_namedtuple", # torch/_custom_op/autograd.py in skip files
"test_reentrant_with_leaf_variable_hook", # reentrant .backward
"test_reentrant_with_non_leaf_variable_hook", # reentrant .backward
"test_reentrant_child_error", # reentrant .backward
"test_deep_reentrant", # reentrant .backward
"test_reentrant_priority", # reentrant .backward
"test_simple_reentrant", # reentrant .backward
}
test_contexts = {
"test_setitem_mask": config.patch(capture_dynamic_output_shape_ops=True),
"test_index_backward_does_not_save_tensor": config.patch(
capture_dynamic_output_shape_ops=True
),
}
# These groups of tests aren't supported yet
known_failures_re = re.compile(
r"^test_(sparse|profiler|gradcheck|checkpoint|named_tensor)"
)
# Bugs needing investigation:
skipped_tests = {
"test_callback_propagates_errors_from_device_thread", # fullgraph for queue_callback, but graph break for RuntimeError
}
known_failing_tests = {
# Category: Compiled autograd
"test_grad_mode_restored_reentrant", # create_graph
"test_reentrant_with_callbacks_both_depths", # queue_callback
"test_reentrant_with_callbacks_depth_0", # queue_callback
"test_reentrant_with_callbacks_depth_1", # queue_callback
"test_current_graph_task_execution_order", # nodes are already freed by the time dynamo traces the lifted hook
"test_anomaly_grad_warnings", # does not support anomaly mode
"test_autograd_inplace_views_cross_dtype", # view_fn not supported by compiled autograd
"test_current_node", # TorchDispatchMode not yet implemented for compiled autograd
"test_post_accumulate_grad_hook_ordering", # accuracy error
"test_retain_grad_cycle", # retains_grad_hooks
"test_retain_grad_inplace", # retains_grad_hooks
"test_retain_grad_inplace_over_view", # retains_grad_hooks
"test_retains_grad_can_always_observe_tensor_prehook", # retains_grad_hooks
"test_retains_grad_inplace_multiple_outputs", # retains_grad_hooks
"test_accumulate_grad", # create_graph
"test_anomaly_assign_parent_cleanup", # create_graph
"test_anomaly_mode_no_check_nan", # anomaly mode
"test_backward_create_graph_warns", # create_graph
"test_backward_with_nonleaf_inputs", # create_graph
"test_create_graph_and_full_backward_hook_cycle", # create_graph
"test_current_graph_task_id", # autograd state already cleared once dynamo is called
"test_custom_autograd_repeated_grad_grad", # create_graph
"test_custom_function_forward_mode_forward_is_no_op", # forward AD
"test_custom_function_forward_mode_inplace_checks", # forward AD
"test_custom_function_forward_mode_view_checks", # forward AD
"test_custom_function_forward_mode_wrong_formula", # forward AD
"test_default_saved_tensors_hooks_double_backward", # create_graph
"test_node_post_hook_registered_during_unpack_hook", # 'NoneType' object has no attribute 'register_hook'
"test_full_backward_hook_double_backward", # create_graph
"test_function", # create_graph
"test_grad", # create_graph
"test_grad_materialize_grads", # create_graph
"test_grad_nonleaf", # create_graph
"test_grad_nonleaf_many_outputs", # create_graph
"test_hessian_vector", # create_graph
"test_hook_edge_case_when_called_with_grad", # retains_grad_hooks
"test_inplace_on_view_backward", # create_graph
"test_multi_grad_any_hooks", # register_multi_grad_hook
"test_multi_grad_all_hooks", # retains_grad_hooks
"test_nested_anomaly_detect_nan", # create_graph
"test_nested_anomaly_printstack_cleanup", # create_graph
"test_once_differentiable", # create_graph
"test_prehook_ordering", # retains_grad_hooks
"test_retain_grad", # retains_grad_hooks
"test_saved_variable_packing_unpacking_saved_original_with_hooks", # create_graph
"test_select_sum", # create_graph, also needs graph breaks
"test_will_engine_execute_node", # retains_grad_hooks
"test_backward_to_node", # retains_grad_hooks NYI
"test_anomaly_detect_nan", # anomaly mode
"test_custom_autograd_no_early_free", # create_graph
"test_custom_function_error", # vjp
"test_custom_function_save_for_forward", # vjp
"test_dont_materialize_grads", # undefined grad
"test_no_grad_copy", # setting static member in lifted backward
"test_no_grad_copy_sparse", # setting static member in lifted backward
"test_node_ordering_when_none_returned", # torch._dynamo.exc.Unsupported: TypeError <built-in method clone
"test_save_output_nr", # output_nr grad passed as None
"test_setup_context_when_forward_has_default_args", # autograd.Function with class methods
"test_lobpcg", # create_graph
# IndexError: list index out of range (NB: x.grad = y where both x and y are input tensors)
"test_grad_nonleaf_register_hook",
"test_backward_twice_without_saved_values", # https://github.com/pytorch/pytorch/issues/129938
# Category: Dynamo
"test_accumulate_grad_tensor_reference", # Out of bounds: frame_state_entry.stride[i] is None
"test_custom_function_exception", # torch.no_grad(), torch._dynamo.exc.Unsupported: missing: WITH_EXCEPT_START
"test_to_sparse_backward", # Out of bounds: frame_state_entry.stride[i] is None
"test_autograd_simple_views_python", # gradient is None
"test_function_returns_undefined_tensor", # gradient is None
"test_naughty_autograd_function_stashing_ctx", # bytecode issue
"test_unrelated_inputs", # gradient batching rule not implemented for aten::sym_size.int
"test_custom_function_non_tensor_inputs_outputs", # gradient batching rule not implemented for aten::sym_size.int
"test_return_duplicate", # gradient batching rule not implemented for aten::sym_size.int
"test_return_duplicate_inplace", # gradient batching rule not implemented for aten::sym_size.int
"test_setitem", # CopySlices accuracy error
# Category: Inductor
"test_input_buffer_accum", # does not support sparse_grad=True: https://github.com/pytorch/pytorch/issues/120267
"test_graph_save_on_cpu", # does not support pin_memory: https://github.com/pytorch/pytorch/issues/134173
# Category: FakeTensor
"test_saving_variable_to_disk", # torch.save should no-op and be recorded in the graph
"test_wrapped_number_saved_tensors_hooks", # Proxy tensor should carryover is_wrapped_number_ of its original
"test_grad_batched_grad", # torch._subclasses.fake_tensor.UnsupportedFakeTensorException: meta converter nyi
"test_scalar_grad_mixed_device", # Fake Tensors aren't propagating device properly for 0-dim grads
# Category: Divergence from eager
"test_invalid_gradients", # can't give autograd error due to inaccurate output metadata of lifted backward
"test_autograd_node_isinstance", # backward ctx is a fake cls and not directly a Node instance
"test_backward_hook_relative_ordering", # compiled autograd collects breadth first, and module backward hook not supported
# Uncategorized
}
if not HAS_CUDA:
# Found Tesla M60 which is too old to be supported by the triton GPU compiler
known_failing_tests.add("test_type_conversions")
test_autograd = load_test_module("test_autograd")
test_custom_ops = load_test_module("test_custom_ops")
TestAutogradWithCompiledAutograd = wrap_test_class(test_autograd.TestAutograd)
TestCustomOpWithCompiledAutograd = wrap_test_class(test_custom_ops.TestCustomOp)
if __name__ == "__main__":
if HAS_CPU:
run_tests(needs="filelock")
|