1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384
|
#include <torch/csrc/jit/codegen/cuda/parser.h>
#include <torch/csrc/jit/codegen/cuda/arith.h>
#include <torch/csrc/jit/codegen/cuda/instrumentation.h>
#include <torch/csrc/jit/codegen/cuda/ir_all_nodes.h>
#include <torch/csrc/jit/codegen/cuda/ir_builder.h>
#include <torch/csrc/jit/codegen/cuda/ir_iostream.h>
#include <torch/csrc/jit/codegen/cuda/ops/all_ops.h>
#include <torch/csrc/jit/codegen/cuda/type_inference.h>
#include <torch/csrc/jit/codegen/cuda/type_promotion.h>
#include <torch/csrc/jit/codegen/cuda/utils.h>
#include <torch/csrc/jit/frontend/function_schema_parser.h>
#include <torch/csrc/jit/ir/constants.h>
#include <ATen/native/Activation.h>
#include <c10/util/CallOnce.h>
#include <unordered_map>
#include <utility>
namespace torch {
namespace jit {
typedef Value JitValue;
typedef Node JitOp;
namespace fuser {
namespace cuda {
constexpr auto kNumUnaryOps = 10;
constexpr auto kNumUnaryFloatOps = 23;
constexpr auto kNumUnaryIsOps = 6;
constexpr auto kNumBinaryFloatOps = 3;
constexpr auto kNumBinaryComparisonOps = 12;
constexpr auto kNumBinaryCastOps = 19;
constexpr auto kNumBinaryOpsWithAlpha = 6;
constexpr auto kNumLerpOps = 2;
constexpr auto kNumLayernormFwd = 2;
constexpr auto kNumBatchnormFwd = 3;
constexpr auto kNumBatchnormBwd = 2;
constexpr auto kNumInstancenormFwd = 1;
constexpr auto kNumSumToSize = 2;
constexpr auto kNumAutocastOps = 2;
constexpr auto kNumAliasDimOps = 2;
constexpr auto kNumViewOps = 2;
constexpr auto kNumVarOps = 2;
constexpr auto kNumSoftmaxFwd = 2;
constexpr auto kNumSoftmaxBwd = 2;
constexpr auto kNumAminAmaxOps = 2;
namespace {
#define REGISTER_PARSE_RULE(op, func_body, ...) \
registerParseRule( \
op, \
[](const Node* node, std::unordered_map<size_t, ValueHolder>& value_map) \
-> void func_body, \
__VA_ARGS__)
const auto& reductionSizeAttr = Symbol::attr("profiled_reduction_size");
const auto& viewSizeAttr = Symbol::attr("profiled_view_size");
const auto& intListAttr = Symbol::attr("profiled_int_list");
const auto& intAttr = Symbol::attr("profiled_int");
const auto& boolListAttr = Symbol::attr("profiled_bool_list");
const auto& boolAttr = Symbol::attr("profiled_bool");
const auto& strAttr = Symbol::attr("profiled_str");
const auto& ivalAttr = Symbol::attr("profiled_ival");
const auto& profileFailedAttr = Symbol::attr("profile_failed");
typedef Val* CgValue;
typedef Expr* CgOp;
Val* castTensoToDtype(CgValue self, JitValue* cast_val) {
auto cast_ival = toIValue(cast_val);
// we need static type for cast
TORCH_INTERNAL_ASSERT(cast_ival.has_value());
if (cast_ival->isInt()) {
auto dtype = cast_ival->toScalarType();
// We want to keep our internal fusion math in FP32
// Shape Inference will continue to propagate the right
// type to outputs unchanged.
if (dtype == at::ScalarType::Half || dtype == at::ScalarType::BFloat16) {
dtype = at::ScalarType::Float;
}
return castOp(aten_to_data_type(dtype), self);
} else {
TORCH_INTERNAL_ASSERT(
cast_ival->isNone(),
"unrecognized dtype option, expect 'int' but got: ",
cast_ival->tagKind());
// return a copy if dtype is `None`
return set(self);
}
}
bool isReductionNonCompatibleTensor(
const std::shared_ptr<c10::TensorType>& tensor_type) {
return is_zero_dim_tensor(tensor_type) || is_zero_sized_tensor(tensor_type);
}
bool isInputNonSizeZeroTensor(const Node* node) {
for (const auto& val : node->inputs()) {
auto tensor_type = val->type()->cast<TensorType>();
if (tensor_type && is_zero_sized_tensor(tensor_type)) {
return false;
}
}
return true;
}
bool isScalarTypeCompatible(const Node* node, size_t offset) {
auto val = node->input(offset);
// return true if it's not specified
if (val->type()->isSubtypeOf(static_cast<c10::TypePtr>(NoneType::get()))) {
return true;
}
// return false if it's runtime value
if (val->node()->kind() != prim::Constant) {
return false;
}
auto dtype = toIValue(val)->toScalarType();
// we do NOT support half math type yet
if (dtype == at::ScalarType::Half || dtype == at::ScalarType::BFloat16) {
return false;
}
return true;
}
// Note [ Permutation Bookkeeping and Propagation in Parser ]
//
// The goal in supporting permutation propagation in parser is to:
// 1. resolves conflicts and propagate permutation;
// 2. bookkeeping of permutation on existing tensors;
//
// The requirement right now is that all parsing rules should support
// non-permuted inputs, some binary operations support inputs with arbitrary
// permutation, a few operations support special inputs.
// In case where "wrong" inputs are fed to an operation, we should transpose
// it to proper supported permutation. This allows us to progressively expand
// permutation support.
// Currently we bind all permuted codegen Val in `ValueHolder`. This saves
// unnecessary transpose (not sure if it actually helps) since we can reuse
// permuted tensors.
//
// Parsing rule pattern:
// a. ops that only support non-permuted inputs (e.g. sum)
//
// // Specifying `MemoryFormat::Contiguous` here to force all inputs to be in
// // `Contiguous`
// auto [format, self] = getConsistentValues(
// MemoryFormat::Contiguous,
// value_map[node->inputs()[0]->unique()]);
// // ... use self
//
// b. format agnostic ops (e.g. PW unary/binary op like aten::add)
//
// // getConsistentValues -> return target format and copies of operands in
// // the same format
// auto [format, lhs, rhs] = getConsistentValues(
// c10::nullopt,
// value_map[node->inputs()[0]->unique()],
// value_map[node->inputs()[1]->unique()]);
//
// // compute out
// auto out = binaryOp(op_mapping[node->kind()], lhs, rhs);
// // specify `format` for out when adding it to `value_map_`
// value_map.emplace(node->output()->unique(), ValueHolder(out, format));
//
// c. ops that supports special permutation. e.g. aten::batch_norm with
// channels-last inputs.
struct MemoryFormat {
// indices of dimensions with increasing stride.
std::vector<int> permuted_order_;
// permutation_ encodes `permuted_order_` by concatenating all elements, with
// the exception for unpermuted tensor, where we special case permutation_ to
// be 0.
//
// e.g. for an channels-last tensor, permutation_ would be (n-1)123...(n-2);
// Note: we are omitting the leading '0' when applicable, and apparently this
// encoding only works with rank < 10
// see [ Note: MemoryFormat and Stride Order ]
size_t permutation_ = 0;
// default to non-permuted tensor
MemoryFormat() = default;
// [ Note: MemoryFormat and Stride Order ]
// stride_order is extracted from
// `TensorType::stride_properties()::stride_index_`, it describes the
// index of axes from fastest to slowest.
// or a 4d tensor, if we have stride_order = {x0, x1, x2, x3}, The i-th
// fastest dimension would be stride_order[i].
//
// Look at comment for c10::Stride in aten/src/ATen/core/jit_type.h
//
// eg0. for rank 4 non-permuted tensor, stride_order would be {3, 2, 1, 0}, it
// means the fastest dimension is axis-3. the next one would be 2, e.t.c.. So
// it's a non-permuted tensor.
// it should be encoded as permutation_ = 3210 (we special case it to 0)
//
// eg1. for rank 4 channels-last tensor, stride_order would be {1, 3, 2, 0},
// it means the fastest dimension is axis-1. the next one would be 3, and then
// 2, and then 0. So this is a channels last tensor (NCHW).
// it will be encoded as permutation_ = 1320
//
// eg2. for a rank 4 permuted tensor, stride_order can be {0, 3, 2, 1}
// it will be encoded as permutation_ = 321 (omitting leading '0')
void setPermutation(const std::vector<int>& stride_order) {
int rank = stride_order.size();
TORCH_INTERNAL_ASSERT(
rank <= 10, "MemoryFormat for permutation only supports rank <= 10");
// storing stride_order in `permuted_order` for a simpler life, so we don't
// have to decode `permutation_` when we want to apply/restore permutation_.
permuted_order_ = stride_order;
bool has_permutation = false;
permutation_ = 0;
for (const auto i : c10::irange(rank)) {
permutation_ = permutation_ * 10 + stride_order[i];
if (!has_permutation && stride_order[i] != rank - 1 - i) {
has_permutation = true;
}
}
// special case permutation_ to reflect non-permuted tensor
if (!has_permutation) {
permutation_ = 0;
}
}
// returns the stride order for given MemoryFormat encoding permutation_
//
// see details for encoding in [ Note: MemoryFormat and Stride Order ]
std::vector<int> toStrideOrder() const {
std::vector<int> stride_order;
// return empty vector for no permutation
if (hasPermutation()) {
// be generous with reserved space
stride_order.reserve(10);
bool encountered_zero = false;
size_t permutation = permutation_;
while (permutation != 0) {
int order = static_cast<int>(permutation % 10);
permutation /= 10;
if (order == 0) {
encountered_zero = true;
}
stride_order.push_back(order);
}
if (!encountered_zero) {
// in case leading '0' is omitted, push it back
stride_order.push_back(0);
}
// since we use push_back, our stride_order is reversed.
std::reverse(stride_order.begin(), stride_order.end());
}
return stride_order;
}
// returns c10::nullopt when it's not safe to broadcast current permutation to
// rank
c10::optional<MemoryFormat> broadcastToRank(size_t rank) const {
auto ret = Contiguous();
if (hasPermutation()) {
auto stride_order = toStrideOrder();
auto cur_rank = stride_order.size();
// no op for (cur_rank == 0) || (cur_rank == rank)
if (cur_rank < rank) {
// broadcasting to hight rank can be done by:
// 1. incrementing all existing stride order by rank_diff;
// 2. push back decrementing elements starting with rank_diff;
// where rank_diff = rank - cur_rank
//
// see [ Note: MemoryFormat and Stride Order]
// e.g.
// taking broadcasted bias for channels last as an example
// stride_order = {0, 2, 1} broadcasted to rank == 4 would give us
// rank_diff = 4 - 3 = 1
// take step 1 -> {1, 3, 2}
// take step 2 -> {1, 3, 2, 0}
int rank_diff = static_cast<int>(rank - cur_rank);
for (auto& val : stride_order) {
val += rank_diff;
}
for (int i = rank_diff - 1; i >= 0; i--) {
stride_order.push_back(i);
}
} else if (cur_rank > rank) {
// shrink permutation to lower rank. We can simply discard higher rank
// stride order when they are not permuted to lower rank bit, because in
// those instance we can't obey broadcasting semantics while preserving
// permutation. We check for stride order and ensure that the lower
// `rank` bits are all permuted within the lower rank. Afterwards, we
// update stride_order by decrement each entry by rank_diff to reflect
// correct stride order.
//
// see [ Note: MemoryFormat and Stride Order]
// e.g. for rank 4 channels last {1, 3, 2, 0}:
// 1. format can safely shrink to rank 3, since any@{1, 3, 2} >=
// (4-3); We ditch last (4-3) rank and decrement each element by (4-1)
// that gives us {0, 2, 1};
// 2. but when we shrink it to rank 2, we have {1, 3} where 1 < (4-2)
// and it can't be handled, we return c10::nullopt.
int collapsed_ranks = static_cast<int>(cur_rank - rank);
for (size_t i = 0; i < rank; i++) {
if (stride_order[i] < collapsed_ranks) {
// illegal collapsing, return c10::nullopt
return c10::nullopt;
}
// update collapsed stride_order
stride_order[i] -= collapsed_ranks;
}
// discard higher rank stride order.
stride_order.resize(rank);
}
ret.setPermutation(stride_order);
}
return ret;
}
// returns non-permuted format
static MemoryFormat Contiguous() {
return MemoryFormat();
}
bool hasPermutation() const {
return permutation_ != 0;
}
bool isChannelsLast() const {
int rank = permuted_order_.size();
if (rank > 2 && permuted_order_[0] == 1 && permuted_order_[rank - 1] == 0) {
for (const auto i : c10::irange(rank - 2)) {
if (permuted_order_[i + 1] != rank - 1 - i) {
return false;
}
}
return true;
}
return false;
}
// returns transpose map to achieve permutation on non-permuted tensor
// note: used for aten::permute API and codegen tranpose API
std::vector<int64_t> apply() const {
std::vector<int64_t> ret;
if (hasPermutation()) {
ret.resize(permuted_order_.size());
std::copy(permuted_order_.rbegin(), permuted_order_.rend(), ret.begin());
}
return ret;
}
// returns transpose map to restore back to non-permuted tensor
// note: used for aten::permute API and codegen transpose API
std::vector<int64_t> restore() const {
std::vector<int64_t> ret;
if (hasPermutation()) {
int rank = permuted_order_.size();
ret.resize(rank);
for (const auto i : c10::irange(rank)) {
ret[permuted_order_[i]] = rank - 1 - i;
}
}
return ret;
}
};
struct MemoryCompare {
bool operator()(const MemoryFormat& format0, const MemoryFormat& format1)
const {
return format0.permutation_ < format1.permutation_;
}
};
typedef std::map<MemoryFormat, CgValue, MemoryCompare> MemoryFormatMap;
MemoryFormat operator+(const MemoryFormat& a, const MemoryFormat& b) {
// Note: TensorIterator logic uses first input to dominate output MemoryFormat
// so instead of `a.permutation_ >= b.permutation_ ? a : b;`, we use:
return a;
};
//! ValueHolder is holds multiple copies in different permutation `MemoryFormat`
//! of a tensor view. This mainly serves two purposes:
//!
//! 1. reuse permuted tensor views among consumers
//! 2. bookkeeping for permuted tensor views in input/output tensors
//!
//! refer to Note [ Permutation Bookkeeping and Propagation in Parser ]
class ValueHolder {
public:
// checks if given Val in target format exists.
bool hasValue(const MemoryFormat& format) const {
return vals_.count(format) != 0;
}
// returns Val in target format.
CgValue value(const MemoryFormat& format) const {
auto iter_val = vals_.find(format);
TORCH_INTERNAL_ASSERT(
iter_val != vals_.end(), "accessing non existing c_last_value()");
return iter_val->second;
}
// returns Val in target format if it exists, otherwise, transpose an existing
// copy and add that to bookkeeping.
CgValue maybeConvertValue(const MemoryFormat& format) {
auto cur_rank = rank();
// scalar (tensor) where cur_rank == 0, memory format doesn't carry meaning
// and should just return the value as-is. same for non-tensor where
// cur_rank == -1
if (cur_rank <= 0) {
return std::get<1>(getEntry());
}
MemoryFormat format_s;
CgValue value_s = nullptr;
std::tie(format_s, value_s) = getEntry();
auto opt_format_d = format.broadcastToRank(static_cast<size_t>(cur_rank));
TORCH_INTERNAL_ASSERT(
opt_format_d.has_value(),
"maybeConvertValue requested for illegal permutation");
MemoryFormat format_d = opt_format_d.value();
auto iter_val = vals_.find(format_d);
if (iter_val != vals_.end()) {
return iter_val->second;
}
auto val = convertValue(format_d, format_s, value_s);
vals_[format_d] = val;
return val;
}
int rank() const {
if (!is_tensor_view_) {
return -1;
} else {
auto v = std::get<1>(getEntry());
TORCH_INTERNAL_ASSERT(
v->isA<TensorView>(), "can only access rank of TensorView");
return static_cast<int>(v->as<TensorView>()->nDims());
}
}
// TODO: delete this and update accessor for value_map(_)
ValueHolder() {
TORCH_INTERNAL_ASSERT(false, "can't default constructor ValueHolder");
}
ValueHolder(CgValue val, MemoryFormat format = MemoryFormat()) {
vals_[format] = val;
if (val->isA<TensorView>()) {
is_tensor_view_ = true;
}
}
// returns the MemoryFormat and codegen Val with the highest precedence among
// existing copies.
std::tuple<MemoryFormat, CgValue> getEntry() const {
TORCH_CHECK(!vals_.empty(), "ValueHolder::getEntry() on empty vals_");
// return the last entry, this allows us to prioritize permuted (e.g.
// channels-last) tensor over non-permuted tensors
return *vals_.rbegin();
}
// TODO: code cleaning in parser so we don't need these.
// returns Val*, keeping them here just so we have less code change.
CgValue operator*() const {
return std::get<1>(getEntry());
}
CgValue operator->() const {
return std::get<1>(getEntry());
}
operator CgValue() const {
return std::get<1>(getEntry());
}
private:
// helper function to convert value_s @ format_s to format_d
CgValue convertValue(
MemoryFormat format_d,
MemoryFormat format_s,
CgValue value_s) {
TORCH_INTERNAL_ASSERT(
value_s->isA<TensorView>(), "cannot convert non-TensorView");
auto tv = value_s->as<TensorView>();
// TODO: we could probably merge the two if it has perf impact on generated
// kernel
// restore source permutation
if (format_s.hasPermutation()) {
tv = permute(tv, format_s.restore());
}
// apply destination permutation
if (format_d.hasPermutation()) {
tv = permute(tv, format_d.apply());
}
return tv;
}
private:
// container to hold all copies of value in different MemoryFormat
// std::unordered_map<MemoryFormat, CgValue> vals_;
MemoryFormatMap vals_;
// identify scalar Val
bool is_tensor_view_ = false;
};
template <class Func, class... Values>
auto iterate(Func f, ValueHolder& val) {
return f(val);
}
template <class Func, class... Values>
auto iterate(Func f, ValueHolder& val, Values&... vals) {
return f(val, iterate(f, vals...));
}
// iterate through all vals and return the output MemoryFormat and copies of
// vals.
// 1. When `forced_format == c10::nullopt`, target MemoryFormat returns the
// format of the first val in `vals`, this is to achieve a coherent
// behavior as with eager TensorIterator;
// 2. The target can be overwritten vias specifying `forced_format`.
//
// Note: take `Values&` by reference, since `maybeConvertValue` needs to modify
// the entry and we want that to be updated in `value_map_`
template <class... Values>
std::pair<MemoryFormat, std::list<CgValue>> getConsistentValues(
c10::optional<MemoryFormat> forced_format,
Values&... vals) {
MemoryFormat format;
if (forced_format.has_value()) {
format = forced_format.value();
} else {
// check for identical nDim on vals
auto rank_func = [](const ValueHolder& val, int rank = 0) {
int v_rank = val.rank();
v_rank = std::max(0, v_rank);
if (rank == 0) {
return v_rank;
} else if (v_rank == 0) {
return rank;
} else if (rank == -1 || v_rank != rank) {
return -1;
}
return rank;
};
int rank = iterate(rank_func, vals...);
// TODO: this is not needed as we are only using the first val
// only apply permutation when all inputs are of identical rank, since
// permutation could have changed semantics among broadcasted tensors.
// Consider pointwise operation between two tensor [N, C, H, W] + [H, W]
if (rank > 0) {
auto format_func = [](const ValueHolder& val,
MemoryFormat f = MemoryFormat::Contiguous()) {
return std::get<0>(val.getEntry()) + f;
};
format = iterate(format_func, vals...);
} else {
format = MemoryFormat::Contiguous();
}
}
auto convert_func = [format](
ValueHolder& val, std::list<CgValue> list_val = {}) {
list_val.push_front(val.maybeConvertValue(format));
return list_val;
};
auto list_val = iterate(convert_func, vals...);
return std::make_pair(format, list_val);
}
// iterate through all vals and return the output MemoryFormat and copies of
// vals.
// 1. When `forced_format == c10::nullopt`, target MemoryFormat returns the
// format of the first val in `vals`, this is to achieve a coherent
// behavior as with eager TensorIterator;
// 2. The target can be overwritten vias specifying `forced_format`.
//
// Note: take `Values&` by reference, since `maybeConvertValue` needs to modify
// the entry and we want that to be updated in `value_map_`
template <class... Values>
std::pair<MemoryFormat, std::list<CgValue>> getPWFormatValues(
c10::optional<MemoryFormat> forced_format,
Values&... vals) {
MemoryFormat format;
if (forced_format.has_value()) {
format = forced_format.value();
} else {
// get maximum rank on vals
std::vector<MemoryFormat> formats;
std::vector<int> ranks;
auto max_rank_func = [&ranks](const ValueHolder& val, int rank = 0) {
int v_rank = val.rank();
ranks.push_back(v_rank);
return std::max(rank, v_rank);
};
int max_rank = iterate(max_rank_func, vals...);
// going through all permutation, keeping consistency with TensorIterator
// behavior and the first tensor with highest rank dictates output
// permutation
auto format_func = [&formats, &max_rank](
const ValueHolder& val,
MemoryFormat f = MemoryFormat::Contiguous()) {
auto cur_format = std::get<0>(val.getEntry());
formats.push_back(cur_format);
return val.rank() == max_rank ? cur_format : f;
};
format = iterate(format_func, vals...);
// we need to do pair-wise comparison to ensure that all permutation are
// compatible since permutation could have changed semantics among
// broadcasted tensors. Consider pointwise operation between three tensor
// [N, C, H, W] + [C, H, W] + [H, W]
for (size_t i = 0; i < formats.size() && format.hasPermutation(); i++) {
for (size_t j = 0; j < formats.size(); j++) {
// don't compare scalar tensor or scalar
if (ranks[i] <= 0 || ranks[j] <= 0 || i == j) {
continue;
}
size_t lower_rank = std::min(ranks[i], ranks[j]);
auto i_format = formats[i].broadcastToRank(lower_rank);
auto j_format = formats[j].broadcastToRank(lower_rank);
// breaks permutation if any:
// 1. i_format can't be broadcasted to lower_rank;
// 2. j_format can't be broadcasted to lower_rank;
if (!i_format.has_value() || !j_format.has_value()) {
format = MemoryFormat::Contiguous();
}
}
}
}
auto convert_func = [format](
ValueHolder& val, std::list<CgValue> list_val = {}) {
list_val.push_front(val.maybeConvertValue(format));
return list_val;
};
auto list_val = iterate(convert_func, vals...);
return std::make_pair(format, list_val);
}
typedef void (
*ParseFuncPtr)(const Node*, std::unordered_map<size_t, ValueHolder>&);
typedef bool (*MergeQueryFuncPtr)(const Node*);
// TODO: add a mutex to make it thread safe.
class IrParser {
enum class OperatorType {
ElementWise,
Reduction,
ReductionToSize,
Normalization
};
typedef OperatorType (*OperatorTypeFuncPtr)(const Node*);
class RegistrationEntry {
public:
RegistrationEntry(
ParseFuncPtr parse_f,
MergeQueryFuncPtr merge_f = nullptr,
OperatorTypeFuncPtr type_f = nullptr)
: parse_f_(parse_f), merge_f_(merge_f), type_f_(type_f) {}
void parse(
const Node* node,
std::unordered_map<size_t, ValueHolder>& values) const {
parse_f_(node, values);
}
bool isCompatible(const Node* node) const {
if (merge_f_ == nullptr) {
return true;
}
return merge_f_(node);
}
bool isType(const Node* node, OperatorType type) const {
auto n_type =
type_f_ == nullptr ? OperatorType::ElementWise : type_f_(node);
return n_type == type;
}
private:
ParseFuncPtr parse_f_;
MergeQueryFuncPtr merge_f_;
OperatorTypeFuncPtr type_f_;
};
public:
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
IrParser(std::shared_ptr<Graph> graph) : graph_(std::move(graph)) {
initRegistry();
}
std::unique_ptr<Fusion> parse() {
auto fusion = std::make_unique<Fusion>();
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
FusionGuard fg(fusion.get());
auto block = graph_->block();
std::unordered_map<Val*, MemoryFormat> permuted_tensors;
// register all inputs;
for (auto val : block->inputs()) {
TORCH_INTERNAL_ASSERT(
registerValue(val),
"Failure when register value: ",
*(val->node()),
" with type: ",
val->type()->repr_str());
MemoryFormat format;
Val* operand = nullptr;
std::tie(format, operand) = value_map_[val->unique()].getEntry();
fusion->addInput(operand);
// mark input tensor as permuted;
if (format.hasPermutation()) {
permuted_tensors.insert({operand, format});
}
auto opt_dtype = operand->getDataType();
// computation promotion, we cast fp16 or bf16 inputs to fp32 and use
// promoted type in the computation.
if (opt_dtype.has_value() &&
(opt_dtype.value() == DataType::Half ||
opt_dtype.value() == DataType::BFloat16)) {
Val* promoted_val = castOp(DataType::Float, operand);
value_map_[val->unique()] = ValueHolder(promoted_val, format);
}
}
// compose nodes in topo order;
for (const JitOp* node : block->nodes()) {
processJitNode(node);
}
// mark output;
for (auto jit_output : block->outputs()) {
MemoryFormat format;
Val* operand = nullptr;
std::tie(format, operand) = value_map_[jit_output->unique()].getEntry();
TensorView* out = operand->as<TensorView>();
// demote output dtype to be match PyTorch JIT graph.
auto tensor_type = jit_output->type()->cast<TensorType>();
TORCH_INTERNAL_ASSERT(
tensor_type, "output of fusion group is not TensorType.");
if (tensor_type->scalarType().has_value()) {
out = optionalCastStrict(
aten_to_data_type(*tensor_type->scalarType()), out)
->as<TensorView>();
}
if (out->isFusionOutput()) {
// TODO: This is wasted memory bandwidth, we need to copy since we can't
// output a tensor twice.
out = set(out);
}
fusion->addOutput(out);
// mark output tensor as permuted;
if (format.hasPermutation()) {
permuted_tensors.insert({out, format});
}
}
for (const auto& i : c10::irange(fusion->inputs().size())) {
const auto& entry = permuted_tensors.find(fusion->inputs()[i]);
if (entry != permuted_tensors.end()) {
fusion->setPermutationOnInput(i, entry->second.apply());
}
}
for (const auto& i : c10::irange(fusion->outputs().size())) {
const auto& entry = permuted_tensors.find(fusion->outputs()[i]);
if (entry != permuted_tensors.end()) {
fusion->setPermutationOnOutput(i, entry->second.restore());
}
}
return fusion;
}
static bool lookupInSymbolSet(const Node* node) {
initRegistry();
std::lock_guard<std::mutex> lock(parser_mutex_);
return parser_symbol_set_.count(node->kind()) != 0;
}
// return nullptr if entry does not exist
static const RegistrationEntry* lookupInRegistry(const Node* node) {
std::lock_guard<std::mutex> lock(parser_mutex_);
if (parser_skip_set_.count(node->kind()) != 0) {
return nullptr;
}
// we need to use maybeSchema for nodes like prim::Constant, which doesn't
// have a schema
auto schema_ptr = node->maybeSchema();
if (schema_ptr != nullptr) {
// search cached entry first
auto cache_it = cached_registry_lookup_.find(schema_ptr);
if (cache_it != cached_registry_lookup_.end()) {
return cache_it->second;
} else {
// match signature
auto schema_str = canonicalSchemaString(*schema_ptr);
auto iter = jit_operator_registry_.find(schema_str);
if (iter != jit_operator_registry_.end()) {
// update cache entry
cached_registry_lookup_.insert(cache_it, {schema_ptr, &iter->second});
return &iter->second;
}
}
}
return nullptr;
}
static bool querySkipSymbolSet(c10::Symbol symbol, bool flip) {
initRegistry();
std::lock_guard<std::mutex> lock(parser_mutex_);
// no need to init registry here (unlike `lookupInSymbolSet`, as
// `parser_skip_set_` is not initialized via initialization
bool ret = parser_skip_set_.count(symbol) != 0;
if (flip) {
if (ret) {
parser_skip_set_.erase(symbol);
} else {
parser_skip_set_.insert(symbol);
}
}
return ret;
}
static void initRegistry() {
c10::call_once(once_flag_, []() {
std::lock_guard<std::mutex> lock(parser_mutex_);
registerJitOperator();
});
}
static bool canParseNode(const Node* node) {
initRegistry();
// match signature.
auto schema_ptr = node->maybeSchema();
if (schema_ptr == nullptr) {
return false;
}
auto reg_entry = lookupInRegistry(node);
return reg_entry != nullptr && reg_entry->isCompatible(node);
}
static bool isReductionToSizeNode(const Node* node) {
initRegistry();
auto reg_entry = lookupInRegistry(node);
return reg_entry != nullptr &&
reg_entry->isType(node, OperatorType::ReductionToSize);
}
static bool isReductionNode(const Node* node) {
initRegistry();
auto reg_entry = lookupInRegistry(node);
return reg_entry != nullptr &&
(reg_entry->isType(node, OperatorType::Reduction) ||
reg_entry->isType(node, OperatorType::ReductionToSize));
}
static bool isNormalizationNode(const Node* node) {
initRegistry();
auto reg_entry = lookupInRegistry(node);
return reg_entry != nullptr &&
reg_entry->isType(node, OperatorType::Normalization);
}
static bool isElementWiseNode(const Node* node) {
initRegistry();
auto reg_entry = lookupInRegistry(node);
return reg_entry != nullptr &&
reg_entry->isType(node, OperatorType::ElementWise);
}
// TODO: is_reduction is too hacky here. we should categorize operation types
// based on their memory accessing pattern, which would affect fusion
// strategy and partition logic.
static void registerParseRule(
std::shared_ptr<Operator>& op,
ParseFuncPtr parse_fn,
MergeQueryFuncPtr merge_query_fn = nullptr,
OperatorTypeFuncPtr type_fn = nullptr) {
auto op_name = op->schema().name();
parser_symbol_set_.insert(c10::Symbol::fromQualString(op_name));
// We blindly attempt to profile the inplace version of supported op, this
// is to ensure that in-place removal in fusion partition would have the
// profile information for them readily available after the pass.
parser_symbol_set_.insert(c10::Symbol::fromQualString(op_name + '_'));
jit_operator_registry_.emplace(
std::piecewise_construct,
std::forward_as_tuple(canonicalSchemaString(op->schema())),
std::forward_as_tuple(parse_fn, merge_query_fn, type_fn));
}
private:
static void registerJitOperator() {
// Register parse-function for each JIT operator;
// This is a one-time look up, our hash registry indexes on the pointer in
// OperatorRegistry.
std::array<const char*, kNumBinaryOpsWithAlpha> BinaryOpWithAlpha = {
"aten::add(Tensor self, Tensor other, *, Scalar alpha) -> Tensor",
"aten::add(Tensor self, Scalar other, Scalar alpha) -> Tensor",
"aten::sub(Tensor self, Tensor other, *, Scalar alpha) -> Tensor",
"aten::sub(Tensor self, Scalar other, Scalar alpha) -> Tensor",
"aten::rsub(Tensor self, Tensor other, *, Scalar alpha) -> Tensor",
"aten::rsub(Tensor self, Scalar other, Scalar alpha) -> Tensor"};
for (auto signature : BinaryOpWithAlpha) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
using BinaryOpWithAlphaType = Val* (*)(Val*, Val*, Val*);
static std::unordered_map<
Symbol,
std::pair<BinaryOpType, BinaryOpWithAlphaType>>
op_mapping(
{{aten::add,
std::make_pair(
BinaryOpType::Add,
static_cast<BinaryOpWithAlphaType>(&add_alpha))},
{aten::sub,
std::make_pair(
BinaryOpType::Sub,
static_cast<BinaryOpWithAlphaType>(&sub_alpha))},
{aten::rsub,
std::make_pair(
BinaryOpType::Sub,
static_cast<BinaryOpWithAlphaType>(&sub_alpha))}});
// TODO: handle scaling factor when it's not constant 1;
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto lhs = list_val.front();
list_val.pop_front();
auto rhs = list_val.front();
list_val.pop_front();
Val* alpha = value_map[node->inputs()[2]->unique()];
auto out = alpha->isOneInt()
? binaryOp(
op_mapping[node->kind()].first,
node->kind() == aten::rsub ? rhs : lhs,
node->kind() == aten::rsub ? lhs : rhs,
TypePromotion::default_op_config)
: (node->kind() == aten::rsub
? op_mapping[node->kind()].second(rhs, lhs, alpha)
: op_mapping[node->kind()].second(lhs, rhs, alpha));
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
std::array<const char*, kNumBinaryFloatOps> BinaryFloatOp = {
"aten::div(Tensor self, Tensor other) -> Tensor",
"aten::div(Tensor self, Scalar other) -> Tensor",
"aten::atan2(Tensor self, Tensor other) -> Tensor"};
for (auto signature : BinaryFloatOp) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
static std::unordered_map<Symbol, BinaryOpType> op_mapping(
{{aten::div, BinaryOpType::Div},
{aten::atan2, BinaryOpType::Atan2}});
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto lhs = list_val.front();
list_val.pop_front();
auto rhs = list_val.front();
list_val.pop_front();
auto out = binaryOp(
op_mapping[node->kind()],
lhs,
rhs,
TypePromotion::float_op_config);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
std::array<const char*, kNumBinaryCastOps> BinaryCastOp = {
"aten::mul(Tensor self, Tensor other) -> Tensor",
"aten::mul(Tensor self, Scalar other) -> Tensor",
"aten::max(Tensor self, Tensor other) -> Tensor",
"aten::min(Tensor self, Tensor other) -> Tensor",
"aten::pow(Tensor self, Tensor exponent) -> Tensor",
"aten::pow(Tensor self, Scalar exponent) -> Tensor",
"aten::pow(Scalar self, Tensor exponent) -> Tensor",
"aten::remainder(Tensor self, Tensor other) -> Tensor",
"aten::fmod(Tensor self, Tensor other) -> Tensor",
"aten::bitwise_and(Tensor self, Tensor other) -> Tensor",
"aten::__and__(Tensor self, Tensor other) -> Tensor",
"aten::bitwise_or(Tensor self, Tensor other) -> Tensor",
"aten::__or__(Tensor self, Tensor other) -> Tensor",
"aten::bitwise_xor(Tensor self, Tensor other) -> Tensor",
"aten::__xor__(Tensor self, Tensor other) -> Tensor",
"aten::bitwise_left_shift(Tensor self, Tensor other) -> Tensor",
"aten::__lshift__(Tensor self, Tensor other) -> Tensor",
"aten::bitwise_right_shift(Tensor self, Tensor other) -> Tensor",
"aten::__rshift__(Tensor self, Tensor other) -> Tensor"};
for (auto signature : BinaryCastOp) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
static std::unordered_map<Symbol, BinaryOpType> op_mapping(
{{aten::mul, BinaryOpType::Mul},
{aten::min, BinaryOpType::Min},
{aten::max, BinaryOpType::Max},
{aten::pow, BinaryOpType::Pow},
{aten::remainder, BinaryOpType::Remainder},
{aten::fmod, BinaryOpType::Fmod},
{aten::bitwise_and, BinaryOpType::And},
{aten::__and__, BinaryOpType::And},
{aten::bitwise_or, BinaryOpType::Or},
{aten::__or__, BinaryOpType::Or},
{aten::bitwise_xor, BinaryOpType::Xor},
{aten::__xor__, BinaryOpType::Xor},
{aten::bitwise_left_shift, BinaryOpType::Lshift},
{aten::__lshift__, BinaryOpType::Lshift},
{aten::bitwise_right_shift, BinaryOpType::Rshift},
{aten::__rshift__, BinaryOpType::Rshift}});
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto lhs = list_val.front();
list_val.pop_front();
auto rhs = list_val.front();
list_val.pop_front();
auto out = binaryOp(
op_mapping[node->kind()],
lhs,
rhs,
TypePromotion::default_op_config);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
std::array<const char*, kNumBinaryComparisonOps> BinaryOp = {
"aten::eq(Tensor self, Tensor other) -> Tensor",
"aten::eq(Tensor self, Scalar other) -> Tensor",
"aten::ne(Tensor self, Tensor other) -> Tensor",
"aten::ne(Tensor self, Scalar other) -> Tensor",
"aten::ge(Tensor self, Tensor other) -> Tensor",
"aten::ge(Tensor self, Scalar other) -> Tensor",
"aten::gt(Tensor self, Tensor other) -> Tensor",
"aten::gt(Tensor self, Scalar other) -> Tensor",
"aten::le(Tensor self, Tensor other) -> Tensor",
"aten::le(Tensor self, Scalar other) -> Tensor",
"aten::lt(Tensor self, Tensor other) -> Tensor",
"aten::lt(Tensor self, Scalar other) -> Tensor"};
for (auto signature : BinaryOp) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
static std::unordered_map<Symbol, BinaryOpType> op_mapping(
{{aten::lt, BinaryOpType::LT},
{aten::le, BinaryOpType::LE},
{aten::gt, BinaryOpType::GT},
{aten::ge, BinaryOpType::GE},
{aten::ne, BinaryOpType::NE},
{aten::eq, BinaryOpType::Eq}});
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto lhs = list_val.front();
list_val.pop_front();
auto rhs = list_val.front();
list_val.pop_front();
auto out = binaryOp(
op_mapping[node->kind()],
lhs,
rhs,
TypePromotion::comparison_op_config);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
std::array<const char*, kNumUnaryOps> UnaryOp = {
"aten::abs(Tensor self) -> Tensor",
"aten::bitwise_not(Tensor self) -> Tensor",
"aten::ceil(Tensor self) -> Tensor",
"aten::floor(Tensor self) -> Tensor",
"aten::frac(Tensor self) -> Tensor",
"aten::neg(Tensor self) -> Tensor",
"aten::relu(Tensor self) -> Tensor",
"aten::round(Tensor self) -> Tensor",
"aten::silu(Tensor self) -> Tensor",
"aten::trunc(Tensor self) -> Tensor",
};
for (auto signature : UnaryOp) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
static std::unordered_map<Symbol, UnaryOpType> op_mapping({
{aten::abs, UnaryOpType::Abs},
{aten::bitwise_not, UnaryOpType::Not},
{aten::ceil, UnaryOpType::Ceil},
{aten::floor, UnaryOpType::Floor},
{aten::frac, UnaryOpType::Frac},
{aten::neg, UnaryOpType::Neg},
{aten::relu, UnaryOpType::Relu},
{aten::round, UnaryOpType::Round},
{aten::silu, UnaryOpType::Silu},
{aten::trunc, UnaryOpType::Trunc},
});
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto operand = list_val.front();
list_val.pop_front();
auto out = unaryOp(op_mapping[node->kind()], operand);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
std::array<const char*, kNumUnaryFloatOps> UnaryFloatOp = {
"aten::log(Tensor self) -> Tensor",
"aten::log10(Tensor self) -> Tensor",
"aten::log1p(Tensor self) -> Tensor",
"aten::log2(Tensor self) -> Tensor",
"aten::lgamma(Tensor self) -> Tensor",
"aten::exp(Tensor self) -> Tensor",
"aten::expm1(Tensor self) -> Tensor",
"aten::erf(Tensor self) -> Tensor",
"aten::erfc(Tensor self) -> Tensor",
"aten::cos(Tensor self) -> Tensor",
"aten::acos(Tensor self) -> Tensor",
"aten::cosh(Tensor self) -> Tensor",
"aten::sin(Tensor self) -> Tensor",
"aten::asin(Tensor self) -> Tensor",
"aten::sinh(Tensor self) -> Tensor",
"aten::tan(Tensor self) -> Tensor",
"aten::atan(Tensor self) -> Tensor",
"aten::tanh(Tensor self) -> Tensor",
"aten::atanh(Tensor self) -> Tensor",
"aten::sqrt(Tensor self) -> Tensor",
"aten::rsqrt(Tensor self) -> Tensor",
"aten::reciprocal(Tensor self) -> Tensor",
"aten::sigmoid(Tensor self) -> Tensor"};
for (auto signature : UnaryFloatOp) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
static std::unordered_map<Symbol, UnaryOpType> op_mapping({
{aten::log, UnaryOpType::Log},
{aten::log10, UnaryOpType::Log10},
{aten::log1p, UnaryOpType::Log1p},
{aten::log2, UnaryOpType::Log2},
{aten::lgamma, UnaryOpType::Lgamma},
{aten::exp, UnaryOpType::Exp},
{aten::expm1, UnaryOpType::Expm1},
{aten::erf, UnaryOpType::Erf},
{aten::erfc, UnaryOpType::Erfc},
{aten::cos, UnaryOpType::Cos},
{aten::acos, UnaryOpType::Acos},
{aten::cosh, UnaryOpType::Cosh},
{aten::sin, UnaryOpType::Sin},
{aten::asin, UnaryOpType::Asin},
{aten::sinh, UnaryOpType::Sinh},
{aten::tan, UnaryOpType::Tan},
{aten::tanh, UnaryOpType::Tanh},
{aten::atan, UnaryOpType::Atan},
{aten::atanh, UnaryOpType::Atanh},
{aten::sqrt, UnaryOpType::Sqrt},
{aten::rsqrt, UnaryOpType::Rsqrt},
{aten::reciprocal, UnaryOpType::Reciprocal},
{aten::sigmoid, UnaryOpType::Sigmoid},
});
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto operand = list_val.front();
list_val.pop_front();
auto out = unaryOp(
op_mapping[node->kind()],
operand,
TypePromotion::float_op_config);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
std::array<const char*, kNumUnaryIsOps> UnaryIsOp = {
"aten::isfinite(Tensor self) -> Tensor",
"aten::isinf(Tensor self) -> Tensor",
"aten::isnan(Tensor self) -> Tensor",
"aten::isneginf(Tensor self) -> Tensor",
"aten::isposinf(Tensor self) -> Tensor",
"aten::isreal(Tensor self) -> Tensor"};
for (auto signature : UnaryIsOp) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
static std::unordered_map<Symbol, UnaryOpType> op_mapping({
{aten::isfinite, UnaryOpType::IsFinite},
{aten::isinf, UnaryOpType::IsInf},
{aten::isnan, UnaryOpType::IsNan},
{aten::isneginf, UnaryOpType::IsNegInf},
{aten::isposinf, UnaryOpType::IsPosInf},
{aten::isreal, UnaryOpType::IsReal},
});
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto operand = list_val.front();
list_val.pop_front();
auto out = unaryIsOp(op_mapping[node->kind()], operand);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::rand_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto operand = list_val.front();
list_val.pop_front();
if (!node->input(3)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
auto device = constant_as<c10::Device>(node->input(3));
TORCH_INTERNAL_ASSERT(
device.has_value() && device->is_cuda(),
"rand_like in nvfuser is not on cuda device");
auto input_tensor_type =
node->input(0)->type()->cast<TensorType>();
// device->index() == -1 indicating that we don't change device
// index
if (device->index() != -1 && input_tensor_type) {
auto input_device = input_tensor_type->device();
// we expect device index to be consistent with input and it
// should have already been handled by partition
TORCH_INTERNAL_ASSERT(
!input_device.has_value() ||
input_device->index() == device->index(),
"rand_like in nvfuser is not on cuda device");
}
}
auto out = randlike(operand);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
if (!node->input(1)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get())) ||
!node->input(2)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get())) ||
!node->input(5)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
return false;
}
return true;
},
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::softplus(Tensor self, Scalar beta, Scalar threshold) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto operand = list_val.front()->as<TensorView>();
list_val.pop_front();
auto& beta = value_map[node->inputs()[1]->unique()];
auto& threshold = value_map[node->inputs()[2]->unique()];
auto out = softplus(operand, beta, threshold);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::threshold(Tensor self, Scalar threshold, Scalar value) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto operand = list_val.front();
list_val.pop_front();
auto& th = value_map[node->inputs()[1]->unique()];
auto& value = value_map[node->inputs()[2]->unique()];
auto out = threshold(operand, th, value);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{ // LTC uses threshold_backward for relu_backward
auto ptr_op = getOperatorForLiteral(
"aten::threshold_backward(Tensor grad_output, Tensor self, Scalar threshold) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto grad_output = list_val.front();
list_val.pop_front();
auto input = list_val.front();
auto& threshold = value_map[node->inputs()[2]->unique()];
auto comparison = binaryOp(
BinaryOpType::GT,
input,
threshold,
TypePromotion::comparison_op_config);
auto mask = castOp(input->getDataType().value(), comparison);
auto out = mul(grad_output, mask);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::clamp(Tensor self, Scalar? min, Scalar? max) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto operand = list_val.front();
list_val.pop_front();
Val* min = value_map.count(node->inputs()[1]->unique()) != 0
? *value_map[node->inputs()[1]->unique()]
: nullptr;
Val* max = value_map.count(node->inputs()[2]->unique()) != 0
? *value_map[node->inputs()[2]->unique()]
: nullptr;
Val* out = clamp(operand, min, max);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::where(Tensor condition, Tensor self, Tensor other) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()],
value_map[node->inputs()[2]->unique()]);
auto condition = list_val.front();
list_val.pop_front();
auto x = list_val.front();
list_val.pop_front();
auto y = list_val.front();
list_val.pop_front();
auto out = where(condition, x, y);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{
std::array<const char*, kNumLerpOps> LerpOp = {
"aten::lerp(Tensor self, Tensor end, Scalar weight) -> Tensor",
"aten::lerp(Tensor self, Tensor end, Tensor weight) -> Tensor"};
for (auto signature : LerpOp) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()],
value_map[node->inputs()[2]->unique()]);
auto self = list_val.front();
list_val.pop_front();
auto end = list_val.front();
list_val.pop_front();
auto weight = list_val.front();
list_val.pop_front();
auto out = lerp(self, end, weight);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
}
{
auto ptr_op = getOperatorForLiteral(
"aten::addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()],
value_map[node->inputs()[2]->unique()],
value_map[node->inputs()[3]->unique()]);
auto self = list_val.front();
list_val.pop_front();
auto tensor1 = list_val.front();
list_val.pop_front();
auto tensor2 = list_val.front();
list_val.pop_front();
auto value = list_val.front();
list_val.pop_front();
auto out = addcmul(self, tensor1, tensor2, value);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto input = list_val.front();
list_val.pop_front();
auto prob = list_val.front();
list_val.pop_front();
auto train = constant_as<bool>(node->input(2));
TORCH_INTERNAL_ASSERT(
train.has_value(), "dropout needs constant `train` flag");
if (train.value()) {
auto result = dropout(input->as<TensorView>(), prob);
value_map.emplace(
node->output(0)->unique(),
ValueHolder(result.output, format));
value_map.emplace(
node->output(1)->unique(), ValueHolder(result.mask, format));
} else {
value_map.emplace(node->output(0)->unique(), input);
value_map.emplace(
node->output(1)->unique(),
ValueHolder(TensorViewBuilder().build(), format));
}
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
if (node->inputs()[2]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::dropout(Tensor input, float p, bool train) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto input = list_val.front();
list_val.pop_front();
auto prob = list_val.front();
list_val.pop_front();
auto train = constant_as<bool>(node->input(2));
TORCH_INTERNAL_ASSERT(
train.has_value(), "dropout needs constant `train` flag");
if (train.value()) {
auto result = dropout(input->as<TensorView>(), prob);
value_map.emplace(
node->output()->unique(), ValueHolder(result.output, format));
} else {
value_map.emplace(
node->output()->unique(), ValueHolder(input, format));
}
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
if (node->inputs()[2]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::native_dropout_backward(Tensor grad_output, Tensor mask, float scale) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()],
value_map[node->inputs()[2]->unique()]);
auto grad = list_val.front();
list_val.pop_front();
auto mask = list_val.front();
list_val.pop_front();
auto scale = list_val.front();
list_val.pop_front();
auto output = dropout_backward(
grad->as<TensorView>(), mask->as<TensorView>(), scale);
value_map.emplace(
node->output()->unique(), ValueHolder(output, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{
std::array<const char*, kNumInstancenormFwd> InstanceNormFwd = {
"aten::instance_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool use_input_stats, float momentum, float eps, bool cudnn_enabled) -> Tensor"};
for (auto signature : InstanceNormFwd) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
// TODO: handle channels last
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto input_t = list_val.front();
list_val.pop_front();
auto input = input_t->as<TensorView>();
TensorView* weight = nullptr;
if (!node->input(1)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
weight = value_map[node->input(1)->unique()]->as<TensorView>();
}
TensorView* bias = nullptr;
if (!node->input(2)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
bias = value_map[node->input(2)->unique()]->as<TensorView>();
}
TensorView* running_mean = nullptr;
if (!node->input(3)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
running_mean =
value_map[node->input(3)->unique()]->as<TensorView>();
}
TensorView* running_var = nullptr;
if (!node->input(4)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
running_var =
value_map[node->input(4)->unique()]->as<TensorView>();
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto use_input_stats = constant_as<bool>(node->input(5));
TORCH_INTERNAL_ASSERT(
use_input_stats.has_value(),
"The use_input_stats (bool) parameter is required.");
const bool kUseInputStats = use_input_stats.value();
Val* momentum_ptr = nullptr;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (auto momentum = constant_as<float>(node->input(6))) {
momentum_ptr = IrBuilder::create<Double>(momentum.value());
} else {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
momentum_ptr = value_map[node->input(6)->unique()];
}
Val* eps_ptr = nullptr;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (auto eps = constant_as<float>(node->input(7))) {
eps_ptr = IrBuilder::create<Double>(eps.value());
} else {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
eps_ptr = value_map[node->input(7)->unique()];
}
auto result = instance_norm(
input,
weight,
bias,
running_mean,
running_var,
kUseInputStats,
momentum_ptr,
eps_ptr);
if (node->kind() ==
c10::Symbol::fromQualString("aten::instance_norm")) {
value_map.emplace(node->output()->unique(), result.output);
}
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Normalization;
});
}
}
{
std::array<const char*, kNumBatchnormFwd> BatchNormFwd = {
"aten::_batch_norm_impl_index(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> (Tensor, Tensor, Tensor, Tensor, int)",
"aten::native_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)",
"aten::batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor"};
for (auto signature : BatchNormFwd) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
Val* operand = nullptr;
std::tie(format, operand) =
value_map[node->input(0)->unique()].getEntry();
if (format.hasPermutation() && !format.isChannelsLast()) {
format = MemoryFormat::Contiguous();
operand = value_map[node->input(0)->unique()].maybeConvertValue(
format);
}
auto input = operand->as<TensorView>();
TensorView* weight = nullptr;
if (!node->input(1)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
weight = value_map[node->input(1)->unique()]->as<TensorView>();
}
TensorView* bias = nullptr;
if (!node->input(2)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
bias = value_map[node->input(2)->unique()]->as<TensorView>();
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto training = constant_as<bool>(node->input(5));
TORCH_INTERNAL_ASSERT(
training.has_value(),
"The training (bool) parameter is required.");
const bool kTraining = training.value();
TensorView* running_mean = nullptr;
if (!node->input(3)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
running_mean =
value_map[node->input(3)->unique()]->as<TensorView>();
}
TensorView* running_var = nullptr;
if (!node->input(4)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
running_var =
value_map[node->input(4)->unique()]->as<TensorView>();
}
Val* momentum_ptr = nullptr;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (auto momentum = constant_as<float>(node->input(6))) {
momentum_ptr = IrBuilder::create<Double>(momentum.value());
} else {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
momentum_ptr = value_map[node->input(6)->unique()];
}
Val* eps_ptr = nullptr;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (auto eps = constant_as<float>(node->input(7))) {
eps_ptr = IrBuilder::create<Double>(eps.value());
} else {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
eps_ptr = value_map[node->input(7)->unique()];
}
auto result = batch_norm(
input,
weight,
bias,
running_mean,
running_var,
kTraining,
momentum_ptr,
eps_ptr,
format.isChannelsLast());
if (node->kind() ==
c10::Symbol::fromQualString("aten::native_batch_norm") ||
node->kind() ==
c10::Symbol::fromQualString(
"aten::_batch_norm_impl_index")) {
// TODO: output 3 & 4 are not created
// we are not creating these outputs because codegen
// currently lacks the support.
value_map.emplace(
node->output(0)->unique(),
ValueHolder(result.output, format));
value_map.emplace(node->output(1)->unique(), result.mean);
value_map.emplace(node->output(2)->unique(), result.invstd);
} else if (
node->kind() ==
c10::Symbol::fromQualString("aten::batch_norm")) {
value_map.emplace(
node->output()->unique(),
ValueHolder(result.output, format));
}
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
if (node->input(5)->node()->kind() != prim::Constant) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Normalization;
});
}
}
{
std::array<const char*, kNumBatchnormBwd> BatchNormBwd = {
"aten::_batch_norm_impl_index_backward(int impl_index, Tensor input, Tensor grad_output, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var_transform, bool train, float eps, bool[3] output_mask, Tensor reservedSpace) -> (Tensor, Tensor, Tensor)",
"aten::native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor)"};
for (auto signature : BatchNormBwd) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
JitValue* ts_input = nullptr;
JitValue* ts_grad_output;
JitValue* ts_weight = nullptr;
JitValue* ts_r_mean = nullptr;
JitValue* ts_r_var = nullptr;
JitValue* ts_save_mean = nullptr;
JitValue* ts_save_invstd = nullptr;
JitValue* ts_train = nullptr;
JitValue* ts_eps = nullptr;
JitValue* ts_mask = nullptr;
if (node->kind() ==
c10::Symbol::fromQualString(
"aten::_batch_norm_impl_index_backward")) {
ts_input = node->input(1);
ts_grad_output = node->input(2);
ts_weight = node->input(3);
ts_r_mean = node->input(4);
ts_r_var = node->input(5);
ts_save_mean = node->input(6);
ts_save_invstd = node->input(7);
ts_train = node->input(8);
ts_eps = node->input(9);
ts_mask = node->input(10);
} else if (
node->kind() ==
c10::Symbol::fromQualString(
"aten::native_batch_norm_backward")) {
ts_grad_output = node->input(0);
ts_input = node->input(1);
ts_weight = node->input(2);
ts_r_mean = node->input(3);
ts_r_var = node->input(4);
ts_save_mean = node->input(5);
ts_save_invstd = node->input(6);
ts_train = node->input(7);
ts_eps = node->input(8);
ts_mask = node->input(9);
} else {
TORCH_INTERNAL_ASSERT(
false,
"Forgot to register the key for BN variation: ",
node->kind().toDisplayString());
}
// discard impl_index and reservedSpace since we don't use them
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt,
value_map[ts_input->unique()],
value_map[ts_grad_output->unique()]);
if (format.hasPermutation() && !format.isChannelsLast()) {
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[ts_input->unique()],
value_map[ts_grad_output->unique()]);
}
auto operand0 = list_val.front();
list_val.pop_front();
auto operand1 = list_val.front();
list_val.pop_front();
auto input = operand0->as<TensorView>();
auto grad_out = operand1->as<TensorView>();
TensorView* weight = nullptr;
if (!ts_weight->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
weight = value_map[ts_weight->unique()]->as<TensorView>();
}
TensorView* running_mean = nullptr;
if (!ts_r_mean->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
running_mean = value_map[ts_r_mean->unique()]->as<TensorView>();
}
TensorView* running_var = nullptr;
if (!ts_r_var->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
running_var = value_map[ts_r_var->unique()]->as<TensorView>();
}
TensorView* save_mean = nullptr;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (!ts_save_mean->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
save_mean = value_map[ts_save_mean->unique()]->as<TensorView>();
}
TensorView* save_invstd = nullptr;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (!ts_save_invstd->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
save_invstd =
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
value_map[ts_save_invstd->unique()]->as<TensorView>();
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto training = constant_as<bool>(ts_train);
TORCH_INTERNAL_ASSERT(
training.has_value(),
"The training (bool) parameter is required.");
const bool kTraining = training.value();
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
Val* eps_ptr = nullptr;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (auto eps = constant_as<float>(ts_eps)) {
eps_ptr = IrBuilder::create<Double>(eps.value());
} else {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
eps_ptr = value_map[ts_eps->unique()];
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto out_mask_list = constant_as<c10::List<bool>>(ts_mask);
TORCH_INTERNAL_ASSERT(
out_mask_list.has_value(),
"output mask for batch_norm_backward");
std::vector<bool> output_mask;
for (const auto value : out_mask_list->vec()) {
output_mask.emplace_back(static_cast<bool>(value));
}
// TODO: merge this loop below.
if (kTraining) {
TORCH_INTERNAL_ASSERT(
save_mean != nullptr && save_invstd != nullptr,
"When training=True, save_mean and save_invstd are required.");
} else {
// TODO: this is not a legit assumption? Can't we run with
// track_running_stats == false && training == false
// which should just run through the case above.
TORCH_INTERNAL_ASSERT(
running_mean != nullptr && running_var != nullptr,
"When training=False, running_mean and running_invstd are required.");
}
auto grads = batch_norm_backward(
input,
grad_out,
weight,
running_mean,
running_var,
save_mean,
save_invstd,
kTraining,
eps_ptr,
output_mask,
format.isChannelsLast());
if (output_mask[0]) {
TORCH_INTERNAL_ASSERT(grads.grad_input != nullptr);
value_map.emplace(
node->output(0)->unique(),
ValueHolder(grads.grad_input, format));
} else {
TORCH_INTERNAL_ASSERT(grads.grad_input == nullptr);
value_map.emplace(
node->output(0)->unique(),
ValueHolder(TensorViewBuilder().build(), format));
}
if (output_mask[1]) {
TORCH_INTERNAL_ASSERT(grads.grad_weight != nullptr);
value_map.emplace(node->output(1)->unique(), grads.grad_weight);
} else {
TORCH_INTERNAL_ASSERT(grads.grad_weight == nullptr);
value_map.emplace(
node->output(1)->unique(), TensorViewBuilder().build());
}
if (output_mask[2]) {
TORCH_INTERNAL_ASSERT(grads.grad_bias != nullptr);
value_map.emplace(node->output(2)->unique(), grads.grad_bias);
} else {
TORCH_INTERNAL_ASSERT(grads.grad_bias == nullptr);
value_map.emplace(
node->output(2)->unique(), TensorViewBuilder().build());
}
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(1)->type()->cast<TensorType>())) {
return false;
}
if (node->kind() ==
c10::Symbol::fromQualString(
"aten::_batch_norm_impl_index_backward")) {
if (node->inputs()[8]->node()->kind() != prim::Constant) {
return false;
}
if (node->inputs()[10]->node()->kind() != prim::Constant) {
return false;
}
} else if (
node->kind() ==
c10::Symbol::fromQualString(
"aten::native_batch_norm_backward")) {
if (node->inputs()[7]->node()->kind() != prim::Constant) {
return false;
}
if (node->inputs()[9]->node()->kind() != prim::Constant) {
return false;
}
} else {
TORCH_INTERNAL_ASSERT(
false,
"Forgot to update profiled constant check for",
node->kind().toDisplayString());
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Normalization;
});
}
}
{
std::array<const char*, kNumLayernormFwd> LayerNormFwd = {
"aten::native_layer_norm(Tensor input, int[] normalized_shape, Tensor? weight, Tensor? bias, float eps) -> (Tensor, Tensor, Tensor)",
"aten::layer_norm(Tensor input, int[] normalized_shape, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enable=True) -> Tensor"};
for (auto signature : LayerNormFwd) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto input_t = list_val.front();
list_val.pop_front();
auto input = input_t->as<TensorView>();
auto norm_shape_optional =
constant_as<c10::List<int64_t>>(node->input(1));
TORCH_INTERNAL_ASSERT(
norm_shape_optional.has_value(),
"The Normalized_Shape list is required.");
auto norm_shape = norm_shape_optional->vec();
TensorView* weight = nullptr;
if (!node->input(2)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
weight = value_map[node->input(2)->unique()]->as<TensorView>();
}
TensorView* bias = nullptr;
if (!node->input(3)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
bias = value_map[node->input(3)->unique()]->as<TensorView>();
}
Val* eps_ptr = nullptr;
if (auto eps = constant_as<float>(node->input(4))) {
eps_ptr = IrBuilder::create<Double>(eps.value());
} else {
eps_ptr = value_map[node->input(4)->unique()];
}
auto result =
layer_norm(input, norm_shape, weight, bias, eps_ptr);
if (node->kind() ==
c10::Symbol::fromQualString("aten::native_layer_norm")) {
value_map.emplace(node->output(0)->unique(), result.output);
value_map.emplace(node->output(1)->unique(), result.mean);
value_map.emplace(node->output(2)->unique(), result.invstd);
} else if (
node->kind() ==
c10::Symbol::fromQualString("aten::layer_norm")) {
value_map.emplace(node->output()->unique(), result.output);
}
},
// TODO: #ProfileIValue List should update this
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Normalization;
});
}
}
{
auto ptr_op = getOperatorForLiteral(
"aten::native_layer_norm_backward(Tensor grad_out, Tensor input, int[] normalized_shape, Tensor mean, Tensor rstd, Tensor? weight, Tensor? bias, bool[3] output_mask) -> (Tensor, Tensor, Tensor)");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto grad_out_t = list_val.front();
list_val.pop_front();
auto input_t = list_val.front();
list_val.pop_front();
auto grad_out = grad_out_t->as<TensorView>();
auto input = input_t->as<TensorView>();
auto norm_shape_optional =
constant_as<c10::List<int64_t>>(node->input(2));
TORCH_INTERNAL_ASSERT(
norm_shape_optional.has_value(),
"The Normalized_Shape list is required.");
auto norm_shape = norm_shape_optional->vec();
auto mean = value_map[node->input(3)->unique()]->as<TensorView>();
auto rstd = value_map[node->input(4)->unique()]->as<TensorView>();
TensorView* weight = nullptr;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (!node->input(5)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
weight = value_map[node->input(5)->unique()]->as<TensorView>();
}
TensorView* bias = nullptr;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
if (!node->input(6)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
bias = value_map[node->input(6)->unique()]->as<TensorView>();
}
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
auto output_mask_optional =
constant_as<c10::List<bool>>(node->input(7));
TORCH_INTERNAL_ASSERT(
output_mask_optional.has_value(),
"output mask for layer_norm_backward");
std::vector<bool> output_mask = output_mask_optional->vec();
auto grad = layer_norm_backward(
grad_out,
input,
norm_shape,
mean,
rstd,
weight,
bias,
output_mask);
if (output_mask[0]) {
TORCH_INTERNAL_ASSERT(grad.grad_input != nullptr);
value_map.emplace(node->output(0)->unique(), grad.grad_input);
} else {
TORCH_INTERNAL_ASSERT(grad.grad_input == nullptr);
value_map.emplace(
node->output(0)->unique(), TensorViewBuilder().build());
}
if (output_mask[1] && weight != nullptr) {
TORCH_INTERNAL_ASSERT(grad.grad_weight != nullptr);
value_map.emplace(node->output(1)->unique(), grad.grad_weight);
} else {
TORCH_INTERNAL_ASSERT(grad.grad_weight == nullptr);
value_map.emplace(
node->output(1)->unique(), TensorViewBuilder().build());
}
if (output_mask[2] && bias != nullptr) {
TORCH_INTERNAL_ASSERT(grad.grad_bias != nullptr);
value_map.emplace(node->output(2)->unique(), grad.grad_bias);
} else {
TORCH_INTERNAL_ASSERT(grad.grad_bias == nullptr);
value_map.emplace(
node->output(2)->unique(), TensorViewBuilder().build());
}
},
// TODO: #ProfileIValue List should update this
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
if (node->inputs()[2]->node()->kind() != prim::Constant) {
return false;
}
if (node->inputs()[7]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Normalization;
});
}
{
std::array<const char*, kNumSoftmaxFwd> SoftmaxFwd = {
"aten::softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor",
"aten::log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor"};
for (auto signature : SoftmaxFwd) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto input_t = list_val.front();
list_val.pop_front();
auto input = input_t->as<TensorView>();
auto dim_value = constant_as<int>(node->input(1));
TORCH_INTERNAL_ASSERT(
dim_value.has_value(), "dim in softmax is not valid");
auto data_type = DataType::Null;
if (const auto opt_ivalue = toIValue(node->input(2))) {
if (!opt_ivalue->isNone()) {
data_type = aten_to_data_type(opt_ivalue->toScalarType());
}
}
input = (data_type != DataType::Null)
? optionalCastStrict(data_type, input)->as<TensorView>()
: input;
bool is_log_softmax = node->kind() ==
c10::Symbol::fromQualString("aten::log_softmax");
auto output = (is_log_softmax)
? log_softmax(input, dim_value.value())
: softmax(input, dim_value.value());
value_map.emplace(node->output()->unique(), output);
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
if (!isScalarTypeCompatible(node, 2)) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Normalization;
});
}
}
{ // LTC uses this op for softmax
auto ptr_op = getOperatorForLiteral(
"aten::_softmax(Tensor self, int dim, bool half_to_float) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto input_t = list_val.front();
list_val.pop_front();
auto input = input_t->as<TensorView>();
auto dim_value = constant_as<int>(node->input(1));
TORCH_INTERNAL_ASSERT(
dim_value.has_value(), "dim in softmax is not valid");
auto output = softmax(input, dim_value.value());
value_map.emplace(node->output()->unique(), output);
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
if (node->inputs()[2]->node()->kind() != prim::Constant) {
return false;
} else {
const auto half_to_float = constant_as<bool>(node->input(2));
TORCH_INTERNAL_ASSERT(
half_to_float.has_value(), "Bool half_to_float is not valid");
auto input_tensor_type =
node->input(0)->type()->cast<TensorType>();
if (half_to_float.value() &&
input_tensor_type->scalarType() != at::ScalarType::Half) {
return false;
}
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Normalization;
});
}
{
std::array<const char*, kNumSoftmaxBwd> SoftmaxBwd = {
"aten::_log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor",
"aten::_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor"};
for (auto signature : SoftmaxBwd) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto grad_output_t = list_val.front();
list_val.pop_front();
auto grad_output = grad_output_t->as<TensorView>();
auto output_t = list_val.front();
list_val.pop_front();
auto output = output_t->as<TensorView>();
auto dim_value = constant_as<int>(node->input(2));
TORCH_INTERNAL_ASSERT(
dim_value.has_value(), "dim in softmax is not valid");
// input_dtype here is ignored! type_inference handles it
bool is_log_softmax = node->kind() ==
c10::Symbol::fromQualString(
"aten::_log_softmax_backward_data");
auto grad_input = (is_log_softmax)
? log_softmax_backward(grad_output, output, dim_value.value())
: softmax_backward(grad_output, output, dim_value.value());
value_map.emplace(node->output()->unique(), grad_input);
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
if (node->inputs()[2]->node()->kind() != prim::Constant) {
return false;
}
if (node->inputs()[3]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Normalization;
});
}
}
{
std::array<const char*, kNumVarOps> Variance = {
"aten::var.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor",
"aten::std.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor"};
for (auto signature : Variance) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto input_t = list_val.front();
list_val.pop_front();
auto input = input_t->as<TensorView>();
bool is_variance =
node->kind() == c10::Symbol::fromQualString("aten::var");
auto dims_list = constant_as<c10::List<int64_t>>(node->input(1));
TORCH_INTERNAL_ASSERT(
dims_list.has_value(), "Cannot fuse with dynamic axes");
std::vector<int> dims;
if (!dims_list->empty()) {
for (const auto dim : dims_list->vec()) {
dims.emplace_back(static_cast<int>(dim));
}
} else {
dims.resize(input->as<TensorView>()->nDims());
std::iota(dims.begin(), dims.end(), 0);
}
auto unbiased = constant_as<bool>(node->input(2));
TORCH_INTERNAL_ASSERT(
unbiased.has_value(), "Cannot fuse with dynamic unbiased");
auto keepdim = constant_as<bool>(node->input(3));
TORCH_INTERNAL_ASSERT(
keepdim.has_value(), "Cannot fuse with dynamic keepdim");
auto output = (is_variance)
? variance(input, dims, unbiased.value(), keepdim.value())
: standard_deviation(
input, dims, unbiased.value(), keepdim.value());
value_map.emplace(node->output()->unique(), output);
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Normalization;
});
}
}
{
auto ptr_op = getOperatorForLiteral(
"aten::sum.dim_IntList(Tensor self, int[1]? dim, bool keepdim=False, *, int? dtype=None) -> (Tensor)");
REGISTER_PARSE_RULE(
ptr_op,
{
// TODO: support channels last in sum
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto self = list_val.front();
list_val.pop_front();
auto dims_list = constant_as<c10::List<int64_t>>(node->input(1));
TORCH_INTERNAL_ASSERT(
dims_list.has_value(),
"aten::sum cannot be fused with dynamic axes");
std::vector<int> dims;
if (!dims_list->empty()) {
for (const auto dim : dims_list->vec()) {
dims.emplace_back(static_cast<int>(dim));
}
} else {
dims.resize(self->as<TensorView>()->nDims());
std::iota(dims.begin(), dims.end(), 0);
}
auto keepdim = constant_as<bool>(node->input(2));
TORCH_INTERNAL_ASSERT(
keepdim.has_value(),
"aten::sum cannot be fused with dynamic keepdim");
auto out = sum(self->as<TensorView>(), dims, keepdim.value());
value_map.emplace(node->output()->unique(), out);
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
// TODO: support cast of output types
if (!node->inputs()[3]->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
// We can only handle output as half, float, and double;
if (const auto opt_ivalue = toIValue(node->input(3))) {
const auto scalar_type = opt_ivalue->toScalarType();
if (!at::isFloatingType(scalar_type)) {
return false;
}
}
}
// we don't support dynamic reduction axes;
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
// we don't support dynamic keepdim yet;
if (node->inputs()[2]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Reduction;
});
}
{
auto ptr_op = getOperatorForLiteral(
"aten::mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto operand = list_val.front();
list_val.pop_front();
auto self = operand->as<TensorView>();
auto dims_list = constant_as<c10::List<int64_t>>(node->input(1));
TORCH_INTERNAL_ASSERT(
dims_list.has_value(),
"aten::mean cannot be fused with dynamic axes");
std::vector<int> dims;
if (!dims_list->empty()) {
for (const auto dim : dims_list->vec()) {
dims.emplace_back(static_cast<int>(dim));
}
} else {
dims.resize(self->as<TensorView>()->nDims());
std::iota(dims.begin(), dims.end(), 0);
}
auto keepdim = constant_as<bool>(node->input(2));
TORCH_INTERNAL_ASSERT(
keepdim.has_value(),
"aten::mean cannot be fused with dynamic keepdim");
auto o_sum = sum(self, dims, keepdim.value());
Val* num_features = IrBuilder::create<Double>(1);
for (auto axis : dims) {
if (axis < 0) {
axis += int(self->nDims());
}
num_features =
mul(num_features, self->domain()->domain()[axis]->extent());
}
auto out = div(o_sum, num_features);
value_map.emplace(node->output()->unique(), out);
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
// TODO: support cast of output types
if (!node->inputs()[3]->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
// We can only handle output as half, float, and double;
if (const auto opt_ivalue = toIValue(node->input(3))) {
const auto scalar_type = opt_ivalue->toScalarType();
if (!at::isFloatingType(scalar_type)) {
return false;
}
}
}
// we don't support dynamic reduction axes;
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
// we don't support dynamic keepdim yet;
if (node->inputs()[2]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Reduction;
});
}
{
std::array<const char*, kNumSumToSize> SumToSize = {
"aten::_grad_sum_to_size(Tensor(a) self, int[]? size) -> Tensor(a)",
"aten::sum_to_size(Tensor self, int[] size) -> Tensor"};
for (auto signature : SumToSize) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto self = list_val.front();
list_val.pop_front();
auto size_to = constant_as<c10::List<int64_t>>(node->input(1));
TORCH_INTERNAL_ASSERT(
size_to.has_value(),
"aten::sum cannot be fused with dynamic axes");
if (!size_to->empty()) {
auto input = self->as<TensorView>();
auto out = sum_to(input, size_to->vec());
// this copy is not necessary, but making copy avoids tricky
// computational graph where no-op could be challenging.
if (out == input) {
out = set(input);
}
value_map.emplace(node->output()->unique(), out);
} else {
// We are introducing alias here!
value_map.emplace(node->output()->unique(), self);
}
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
// we don't support dynamic reduction axes;
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
auto size_to = constant_as<c10::List<int64_t>>(node->input(1));
// technically size_to->empty() should never occur, as specialized
// _grad_sum_to_size should have been removed by optimization pass
if (size_to->empty()) {
return OperatorType::ElementWise;
} else {
return OperatorType::ReductionToSize;
}
});
}
}
{
std::array<const char*, kNumAutocastOps> AutocastOps = {
"aten::_autocast_to_reduced_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled, ScalarType cuda_dtype, ScalarType cpu_dtype) -> Tensor(a)",
"aten::_autocast_to_full_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled) -> Tensor(a)"};
for (auto signature : AutocastOps) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto self = list_val.front();
list_val.pop_front();
auto out = set(self);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
}
{
auto ptr_op = getOperatorForLiteral(
"aten::_to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto self = list_val.front();
list_val.pop_front();
auto out = castTensoToDtype(self, node->input(1));
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
// we do not support explicit memory_format on output
if (!node->inputs()[2]->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
return false;
}
// we do not support explicit memory_format on output
if (!node->inputs()[3]->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
return false;
}
// we do not support explicit memory_format on output
if (!node->inputs()[4]->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
return false;
}
// we do not support explicit memory_format on output
if (!node->inputs()[6]->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
return false;
}
return true;
},
nullptr);
}
// Limiting aten::to implementation to only change the dtype of a tensor
{
auto ptr_op = getOperatorForLiteral(
"aten::to.dtype(Tensor self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto self = list_val.front();
list_val.pop_front();
auto out = castTensoToDtype(self, node->input(1));
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
// we do not support explicit memory_format on output
if (!node->inputs()[4]->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
return false;
}
return true;
},
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::type_as(Tensor self, Tensor other) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto self = list_val.front();
list_val.pop_front();
// TODO: switch to PyTorch dtype as it's closer to truth.
// For now, reality is that PyTorch IR profiling information could
// be missing even with profiling executor, due to upstream
// transformations between profiling runs to fusion pass.
auto opt_dtype =
value_map[node->inputs()[1]->unique()]->getDataType();
TORCH_INTERNAL_ASSERT(opt_dtype.has_value());
auto out = castOp(opt_dtype.value(), self);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{
// We are not fusing `linear` yet, because we can't codegen efficient gemm
// However, we still need this here, so PE would insert profile node for
// this node.
// During fusion pass, We decompose linear into gemm + elementwise.
auto ptr_op = getOperatorForLiteral(
"aten::linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
// this entry is created so we do profile input tensors;
TORCH_INTERNAL_ASSERT(false, "not implemented yet");
},
[](const Node* node) -> bool {
// We only profile `linear` layer but not fusing it.
return false;
});
}
{
auto ptr_op = getOperatorForLiteral(
"prim::add_optional(Tensor(a) input, Tensor? bias) -> Tensor(a)");
REGISTER_PARSE_RULE(
ptr_op,
{
// this entry is created so we do profile input tensors;
if (node->input(1)->type()->isSubtypeOf(
static_cast<c10::TypePtr>(NoneType::get()))) {
// forwarding the value;
value_map.emplace(
node->output()->unique(),
value_map[node->inputs()[0]->unique()]);
} else {
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto lhs = list_val.front();
list_val.pop_front();
auto rhs = list_val.front();
list_val.pop_front();
auto out = binaryOp(
BinaryOpType::Add,
lhs,
rhs,
TypePromotion::default_op_config);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
}
},
isInputNonSizeZeroTensor,
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::leaky_relu(Tensor self, Scalar negative_slope=0.01) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
Val* negative_slope = value_map[node->inputs()[1]->unique()];
auto out = leaky_relu(self, negative_slope);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
return true;
},
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::gelu(Tensor self, *, str approximate='none') -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
c10::nullopt, value_map[node->inputs()[0]->unique()]);
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
auto approximate = constant_as<std::string>(node->input(1));
TORCH_INTERNAL_ASSERT(
approximate.has_value(),
"The approximate parameter is required.");
const auto kTanhGelu =
at::native::get_gelutype_enum(approximate.value()) ==
at::native::GeluType::Tanh;
auto out = (kTanhGelu) ? tanh_gelu(self) : gelu(self);
value_map.emplace(
node->output()->unique(), ValueHolder(out, format));
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
if (node->input(1)->node()->kind() != prim::Constant) {
return false;
}
return true;
},
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::gelu_backward(Tensor grad_output, Tensor self, *, str approximate='none') -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto grad_out = list_val.front()->as<TensorView>();
list_val.pop_front();
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
auto approximate = constant_as<std::string>(node->input(2));
TORCH_INTERNAL_ASSERT(
approximate.has_value(),
"The approximate parameter is required.");
const auto kTanhGelu =
at::native::get_gelutype_enum(approximate.value()) ==
at::native::GeluType::Tanh;
auto grad_in = (kTanhGelu) ? tanh_gelu_backward(grad_out, self)
: gelu_backward(grad_out, self);
value_map.emplace(
node->output()->unique(), ValueHolder(grad_in, format));
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
if (node->input(2)->node()->kind() != prim::Constant) {
return false;
}
return true;
},
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"aten::tanh_backward(Tensor grad_output, Tensor output) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto grad_out = list_val.front()->as<TensorView>();
list_val.pop_front();
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
auto grad_in = tanh_backward(grad_out, self);
value_map.emplace(
node->output()->unique(), ValueHolder(grad_in, format));
},
isInputNonSizeZeroTensor,
nullptr);
}
{
std::array<const char*, kNumAminAmaxOps> BinaryFloatOp = {
"aten::amax(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor",
"aten::amin(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor"};
for (auto signature : BinaryFloatOp) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto self = list_val.front();
list_val.pop_front();
auto dims_list = constant_as<c10::List<int64_t>>(node->input(1));
TORCH_INTERNAL_ASSERT(
dims_list.has_value(),
"aten::amax/amin cannot be fused with dynamic axes");
std::vector<int> dims;
if (!dims_list->empty()) {
for (const auto dim : dims_list->vec()) {
dims.emplace_back(static_cast<int>(dim));
}
} else {
dims.resize(self->as<TensorView>()->nDims());
std::iota(dims.begin(), dims.end(), 0);
}
auto keepdim = constant_as<bool>(node->input(2));
TORCH_INTERNAL_ASSERT(
keepdim.has_value(),
"aten::amax/amin cannot be fused with dynamic keepdim");
TensorView* out = nullptr;
if (node->kind() == c10::Symbol::fromQualString("aten::amax")) {
out = max(self->as<TensorView>(), dims, keepdim.value());
} else if (
node->kind() == c10::Symbol::fromQualString("aten::amin")) {
out = min(self->as<TensorView>(), dims, keepdim.value());
} else {
TORCH_INTERNAL_ASSERT(
false, "unrecognized operation in aten::amax/amin");
}
value_map.emplace(node->output()->unique(), out);
},
[](const Node* node) -> bool {
if (isReductionNonCompatibleTensor(
node->input(0)->type()->cast<TensorType>())) {
return false;
}
// we don't support dynamic reduction axes;
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
// we don't support dynamic keepdim yet;
if (node->inputs()[2]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
[](const Node* node) -> OperatorType {
return OperatorType::Reduction;
});
}
}
{
std::array<const char*, kNumViewOps> ViewOps = {
"prim::reshape_copy(Tensor self, int[] shape) -> Tensor",
"prim::view_copy(Tensor self, int[] size) -> Tensor"};
for (auto signature : ViewOps) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
auto self_value = node->inputs()[0];
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(), value_map[self_value->unique()]);
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
auto self_type = self_value->type()->cast<c10::TensorType>();
TORCH_INTERNAL_ASSERT(self_type != nullptr);
auto self_sizes = getTensorSizes(self_type);
auto view_sizes = constant_as<c10::List<int64_t>>(node->input(1));
TORCH_INTERNAL_ASSERT(
view_sizes.has_value(), "The size parameter is required.");
auto output = view(self, self_sizes, view_sizes->vec());
value_map.emplace(node->output()->unique(), output);
},
[](const Node* node) -> bool {
auto self_value = node->inputs()[0];
auto tensor_type = self_value->type()->cast<c10::TensorType>();
if (tensor_type == nullptr) {
return false;
}
if (!tensor_type->sizes().concrete_sizes().has_value()) {
// Shape information for input tensor is required.
return false;
}
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
// Reject fusing node if view_sizes contains an inferred dimension
auto view_sizes = constant_as<c10::List<int64_t>>(node->input(1));
if (!view_sizes.has_value()) {
// The size parameter is required.
return false;
}
for (auto axis_size : view_sizes->vec()) {
if (axis_size == -1) {
return false;
}
}
return true;
},
nullptr);
}
}
{
auto flatten_op = getOperatorForLiteral(
"prim::flatten_copy(Tensor self, int start_dim, int end_dim) -> Tensor");
REGISTER_PARSE_RULE(
flatten_op,
{
auto self_value = node->inputs()[0];
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(), value_map[self_value->unique()]);
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
auto start_dim_value = constant_as<int>(node->input(1));
TORCH_INTERNAL_ASSERT(
start_dim_value.has_value(), "start_dim is not valid");
auto end_dim_value = constant_as<int>(node->input(2));
TORCH_INTERNAL_ASSERT(
end_dim_value.has_value(), "end_dim is not valid");
TensorView* output =
flatten(self, start_dim_value.value(), end_dim_value.value());
value_map.emplace(node->output()->unique(), output);
},
[](const Node* node) -> bool {
// we don't support dynamic start_dim;
if (node->inputs()[1]->node()->kind() != prim::Constant) {
return false;
}
// we don't support dynamic end_dim yet;
if (node->inputs()[2]->node()->kind() != prim::Constant) {
return false;
}
return true;
},
nullptr);
}
{
auto ptr_op =
getOperatorForLiteral("prim::squeeze_copy(Tensor self) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
auto self_value = node->inputs()[0];
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(), value_map[self_value->unique()]);
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
auto self_type = self_value->type()->cast<c10::TensorType>();
TORCH_INTERNAL_ASSERT(self_type != nullptr);
auto self_sizes = getTensorSizes(self_type);
TensorView* output = nullptr;
if (self_sizes.empty()) {
// squeeze on scalar tensor should just return itself;
output = set(self);
} else {
output = squeeze(self, self_sizes);
}
value_map.emplace(node->output()->unique(), output);
},
[](const Node* node) -> bool {
// Shape information for input tensor is required.
auto self_value = node->inputs()[0];
auto tensor_type = self_value->type()->cast<c10::TensorType>();
if (tensor_type == nullptr) {
return false;
}
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
return tensor_type->sizes().concrete_sizes().has_value();
},
nullptr);
}
{
std::array<const char*, kNumAliasDimOps> AliasOpWithDim = {
"prim::squeeze_copy.dim(Tensor self, int dim) -> Tensor",
"prim::unsqueeze_copy(Tensor self, int dim) -> Tensor"};
for (auto signature : AliasOpWithDim) {
auto ptr_op = getOperatorForLiteral(signature);
REGISTER_PARSE_RULE(
ptr_op,
{
auto self_value = node->inputs()[0];
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(),
value_map[node->inputs()[0]->unique()]);
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
auto dim_value = constant_as<int>(node->input(1));
TORCH_INTERNAL_ASSERT(dim_value.has_value(), "dim is not valid");
TensorView* output = nullptr;
if (node->kind() == prim::unsqueeze_copy) {
output = unsqueeze(self, dim_value.value());
} else {
auto self_type = self_value->type()->cast<c10::TensorType>();
TORCH_INTERNAL_ASSERT(self_type != nullptr);
auto self_sizes = getTensorSizes(self_type);
if (self_sizes.empty()) {
// squeeze on scalar tensor should just return itself;
output = set(self);
} else {
output = squeeze(self, self_sizes, dim_value.value());
}
}
value_map.emplace(node->output()->unique(), output);
},
[](const Node* node) -> bool {
// Shape information for input tensor is required.
auto self_value = node->inputs()[0];
auto tensor_type = self_value->type()->cast<c10::TensorType>();
if (tensor_type == nullptr) {
return false;
}
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
if (node->input(1)->node()->kind() != prim::Constant) {
return false;
}
auto optional_sizes = tensor_type->sizes().concrete_sizes();
return tensor_type->sizes().concrete_sizes().has_value();
},
nullptr);
}
}
{
auto ptr_op = getOperatorForLiteral(
"prim::expand_as_copy(Tensor self, Tensor other) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getPWFormatValues(
c10::nullopt,
value_map[node->inputs()[0]->unique()],
value_map[node->inputs()[1]->unique()]);
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
auto other = list_val.front()->as<TensorView>();
list_val.pop_front();
auto output = expand_as(self, other);
value_map.emplace(
node->output()->unique(), ValueHolder(output, format));
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
return true;
},
nullptr);
}
{
auto ptr_op = getOperatorForLiteral(
"prim::expand_copy(Tensor self, int[] size, *, bool implicit=False) -> Tensor");
REGISTER_PARSE_RULE(
ptr_op,
{
auto self_value = node->inputs()[0];
MemoryFormat format;
std::list<Val*> list_val;
std::tie(format, list_val) = getConsistentValues(
MemoryFormat::Contiguous(), value_map[self_value->unique()]);
auto self = list_val.front()->as<TensorView>();
list_val.pop_front();
auto expand_sizes = constant_as<c10::List<int64_t>>(node->input(1));
TORCH_INTERNAL_ASSERT(
expand_sizes.has_value(), "The size parameter is required.");
std::vector<CgValue> expand_sizes_vec;
for (const int64_t& size : expand_sizes.value()) {
expand_sizes_vec.push_back(IrBuilder::create<Int>(size));
}
// TODO: we should be able to support dynamic expand values
auto output = expand(self, expand_sizes_vec);
value_map.emplace(node->output()->unique(), output);
},
[](const Node* node) -> bool {
if (!isInputNonSizeZeroTensor(node)) {
return false;
}
// expand_sizes needs to be constant
auto expand_sizes = constant_as<c10::List<int64_t>>(node->input(1));
if (!expand_sizes.has_value()) {
return false;
}
return true;
},
nullptr);
}
}
void processJitNode(const JitOp* node) {
if (node->kind() == prim::Constant) {
// partition doesn't take constant node explicitly, but it does and copy
// constant into subgraph. So we need to register constants in codegen IR;
for (auto output : node->outputs()) {
TORCH_INTERNAL_ASSERT(
registerScalar(output),
"registration of output failed at index ",
output->offset(),
" for node ",
*node);
}
} else {
auto reg_entry = lookupInRegistry(node);
TORCH_INTERNAL_ASSERT(
reg_entry != nullptr,
"CudaFusionGroup Parser doesn't handle node: ",
canonicalSchemaString(node->schema()));
reg_entry->parse(node, value_map_);
}
}
bool registerValue(const JitValue* val) {
return registerInputTensor(val) || registerScalar(val);
}
bool registerScalar(const JitValue* val) {
if (val->type()->isSubtypeOf(
static_cast<c10::TypePtr>(ComplexType::get()))) {
CgValue cg_val = nullptr;
if (auto ival = constant_as<c10::complex<double>>(val)) {
cg_val = IrBuilder::create<ComplexDouble>(ival.value());
} else {
cg_val = IrBuilder::create<ComplexDouble>();
}
value_map_.emplace(val->unique(), cg_val);
return true;
} else if (val->type()->isSubtypeOf(
static_cast<c10::TypePtr>(FloatType::get()))) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
CgValue cg_val;
if (auto ival = constant_as<double>(val)) {
cg_val = IrBuilder::create<Double>(ival.value());
} else {
cg_val = IrBuilder::create<Double>();
}
value_map_.emplace(val->unique(), cg_val);
return true;
} else if (val->type()->isSubtypeOf(
static_cast<c10::TypePtr>(IntType::get()))) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
CgValue cg_val;
if (auto ival = constant_as<int64_t>(val)) {
cg_val = IrBuilder::create<Int>(ival.value());
} else {
cg_val = IrBuilder::create<Int>();
}
value_map_.emplace(val->unique(), cg_val);
return true;
} else if (val->type()->isSubtypeOf(
static_cast<c10::TypePtr>(BoolType::get()))) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
CgValue cg_val;
if (auto ival = constant_as<bool>(val)) {
cg_val = IrBuilder::create<Bool>(ival.value());
} else {
cg_val = IrBuilder::create<Bool>();
}
value_map_.emplace(val->unique(), cg_val);
return true;
} else if (
val->type()->isSubtypeOf(
static_cast<c10::TypePtr>(StringType::get())) ||
val->type()->isSubtypeOf(
static_cast<c10::TypePtr>(DeviceObjType::get())) ||
val->type()->isSubtypeOf(static_cast<c10::TypePtr>(NoneType::get()))) {
// TODO: should we consider adding support for NoneType;
// Note: String/Device scalars are only used in parsing rules, do not
// register string with codegen IR.
return true;
} else if (val->type()->cast<ListType>()) {
// TODO: we don't support list type in codegen yet;
// This is a WAR to allow axes of reduction to be passed as constant list;
// We simply ignore conversion if the scalar value is a constant;
auto ivalue = toIValue(val);
TORCH_INTERNAL_ASSERT(
ivalue.has_value(),
"List[T] is not supported as an argument by NvFuser. Use a Constant List.");
return true;
}
return false;
}
bool registerInputTensor(const JitValue* val) {
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
CgValue cg_val;
// Don't register if we don't support the type
if (auto tensor_type = val->type()->cast<c10::TensorType>()) {
if (!tensor_type->scalarType().has_value()) {
return false;
}
if (aten_to_data_type(tensor_type->scalarType().value()) ==
DataType::Null) {
return false;
}
// check for NHWC contiguous tensor
TORCH_CHECK(tensor_type->dim().has_value(), "rank missing");
const auto n_dim = tensor_type->dim().value();
MemoryFormat format;
std::vector<int> stride_index;
for (const auto i : c10::irange(n_dim)) {
const auto& stride_property_i = tensor_type->stride_properties()[i];
if (stride_property_i->stride_index_.has_value()) {
stride_index.emplace_back(stride_property_i->stride_index_.value());
}
}
// only set permutation when all stride_index are available
if (stride_index.size() == n_dim) {
format.setPermutation(stride_index);
}
// construct permuted tensor_type
if (format.hasPermutation()) {
auto opt_s_vec = tensor_type->symbolic_sizes().sizes();
TORCH_CHECK(opt_s_vec.has_value(), "missing rank of symbolic sizes");
std::vector<c10::ShapeSymbol> s_vec = opt_s_vec.value();
// apply permutation
auto permutation = format.apply();
for (auto new_axis : c10::irange(permutation.size())) {
auto old_axis = permutation.at(new_axis);
s_vec[new_axis] = opt_s_vec.value()[old_axis];
}
// copying stride properties because we need to permute it
auto opt_stride_vec = tensor_type->stride_properties().sizes();
TORCH_CHECK(opt_stride_vec.has_value(), "missing stride properties");
auto nhwc_stride_vec = opt_stride_vec.value();
// Make tensor contiguous after permutation.
// Note that we are only updating stride_properties.stride_index, since
// contiguous_ and stride_ value should remain the same after
// permutation
for (const auto i : c10::irange(n_dim)) {
nhwc_stride_vec[i]->stride_index_ = n_dim - i - 1;
}
tensor_type = c10::TensorType::create(
tensor_type->scalarType(),
tensor_type->device(),
s_vec,
nhwc_stride_vec,
tensor_type->requires_grad(),
tensor_type->undefined());
}
cg_val = IrBuilder::create<TensorView>(tensor_type);
if (is_cpu_scalar(*tensor_type)) {
cg_val->as<TensorView>()->setCpuScalar(true);
}
value_map_.emplace(val->unique(), ValueHolder(cg_val, format));
return true;
}
return false;
}
std::shared_ptr<Graph> graph_;
// maps from JitValue::unique() to fusion Val;
std::unordered_map<size_t, ValueHolder> value_map_;
static std::unordered_set<Symbol> parser_symbol_set_;
static std::unordered_set<Symbol> parser_skip_set_;
static std::mutex parser_mutex_;
// parsing rule registry.
static std::unordered_map<std::string, RegistrationEntry>
jit_operator_registry_; // NOLINT
// pointing cached entry stored in `jit_operator_registry_`
static std::unordered_map<const FunctionSchema*, const RegistrationEntry*>
cached_registry_lookup_; // NOLINT
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
static c10::once_flag once_flag_;
};
std::unordered_set<Symbol> IrParser::parser_symbol_set_; // NOLINT
std::unordered_set<Symbol> IrParser::parser_skip_set_; // NOLINT
std::mutex IrParser::parser_mutex_;
std::unordered_map<std::string, IrParser::RegistrationEntry>
IrParser::jit_operator_registry_; // NOLINT
std::unordered_map<const FunctionSchema*, const IrParser::RegistrationEntry*>
IrParser::cached_registry_lookup_; // NOLINT
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
c10::once_flag IrParser::once_flag_;
ProfileIValueOp* insertProfileIValueOp(
Node* node,
size_t offset,
ProfilingRecord* pr) {
auto in_val = node->input(offset);
auto pn = pr->createProfileIValueNode(in_val);
pn->insertBefore(node);
node->replaceInput(offset, pn->output());
return pn;
}
void profileReductionSize(ProfilingRecord* pr, Node* node, size_t offset) {
auto pn = insertProfileIValueOp(node, offset, pr);
const auto ivalue_profiler = [pr, pn](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// TODO: we don't care about merging multiple profiling runs as we don't
// support it at all;
int64_t frame_id = 0;
pop(stack, frame_id);
IValue value;
pop(stack, value);
std::vector<int64_t> size_vec;
if (value.isIntList()) {
size_vec = value.toIntVector();
} else if (value.isNone()) {
size_vec.clear();
} else {
TORCH_INTERNAL_ASSERT(
false,
"profileReductionSize does not support data type: ",
value.tagKind());
}
// We stop profiling when it has failed
if (!pn->hasAttribute(profileFailedAttr)) {
if (!pn->hasAttribute(reductionSizeAttr)) {
pn->is_(reductionSizeAttr, size_vec);
} else {
auto profiled_ints = pn->is(reductionSizeAttr);
if (profiled_ints.size() != size_vec.size() ||
!std::equal(
profiled_ints.begin(), profiled_ints.end(), size_vec.begin())) {
TORCH_WARN_ONCE(
__FUNCTION__,
" sees varying value in profiling, ignoring and this should be handled by GUARD logic");
pn->s_(profileFailedAttr, "varying profile values");
pn->removeAttribute(reductionSizeAttr);
}
}
} else {
TORCH_INTERNAL_ASSERT(
!pn->hasAttribute(reductionSizeAttr),
"profiled attribute should have been removed when profiling is marked as failed");
}
push(stack, value);
};
pn->setCallback(ivalue_profiler);
}
void profileViewSize(ProfilingRecord* pr, Node* node, size_t offset) {
auto pn = insertProfileIValueOp(node, offset, pr);
const auto ivalue_profiler = [pr, pn](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// TODO: we don't care about merging multiple profiling runs as we don't
// support it at all;
int64_t frame_id = 0;
pop(stack, frame_id);
IValue value;
pop(stack, value);
TORCH_INTERNAL_ASSERT(
value.isIntList(), "profiling seeing the wrong data type");
if (!pn->hasAttribute(profileFailedAttr)) {
if (!pn->hasAttribute(viewSizeAttr)) {
pn->is_(viewSizeAttr, value.toIntVector());
} else {
auto profiled_ints = pn->is(viewSizeAttr);
auto input_ints = value.toIntList();
if (profiled_ints.size() != input_ints.size() ||
!std::equal(
profiled_ints.begin(),
profiled_ints.end(),
input_ints.begin())) {
TORCH_WARN_ONCE(
__FUNCTION__,
" sees varying value in profiling, ignoring and this should be handled by GUARD logic");
pn->s_(profileFailedAttr, "varying profile values");
pn->removeAttribute(viewSizeAttr);
}
}
} else {
TORCH_INTERNAL_ASSERT(
!pn->hasAttribute(viewSizeAttr),
"profiled attribute should have been removed when profiling is marked as failed");
}
push(stack, value);
};
pn->setCallback(ivalue_profiler);
}
void profileIntList(ProfilingRecord* pr, Node* node, size_t offset) {
auto pn = insertProfileIValueOp(node, offset, pr);
const auto ivalue_profiler = [pr, pn](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// TODO: we don't care about merging multiple profiling runs as we don't
// support it at all;
int64_t frame_id = 0;
pop(stack, frame_id);
IValue value;
pop(stack, value);
TORCH_INTERNAL_ASSERT(
value.isIntList(), "profiling seeing the wrong data type");
if (!pn->hasAttribute(profileFailedAttr)) {
if (!pn->hasAttribute(intListAttr)) {
pn->is_(intListAttr, value.toIntVector());
} else {
auto profiled_ints = pn->is(intListAttr);
auto input_ints = value.toIntList();
if (profiled_ints.size() != input_ints.size() ||
!std::equal(
profiled_ints.begin(),
profiled_ints.end(),
input_ints.begin())) {
TORCH_WARN_ONCE(
__FUNCTION__,
" sees varying value in profiling, ignoring and this should be handled by GUARD logic");
pn->s_(profileFailedAttr, "varying profile values");
pn->removeAttribute(intListAttr);
}
}
} else {
TORCH_INTERNAL_ASSERT(
!pn->hasAttribute(intListAttr),
"profiled attribute should have been removed when profiling is marked as failed");
}
push(stack, value);
};
pn->setCallback(ivalue_profiler);
}
void profileString(ProfilingRecord* pr, Node* node, size_t offset) {
auto pn = insertProfileIValueOp(node, offset, pr);
const auto ivalue_profiler = [pr, pn](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// TODO: we don't care about merging multiple profiling runs as we don't
// support it at all;
int64_t frame_id = 0;
pop(stack, frame_id);
IValue value;
pop(stack, value);
TORCH_INTERNAL_ASSERT(
value.isString(), "profiling seeing the wrong data type");
if (!pn->hasAttribute(profileFailedAttr)) {
if (!pn->hasAttribute(strAttr)) {
pn->s_(strAttr, value.toStringRef());
} else {
const auto& profiled_str = pn->s(strAttr);
const auto& input_str = value.toStringRef();
if (input_str != profiled_str) {
TORCH_WARN_ONCE(
__FUNCTION__,
" sees varying value in profiling, ignoring and this should be handled by GUARD logic");
pn->s_(profileFailedAttr, "varying profile values");
pn->removeAttribute(strAttr);
}
}
} else {
TORCH_INTERNAL_ASSERT(
!pn->hasAttribute(strAttr),
"profiled attribute should have been removed when profiling is marked as failed");
}
push(stack, value);
};
pn->setCallback(ivalue_profiler);
}
void profileBool(ProfilingRecord* pr, Node* node, size_t offset) {
auto pn = insertProfileIValueOp(node, offset, pr);
const auto ivalue_profiler = [pr, pn](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// TODO: we don't care about merging multiple profiling runs as we don't
// support it at all;
int64_t frame_id = 0;
pop(stack, frame_id);
IValue value;
pop(stack, value);
TORCH_INTERNAL_ASSERT(
value.isBool(), "profiling seeing the wrong data type");
if (!pn->hasAttribute(profileFailedAttr)) {
if (!pn->hasAttribute(boolAttr)) {
pn->i_(boolAttr, value.toBool());
} else {
auto profiled_bool = pn->i(boolAttr);
auto input_bool = value.toBool();
if (input_bool != profiled_bool) {
TORCH_WARN_ONCE(
__FUNCTION__,
" sees varying value in profiling, ignoring and this should be handled by GUARD logic");
pn->s_(profileFailedAttr, "varying profile values");
pn->removeAttribute(boolAttr);
}
}
} else {
TORCH_INTERNAL_ASSERT(
!pn->hasAttribute(boolAttr),
"profiled attribute should have been removed when profiling is marked as failed");
}
push(stack, value);
};
pn->setCallback(ivalue_profiler);
}
void profileInt(ProfilingRecord* pr, Node* node, size_t offset) {
auto pn = insertProfileIValueOp(node, offset, pr);
const auto ivalue_profiler = [pr, pn](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// TODO: we don't care about merging multiple profiling runs as we don't
// support it at all;
int64_t frame_id = 0;
pop(stack, frame_id);
IValue value;
pop(stack, value);
TORCH_INTERNAL_ASSERT(
value.isInt(), "profiling seeing the wrong data type");
if (!pn->hasAttribute(profileFailedAttr)) {
if (!pn->hasAttribute(intAttr)) {
pn->i_(intAttr, value.toInt());
} else {
auto profiled_int = pn->i(intAttr);
auto input_int = value.toInt();
if (input_int != profiled_int) {
TORCH_WARN_ONCE(
__FUNCTION__,
" sees varying value in profiling, ignoring and this should be handled by GUARD logic");
pn->s_(profileFailedAttr, "varying profile values");
pn->removeAttribute(intAttr);
}
}
} else {
TORCH_INTERNAL_ASSERT(
!pn->hasAttribute(intAttr),
"profiled attribute should have been removed when profiling is marked as failed");
}
push(stack, value);
};
pn->setCallback(ivalue_profiler);
}
// profile ivalue, used for optional arguments
void profileIval(ProfilingRecord* pr, Node* node, size_t offset) {
auto pn = insertProfileIValueOp(node, offset, pr);
const auto ivalue_profiler = [pr, pn](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// TODO: we don't care about merging multiple profiling runs as we don't
// support it at all;
int64_t frame_id = 0;
pop(stack, frame_id);
IValue value;
pop(stack, value);
if (!pn->hasAttribute(profileFailedAttr)) {
if (!pn->hasAttribute(ivalAttr)) {
pn->ival_(ivalAttr, value);
} else {
auto profiled_ival = pn->ival(ivalAttr);
if (value != profiled_ival) {
TORCH_WARN_ONCE(
__FUNCTION__,
" sees varying value in profiling, ignoring and this should be handled by GUARD logic");
pn->s_(profileFailedAttr, "varying profile values");
pn->removeAttribute(ivalAttr);
}
}
} else {
TORCH_INTERNAL_ASSERT(
!pn->hasAttribute(ivalAttr),
"profiled attribute should have been removed when profiling is marked as failed");
}
push(stack, value);
};
pn->setCallback(ivalue_profiler);
}
void profileBoolList(ProfilingRecord* pr, Node* node, size_t offset) {
auto pn = insertProfileIValueOp(node, offset, pr);
const auto ivalue_profiler = [pr, pn](Stack& stack) {
std::lock_guard<std::mutex> lock(pr->mutex_);
// TODO: we don't care about merging multiple profiling runs as we don't
// support it at all;
int64_t frame_id = 0;
pop(stack, frame_id);
IValue value;
pop(stack, value);
TORCH_INTERNAL_ASSERT(
value.isBoolList(), "profiling seeing the wrong data type");
if (!pn->hasAttribute(profileFailedAttr)) {
if (!pn->hasAttribute(boolListAttr)) {
auto list = value.toBoolList();
std::vector<int64_t> val(list.begin(), list.end());
pn->is_(boolListAttr, val);
} else {
auto profiled_ints = pn->is(boolListAttr);
auto input_bools = value.toBoolList();
if (profiled_ints.size() != input_bools.size() ||
!std::equal(
input_bools.begin(),
input_bools.end(),
profiled_ints.begin())) {
TORCH_WARN_ONCE(
__FUNCTION__,
" sees varying value in profiling, ignoring and this should be handled by GUARD logic");
pn->s_(profileFailedAttr, "varying profile values");
pn->removeAttribute(boolListAttr);
}
}
} else {
TORCH_INTERNAL_ASSERT(
!pn->hasAttribute(boolListAttr),
"profiled attribute should have been removed when profiling is marked as failed");
}
push(stack, value);
};
pn->setCallback(ivalue_profiler);
}
bool anyInBlock(
const Block* block,
const std::function<bool(const Node*)>& fn) {
for (auto node : block->nodes()) {
if (fn(node)) {
return true;
}
for (auto block : node->blocks()) {
if (anyInBlock(block, fn)) {
return true;
}
}
}
return false;
}
} // namespace
bool hasReductionNode(const Block* block) {
return anyInBlock(block, isReductionNode);
}
bool isReductionNode(const Node* node) {
return IrParser::isReductionNode(node);
}
bool isReductionToSizeNode(const Node* node) {
return IrParser::isReductionToSizeNode(node);
}
bool hasNormalizationNode(const Block* block) {
return anyInBlock(block, isNormalizationNode);
}
bool isNormalizationNode(const Node* node) {
return IrParser::isNormalizationNode(node);
}
bool isElementWiseNode(const Node* node) {
return IrParser::isElementWiseNode(node);
}
bool isNodeParsible(const Node* node) {
return IrParser::canParseNode(node);
}
bool shouldProfileNode(const Node* node) {
return IrParser::lookupInSymbolSet(node);
}
bool skipNodeKind(const std::string& symbol_str, bool flip) {
return IrParser::querySkipSymbolSet(
c10::Symbol::fromQualString(symbol_str), flip);
}
bool insertProfileIValue(ProfilingRecord* pr, Node* node, size_t offset) {
// is skip constant necessary?
if (node->input(offset)->node()->kind() == prim::Constant) {
return false;
}
static auto dropout_schema =
getOperatorForLiteral(
"aten::dropout(Tensor input, float p, bool train) -> Tensor")
->schema();
static auto native_dropout_schema =
getOperatorForLiteral(
"aten::native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)")
->schema();
if (node->matches(dropout_schema) || node->matches(native_dropout_schema)) {
switch (offset) {
// argument 2: Is training?
case 2:
profileBool(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto amax_schema =
getOperatorForLiteral(
"aten::amax(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor")
->schema();
static auto amin_schema =
getOperatorForLiteral(
"aten::amin(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor")
->schema();
if (node->matches(amax_schema) || node->matches(amin_schema)) {
switch (offset) {
// argument 1: reduction axes;
case 1:
profileIntList(pr, node, offset);
break;
// argument 2: keepdim;
case 2:
profileBool(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto reduction_operator_schema =
getOperatorForLiteral(
"aten::sum.dim_IntList(Tensor self, int[1]? dim, bool keepdim=False, *, int? dtype=None) -> (Tensor)")
->schema();
if (node->matches(reduction_operator_schema)) {
switch (offset) {
// argument 1: reduction axes;
case 1:
profileIntList(pr, node, offset);
break;
// argument 2: keepdim;
case 2:
profileBool(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto sum_to_size_schema =
getOperatorForLiteral(
"aten::sum_to_size(Tensor self, int[] size) -> Tensor")
->schema();
static auto grad_sum_to_size_schema =
getOperatorForLiteral(
"aten::_grad_sum_to_size(Tensor(a) self, int[]? size) -> Tensor(a)")
->schema();
if (node->matches(sum_to_size_schema) ||
node->matches(grad_sum_to_size_schema)) {
switch (offset) {
// argument 1: reduction sizes;
case 1:
// TODO(profile_size): double check optional[size]?
profileReductionSize(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto reshape_schema =
getOperatorForLiteral("aten::reshape(Tensor self, int[] shape) -> Tensor")
->schema();
static auto reshape_copy_schema =
getOperatorForLiteral(
"prim::reshape_copy(Tensor self, int[] shape) -> Tensor")
->schema();
static auto view_schema =
getOperatorForLiteral("aten::view(Tensor self, int[] size) -> Tensor")
->schema();
static auto view_copy_schema =
getOperatorForLiteral(
"prim::view_copy(Tensor self, int[] size) -> Tensor")
->schema();
if (node->matches(reshape_schema) || node->matches(reshape_copy_schema) ||
node->matches(view_schema) || node->matches(view_copy_schema)) {
switch (offset) {
// argument 1: new tensor size;
case 1:
profileViewSize(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto flatten_schema1 =
getOperatorForLiteral(
"aten::flatten.using_ints(Tensor self, int start_dim=0, int end_dim=-1) -> Tensor")
->schema();
static auto flatten_schema2 =
getOperatorForLiteral(
"prim::flatten_copy(Tensor self, int start_dim, int end_dim) -> Tensor")
->schema();
if (node->matches(flatten_schema1) || node->matches(flatten_schema2)) {
switch (offset) {
// argument 1: start_dim;
// argument 2: end_dim;
case 1:
case 2:
profileInt(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto squeeze_dim_schema =
getOperatorForLiteral(
"prim::squeeze_copy.dim(Tensor self, int dim) -> Tensor")
->schema();
static auto unsqueeze_schema =
getOperatorForLiteral(
"prim::unsqueeze_copy(Tensor self, int dim) -> Tensor")
->schema();
if (node->matches(squeeze_dim_schema) || node->matches(unsqueeze_schema)) {
switch (offset) {
// argument 1: unsqueeze dim;
case 1:
profileInt(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto batch_norm_impl_index_schema =
getOperatorForLiteral(
"aten::_batch_norm_impl_index(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> (Tensor, Tensor, Tensor, Tensor, int)")
->schema();
static auto native_batch_norm_schema =
getOperatorForLiteral(
"aten::native_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)")
->schema();
static auto batch_norm_schema =
getOperatorForLiteral(
"aten::batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor")
->schema();
static auto instance_norm_schema =
getOperatorForLiteral(
"aten::instance_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool use_input_stats, float momentum, float eps, bool cudnn_enabled) -> Tensor")
->schema();
if (node->matches(native_batch_norm_schema) ||
node->matches(batch_norm_impl_index_schema) ||
node->matches(batch_norm_schema) || node->matches(instance_norm_schema)) {
switch (offset) {
// argument 5: training;
case 5:
profileBool(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto gelu_schema =
getOperatorForLiteral(
"aten::gelu(Tensor self, *, str approximate='none') -> Tensor")
->schema();
if (node->matches(gelu_schema)) {
switch (offset) {
// argument 1: approximate;
case 1:
profileString(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto gelu_backward_schema =
getOperatorForLiteral(
"aten::gelu_backward(Tensor grad_output, Tensor self, *, str approximate='none') -> Tensor")
->schema();
if (node->matches(gelu_backward_schema)) {
switch (offset) {
// argument 2: approximate;
case 2:
profileString(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto native_layer_norm_schema =
getOperatorForLiteral(
"aten::native_layer_norm(Tensor input, int[] normalized_shape, Tensor? weight, Tensor? bias, float eps) -> (Tensor, Tensor, Tensor)")
->schema();
static auto layer_norm_schema =
getOperatorForLiteral(
"aten::layer_norm(Tensor input, int[] normalized_shape, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enable=True) -> Tensor")
->schema();
if (node->matches(native_layer_norm_schema) ||
node->matches(layer_norm_schema)) {
switch (offset) {
case 1:
profileIntList(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto batch_norm_impl_index_backward_schema =
getOperatorForLiteral(
"aten::_batch_norm_impl_index_backward(int impl_index, Tensor input, Tensor grad_output, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var_transform, bool train, float eps, bool[3] output_mask, Tensor reservedSpace) -> (Tensor, Tensor, Tensor)")
->schema();
if (node->matches(batch_norm_impl_index_backward_schema)) {
switch (offset) {
// TODO: guard impl_index, but I think that's not needed;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
case 8: // argument 8: training;
profileBool(pr, node, offset);
break;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
case 10:
profileBoolList(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto batch_norm_backward_schema =
getOperatorForLiteral(
"aten::native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor)")
->schema();
if (node->matches(batch_norm_backward_schema)) {
switch (offset) {
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
case 7: // argument 8: training;
profileBool(pr, node, offset);
break;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
case 9:
profileBoolList(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto native_layer_norm_backward_schema =
getOperatorForLiteral(
"aten::native_layer_norm_backward(Tensor grad_out, Tensor input, int[] normalized_shape, Tensor mean, Tensor rstd, Tensor? weight, Tensor? bias, bool[3] output_mask) -> (Tensor, Tensor, Tensor)")
->schema();
if (node->matches(native_layer_norm_backward_schema)) {
switch (offset) {
case 2:
profileIntList(pr, node, offset);
break;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
case 7:
profileBoolList(pr, node, offset);
break;
default:
return false;
}
return true;
}
static auto to_copy_schema =
getOperatorForLiteral(
"aten::_to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor")
->schema();
if (node->matches(to_copy_schema)) {
switch (offset) {
case 1:
profileInt(pr, node, offset);
return true;
default:
return false;
}
}
static auto to_dtype_schema =
getOperatorForLiteral(
"aten::to.dtype(Tensor self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor")
->schema();
if (node->matches(to_dtype_schema)) {
switch (offset) {
case 1:
profileInt(pr, node, offset);
return true;
default:
return false;
}
}
static auto log_softmax_data_schema =
getOperatorForLiteral(
"aten::log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor")
->schema();
static auto softmax_data_schema =
getOperatorForLiteral(
"aten::softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor")
->schema();
if (node->matches(log_softmax_data_schema) ||
node->matches(softmax_data_schema)) {
switch (offset) {
case 2:
profileIval(pr, node, offset);
return true;
default:
return false;
}
}
static auto log_softmax_backward_data_schema =
getOperatorForLiteral(
"aten::_log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor")
->schema();
static auto softmax_backward_data_schema =
getOperatorForLiteral(
"aten::_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor")
->schema();
if (node->matches(log_softmax_backward_data_schema) ||
node->matches(softmax_backward_data_schema)) {
switch (offset) {
case 2:
profileInt(pr, node, offset);
return true;
case 3:
profileInt(pr, node, offset);
return true;
default:
return false;
}
}
return false;
}
void insertProfileNodesForCUDAFuser_(Block* block, ProfilingRecord* pr) {
for (const auto& n : block->nodes()) {
for (const auto offset : c10::irange(n->inputs().size())) {
insertProfileIValue(pr, n, offset);
}
for (auto ib : n->blocks()) {
insertProfileNodesForCUDAFuser_(ib, pr);
}
}
}
void InsertProfileNodes(ProfilingRecord* pr) {
insertProfileNodesForCUDAFuser_(pr->profiled_graph_->block(), pr);
}
std::unique_ptr<Fusion> parseJitIR(const std::shared_ptr<Graph>& graph) {
FUSER_PERF_SCOPE("parseJitIR");
IrParser parser(graph);
return parser.parse();
}
} // namespace cuda
} // namespace fuser
} // namespace jit
} // namespace torch
|