File size: 126,740 Bytes
f614769 | 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 | # Copyright (C) 2022-3 Intel Corporation
# SPDX-License-Identifier: MIT License
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Iterable
from contextlib import ExitStack, nullcontext
from pathlib import Path
from typing import Any, Callable, ContextManager, Dict, List, Optional, Type, Union
from warnings import warn
import pytorch_lightning as pl
import torch
import torchmetrics
from einops import reduce
from matsciml.common import package_registry
from matsciml.common.registry import registry
from matsciml.common.types import AbstractGraph, BatchDict, DataDict, Embeddings
from matsciml.models.common import OutputHead
from matsciml.modules.normalizer import Normalizer
from torch import Tensor, nn
from torch.optim import AdamW, Optimizer, lr_scheduler
if package_registry["dgl"]:
import dgl
if package_registry["pyg"]:
import torch_geometric as pyg
__all__ = [
"AbstractEnergyModel",
"ScalarRegressionTask",
"BinaryClassificationTask",
"ForceRegressionTask",
"CrystalSymmetryClassificationTask",
"MultiTaskLitModule",
"OpenCatalystInference",
"IS2REInference",
"S2EFInference",
]
"""
base.py
This module implements all the base classes for task and model
abstraction.
The way models and tasks are meant to be composed is as follows:
An abstract GNN architecture inherits from either `AbstractS2EFModel`
or `AbstractIS2REModel`: this abstracts out things like force computation
in the former, where the `forward` pass computes the energy, and the
class implements the `compute_force` method that uses autograd for
the force.
The GNN model is then passed as "the model" within a PyTorch Lightning
Module, which takes care of all the loss computation, normalization,
logging, and CPU/GPU/TPU transfers.
"""
def decorate_color(color: str):
"""This creates a logging function with flair"""
def debug_message(logger, message: str) -> None:
logger.debug(f"\033{color} {message}\033[00m")
return debug_message
# set up different colors for logging
debug_green = decorate_color("[92m")
debug_lightpurple = decorate_color("[94m")
debug_cyan = decorate_color("[96m")
def dynamic_gradients_context(need_grad: bool, has_rnn: bool) -> ContextManager:
"""
Conditional gradient context manager, based on whether or not
force computation is necessary in the process.
This is necessary because there are actually two contexts
necessary: enable gradient computation _and_ make sure we
aren't in inference mode, which is enabled by PyTorch Lightning
for faster inference.
If this is `regress_forces` is set to False, a `nullcontext`
is applied that does nothing.
Parameters
----------
need_grad : bool
Flag to designate whether or not gradients need to be forced
within this code block.
has_rnn : bool
Flag to indicate whether or not RNNs are being used in this
model, which will disable cudnn to enable double backprop.
Returns
-------
ContextManager
Joint context, combining `inference_mode` and `enable_grad`,
otherwise a `nullcontext` if `need_grad` is `False`.
"""
manager = ExitStack()
if need_grad:
contexts = [torch.inference_mode(False), torch.enable_grad()]
# if we're also using CUDA, there is an additional context to allow
# RNNs to do double backprop
if torch.cuda.is_available() and has_rnn:
contexts.append(torch.backends.cudnn.flags(enabled=False))
for cxt in contexts:
manager.enter_context(cxt)
else:
manager.enter_context(nullcontext())
return manager
def rnn_force_train_mode(module: nn.Module) -> None:
"""
Forces RNN subclasses into training mode to facilitate
derivatives for force computation outside of training
steps.
See https://docs.nvidia.com/deeplearning/cudnn/api/index.html#cudnnRNNForward
Parameters
----------
module : nn.Module
Abstract `torch.nn.Module` to check and toggle
"""
# this try/except will catch non-CUDA enabled systems
# this patch is only for cudnn
try:
_ = torch.cuda.current_device()
if isinstance(module, nn.RNNBase):
module.train()
except AssertionError:
pass
def lit_conditional_grad(regress_forces: bool):
"""
Decorator function that will dynamically enable gradient
computation. An example usage for this decorator is given in
the `S2EFLitModule.forward` call, where we determine at
runtime whether or not to enable gradients for the force
computation by wrapping the embedded `gnn.forward` method.
Parameters
----------
regress_forces : bool
Specifies whether or not to regress forces; if so,
enable gradient computation.
"""
def decorator(func):
def cls_method(self, *args, **kwargs):
f = func
if regress_forces:
f = torch.enable_grad()(func)
return f(self, *args, **kwargs)
return cls_method
return decorator
def prepend_affix(metrics: dict[str, torch.Tensor], affix: str) -> None:
"""
Mutate a dictionary in place, prepending an affix to keys.
This is primarily for logging metrics, where we want to denote something
originating from train/test/validation, etc.
Parameters
----------
metrics : Dict[str, torch.Tensor]
Dictionary containing metrics
affix : str
Affix to prepend each key, for example "train" for training metrics.
"""
keys = list(metrics.keys())
for key in keys:
metrics[f"{affix}.{key}"] = metrics[key]
del metrics[key]
class BaseModel(nn.Module):
def __init__(self, num_atoms=None, bond_feat_dim=None, num_targets=None):
super().__init__()
self.num_atoms = num_atoms
self.bond_feat_dim = bond_feat_dim
self.num_targets = num_targets
def forward(self, data):
raise NotImplementedError
@property
def num_params(self):
return sum(p.numel() for p in self.parameters())
class AbstractTask(ABC, pl.LightningModule):
# TODO the intention is for this class to supersede AbstractEnergyModel for DGL
def __init__(
self,
atom_embedding_dim: int,
num_atom_embedding: int = 100,
embedding_kwargs: dict[str, Any] = {},
encoder_only: bool = True,
) -> None:
super().__init__()
embedding_kwargs.setdefault("padding_idx", 0)
self.atom_embedding = nn.Embedding(
num_atom_embedding,
atom_embedding_dim,
**embedding_kwargs,
)
self.save_hyperparameters()
@property
def num_params(self) -> int:
return sum(p.numel() for p in self.parameters())
@property
def has_rnn(self) -> bool:
"""
Returns True if any components of this model contains an RNN unit that
inherits from 'nn.RNNBase'.
"""
return any([isinstance(block, nn.RNNBase) for block in self.modules()])
@abstractmethod
def read_batch(self, batch: BatchDict) -> DataDict:
"""
This method must be implemented by subclasses to extract
input data out of a batch and into a dictionary format ready
to be ingested by the actual model.
Parameters
----------
batch : BatchDict
Batch of input data to be read
Returns
-------
DataDict
Dictionary containing input data, i.e. graphs and other
tensor structures to be passed into the model
"""
...
@abstractmethod
def read_batch_size(self, batch: BatchDict) -> int | None: ...
@abstractmethod
def _forward(self, *args, **kwargs) -> Embeddings:
"""
Implements the actual logic of the architecture. Given a set
of input features, produce outputs/predictions from the model.
Returns
-------
Embeddings
Data structure containing system/graph and point/node level embeddings.
"""
...
def forward(self, batch: BatchDict) -> Embeddings:
"""
Given a batch structure, extract out data and pass it into the
neural network architecture. This implements the 'forward' method
as expected of all children of 'nn.Module'; it is not intended to
be overridden, instead modify the 'read_batch' and '_forward' methods
to change how this model/class of models interact with data.
Parameters
----------
batch : BatchDict
Batch of data to process
Returns
-------
Embeddings
Data structure containing system/graph and point/node level embeddings.
"""
input_data = self.read_batch(batch)
outputs = self._forward(**input_data)
# raise an error to help spot models that have not yet been refactored
if not isinstance(outputs, Embeddings):
raise ValueError(
"Encoder did not return `Embeddings` data structure: please refactor your model!",
)
return outputs
class AbstractPointCloudModel(AbstractTask):
def read_batch(self, batch: BatchDict) -> DataDict:
r"""
Extract data needed for point cloud modeling from a batch.
Notably, to facilitate force calculation, the point cloud
"neighborhood" for atom positions is constructed **after**
giving the primary task (i.e. ``ForceRegressionTask``) an
opportunity to enable gradients for each sample within the point cloud.
To clarify usage of ``pos`` and ``pc_pos``, the former represents
the packed batch of positions without separating them into their
individual point clouds: **this is used for force computation**
where we want to end up with a force tensor with the same shape.
``pc_pos`` corresponds to the padded, molecule centered point
cloud data that should be used as input to a point cloud model.
Parameters
----------
batch : BatchDict
Batch of samples to process
Returns
-------
DataDict
Input data for a point cloud model to process, notably
including particle positions and features
"""
from matsciml.datasets.utils import pad_point_cloud
assert isinstance(
batch["pos"],
torch.Tensor,
), "Expect 'pos' data to be a packed tensor of shape [N, 3]"
data = {key: batch.get(key) for key in ["pc_features", "pos"]}
# split the stacked positions into each individual point cloud
temp_pos = batch["pos"].split(batch["sizes"])
pc_pos = []
# sizes records the number of centers being used
sizes = []
# loop over each sample within a batch
for index, sample in enumerate(temp_pos):
src_nodes, dst_nodes = batch["src_nodes"][index], batch["dst_nodes"][index]
# use dst_nodes to gauge size because you will always have more
# dst nodes than src nodes right now
sizes.append(len(dst_nodes))
# carve out neighborhoods as dictated by the dataset/transform definition
sample_pc_pos = sample[src_nodes][None, :] - sample[dst_nodes][:, None]
pc_pos.append(sample_pc_pos)
# pad the position result
pc_pos, mask = pad_point_cloud(pc_pos, max(sizes))
# get the features and make sure the shapes are consistent for the
# batch and neighborhood
feat_shape = data.get("pc_features").shape
assert (
pc_pos.shape[:-1] == feat_shape[:-1]
), "Shape of point cloud neighborhood positions is different from features!"
data["pc_pos"] = pc_pos
data["mask"] = mask
data["sizes"] = sizes
return data
@abstractmethod
def _forward(
self,
pc_pos: torch.Tensor,
pc_features: torch.Tensor,
mask: torch.Tensor | None = None,
sizes: list[int] | None = None,
**kwargs,
) -> Embeddings:
"""
Sets expected patterns for args for point cloud based modeling, whereby
the bare minimum expected data are 'pos' and 'pc_features' akin to graph
approaches.
Parameters
----------
pc_pos : torch.Tensor
Padded point cloud neighborhood tensor, with shape ``[B, N, M, 3]``
for ``B`` batch size and ``N`` padded size. For full pairwise point
clouds, ``N == M``.
pc_features : torch.Tensor
Padded point cloud feature tensor, with shape ``[B, N, M, D_in]``
for ``B`` batch size and ``N`` padded size. For full pairwise point
clouds, ``N == M``.
mask : Optional[torch.Tensor], optional
Boolean tensor with shape ``[B, N, M]``, by default None. If supplied
in conjuction with ``sizes``, will mask out contributions from padding
nodes.
sizes : Optional[List[int]], optional
List of integers denoting the size of the first non-batch point cloud
dimension, by default None. If supplied in conjuction with ``mask``,
will mask out contributions from padding nodes.
Returns
-------
torch.Tensor
Output of a point cloud model; system-level embedding or predictions
"""
...
@staticmethod
def mask_model_output(
result: torch.Tensor,
mask: torch.Tensor,
sizes: list[int],
extensive: bool,
) -> torch.Tensor:
r"""
Perform a masked reduction over a point cloud model output.
This effectively removes the contributions from node centers or source
particles, i.e. the first non-batch dimension, that correspond to padding nodes.
The resulting shape should be ``[B, D]`` with ``B`` batch size and ``D``
desired output dimension.
Parameters
----------
result : torch.Tensor
Result of a point cloud model, with shape ``[B, N, M, D]``
for ``B`` batch size, ``N`` padded source nodes, ``M``
padded destination nodes, and output dimension ``D``.
mask : torch.Tensor
A 3D boolean tensor of shape ``[B, N, M]``
sizes : List[int]
A list comprising the number of atom centers that are not padding
nodes.
extensive : bool
If ``True``, sums over nodes, otherwise performs a mean reduction.
Returns
-------
torch.Tensor
Per-point cloud results, with shape ``[B, D]``
"""
# extract out a mask over [B, N] for N atom centers, removing
# padded center node contributions to the system output
center_mask = mask[..., 0]
# this extracts a [N, D] tensor with N total particles, D embedding dim
unpadded_result = result[center_mask]
# this splits up into embeddings per node
split_results = unpadded_result.split(sizes)
# figure out what reduction to perform over the particles
if extensive:
reduce = torch.sum
else:
reduce = torch.mean
# should be [B, D] for B systems
output = torch.stack([reduce(t, dim=0) for t in split_results])
return output
def read_batch_size(self, batch: BatchDict) -> None:
# returns None, because batch size can be readily determined by Lightning
return None
class AbstractGraphModel(AbstractTask):
def __init__(
self,
atom_embedding_dim: int,
num_atom_embedding: int = 100,
embedding_kwargs: dict[str, Any] = {},
encoder_only: bool = True,
) -> None:
super().__init__(
atom_embedding_dim,
num_atom_embedding,
embedding_kwargs,
encoder_only,
)
def read_batch(self, batch: BatchDict) -> DataDict:
assert (
"graph" in batch
), f"Model {self.__class__.__name__} expects graph structures, but 'graph' key was not found in batch."
graph = batch.get("graph")
return {"graph": graph}
@staticmethod
def join_position_embeddings(
pos: torch.Tensor,
node_feats: torch.Tensor,
) -> torch.Tensor:
"""
This is a method for conveniently embedding both positions and node features
together. Given that not every type of model will use this approach, it is
left for concrete classes to utilize rather than being the default.
Parameters
----------
pos : torch.Tensor
2D tensor with [N, 3] containing coordinates of each node in N
node_feats : torch.Tensor
2D tensor with [N, D] containing features of each node in N. Typically
this pertains to the embedding lookup features, but up to the developer
Returns
-------
torch.Tensor
2D tensor with shape [N, D + 3]
"""
return torch.hstack([pos, node_feats])
@abstractmethod
def _forward(
self,
graph: AbstractGraph,
node_feats: torch.Tensor,
pos: torch.Tensor | None = None,
edge_feats: torch.Tensor | None = None,
graph_feats: torch.Tensor | None = None,
**kwargs,
) -> Embeddings:
"""
Sets args/kwargs for the expected components of a graph-based
model. At the bare minimum, we expect some kind of abstract
graph structure, along with tensors of atomic coordinates and
numbers to process. Optionally, models can include edge and graph
features, but is left for concrete classes to implement how
these are obtained.
Parameters
----------
graph : AbstractGraph
Graph structure implemented in a particular framework
node_feats : torch.Tensor
Atomic numbers or other featurizations, typically shape [N, ...] for N nuclei
pos : Optional[torch.Tensor]
Atom positions with shape [N, 3], by default None to make this optional
as some architectures may pass them as 'node_feats'
edge_feats : Optional[torch.Tensor], optional
Edge features to process, by default None
graph_feats : Optional[torch.Tensor], optional
Graph-level attributes/features to use, by default None
Returns
-------
torch.Tensor
Model output; either embedding or projected output
"""
...
if package_registry["dgl"]:
class AbstractDGLModel(AbstractGraphModel):
def read_batch(self, batch: BatchDict) -> DataDict:
"""
Extract DGLGraph structure and features to pass into the model.
More complicated models can override this method to extract out edge and
graph features as well.
Parameters
----------
batch : BatchDict
Batch of data to process.
Returns
-------
DataDict
Dictionary of input features to pass into the model
"""
data = super().read_batch(batch)
graph = data.get("graph")
assert isinstance(
graph,
dgl.DGLGraph,
), f"Model {self.__class__.__name__} expects DGL graphs, but data in 'graph' key is type {type(graph)}"
atomic_numbers = data["graph"].ndata["atomic_numbers"].long()
node_embeddings = self.atom_embedding(atomic_numbers)
pos = graph.ndata["pos"]
# optionally can fuse into a single tensor with `self.join_position_embeddings`
data["node_feats"] = node_embeddings
data["pos"] = pos
# these keys are left as None, but are filler for concrete models to extract
data.setdefault("edge_feats", None)
data.setdefault("graph_feats", None)
return data
def read_batch_size(self, batch: BatchDict) -> int:
# grabs the number of batch samples from the DGLGraph attribute
graph = batch["graph"]
return graph.batch_size
if package_registry["pyg"]:
class AbstractPyGModel(AbstractGraphModel):
def read_batch(self, batch: BatchDict) -> DataDict:
"""
Extract PyG structure and features to pass into the model.
More complicated models can override this method to extract out edge and
graph features as well.
Parameters
----------
batch : BatchDict
Batch of data to process.
Returns
-------
DataDict
Dictionary of input features to pass into the model
"""
data = super().read_batch(batch)
graph = data.get("graph")
assert isinstance(
graph,
(pyg.data.Data, pyg.data.Batch),
), f"Model {self.__class__.__name__} expects PyG graphs, but data in 'graph' key is type {type(graph)}"
for key in ["edge_feats", "graph_feats"]:
data[key] = getattr(graph, key, None)
atomic_numbers: torch.Tensor = getattr(graph, "atomic_numbers").to(
torch.int,
)
node_embeddings = self.atom_embedding(atomic_numbers)
pos: torch.Tensor = getattr(graph, "pos")
# optionally can fuse into a single tensor with `self.join_position_embeddings`
data["node_feats"] = node_embeddings
data["pos"] = pos
return data
def read_batch_size(self, batch: BatchDict) -> int:
graph = batch["graph"]
return graph.num_graphs
class AbstractEnergyModel(pl.LightningModule):
"""
At a minimum, the point of this is to help register associated models
with PyTorch Lightning ModelRegistry; the expectation is that you get
the graph energy as well as the atom forces.
TODO - replace this class with `AbstractTask`, see #167 and #168
"""
def __init__(self):
super().__init__()
self.save_hyperparameters()
def forward(self, graph: dgl.DGLGraph) -> Tensor:
"""
Implements the basic forward call for an S2EF task; given a graph,
predict the energy. Force computation relies on a decorated version
of this function, which is used by the `S2EFLitModule`.
Parameters
----------
graph : dgl.DGLGraph
A DGL graph object
Returns
-------
Tensor
A float Tensor containing the energy of
each graph, shape [G, 1] for G graphs
"""
energy = self.forward(graph)
return energy
@registry.register_task("BaseTaskModule")
class BaseTaskModule(pl.LightningModule):
__task__ = None
__needs_grads__ = []
def __init__(
self,
encoder: nn.Module | None = None,
encoder_class: type[nn.Module] | None = None,
encoder_kwargs: dict[str, Any] | None = None,
loss_func: type[nn.Module] | nn.Module | None = None,
task_keys: list[str] | None = None,
output_kwargs: dict[str, Any] = {},
lr: float = 1e-4,
weight_decay: float = 0.0,
embedding_reduction_type: str = "mean",
normalize_kwargs: dict[str, float] | None = None,
scheduler_kwargs: dict[str, dict[str, Any]] | None = None,
**kwargs,
) -> None:
super().__init__()
if encoder is not None:
warn(
f"Encoder object was passed directly into {self.__class__.__name__}; saved hyperparameters will be incomplete!",
)
if encoder_class is not None and encoder_kwargs:
try:
encoder = encoder_class(**encoder_kwargs)
except: # noqa: E722
raise ValueError(
f"Unable to instantiate encoder {encoder_class} with kwargs: {encoder_kwargs}.",
)
if encoder is not None:
self.encoder = encoder
else:
raise ValueError("No valid encoder passed.")
if isinstance(loss_func, type):
loss_func = loss_func()
self.loss_func = loss_func
default_heads = {"act_last": None, "hidden_dim": 128}
default_heads.update(output_kwargs)
self.output_kwargs = default_heads
self.normalize_kwargs = normalize_kwargs
self.task_keys = task_keys
if "task_loss_scaling" in kwargs:
if kwargs["task_loss_scaling"] is not None:
self.task_loss_scaling = kwargs["task_loss_scaling"]
else:
self.task_loss_scaling = dict(zip(task_keys, [1] * len(task_keys)))
self.embedding_reduction_type = embedding_reduction_type
self.save_hyperparameters(ignore=["encoder", "loss_func"])
accuracy_func = kwargs.get("accuracy_func", None)
if accuracy_func is not None:
self.accuracy_func = accuracy_func(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
)
self.accuracy_func_5 = accuracy_func(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
top_k=5,
)
self.accuracy_func_10 = accuracy_func(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
top_k=10,
)
self._precision = torchmetrics.Precision(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
)
self._precision_5 = torchmetrics.Precision(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
top_k=5,
)
self._precision_10 = torchmetrics.Precision(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
top_k=10,
)
self.recall = torchmetrics.Recall(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
)
self.recall_5 = torchmetrics.Recall(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
top_k=5,
)
self.recall_10 = torchmetrics.Recall(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
top_k=10,
)
self.f1 = torchmetrics.F1Score(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
)
self.f1_5 = torchmetrics.F1Score(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
top_k=5,
)
self.f1_10 = torchmetrics.F1Score(
task=kwargs["classification_type"],
num_classes=kwargs.get("num_classes", None),
top_k=10,
)
else:
self.accuracy_func = accuracy_func
@property
def task_keys(self) -> list[str]:
return self._task_keys
@task_keys.setter
def task_keys(self, values: set | list[str] | None) -> None:
"""
Ensures that the task keys are unique.
Parameters
----------
values : Union[set, List[str]]
Array of keys to use to look up targets.
"""
if values is None:
values = []
if isinstance(values, list):
values = set(values)
if isinstance(values, set):
values = list(values)
self._task_keys = values
# if we're setting task keys we have enough to initialize
# the output heads
if not self.has_initialized:
self.output_heads = self._make_output_heads()
self.normalizers = self._make_normalizers()
self.hparams["task_keys"] = self._task_keys
@property
def has_initialized(self) -> bool:
if len(self.task_keys) == 0:
return False
output_heads = getattr(self, "output_heads", None)
if output_heads is None:
return False
# basically if we've passed these two assertions, we should have
# all the heads. We can't check against self.task_keys, because
# some tasks like ForceRegressionTask doesn't actually use an output
# head for the forces
return True
@abstractmethod
def _make_output_heads(self) -> nn.ModuleDict: ...
@property
def output_heads(self) -> nn.ModuleDict:
return self._output_heads
@output_heads.setter
def output_heads(self, heads: nn.ModuleDict) -> None:
assert isinstance(
heads,
nn.ModuleDict,
), "Output heads must be an instance of `nn.ModuleDict`."
assert len(heads) > 0, f"No output heads in {heads}."
assert all(
[key in self.task_keys for key in heads.keys()],
), f"Output head keys {heads.keys()} do not match any in tasks: {self.task_keys}."
self._output_heads = heads
@property
def num_heads(self) -> int:
return len(self.task_keys)
@property
def uses_normalizers(self) -> bool:
# property determines if we normalize targets or not
norms = getattr(self, "normalizers", None)
if norms is None or self.__task__ in ["classification", "symmetry"]:
return False
return True
@property
def has_rnn(self) -> bool:
"""
Property to determine whether or not this LightningModule contains
RNNs. This is primarily to determine whether or not to enable/disable
contexts with cudnn, as double backprop is not supported.
Returns
-------
bool
True if any module is a subclass of `RNNBase`, otherwise False.
"""
return any([isinstance(module, nn.RNNBase) for module in self.modules()])
def forward(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> dict[str, torch.Tensor]:
if "embeddings" in batch:
embedding = batch.get("embeddings")
else:
embedding = self.encoder(batch)
outputs = self.process_embedding(embedding)
return outputs
def process_embedding(self, embeddings: Embeddings) -> dict[str, torch.Tensor]:
"""
Given a set of embeddings, output predictions for each head.
Parameters
----------
embeddings : torch.Tensor
Batch of graph/point cloud embeddings
Returns
-------
Dict[str, torch.Tensor]
Predictions per output head
"""
results = {}
for key, head in self.output_heads.items():
# in the event that we get multiple embeddings, we average
# every dimension execpt the batch and dimensionality
output = head(embeddings.system_embedding)
output = reduce(
output,
"b ... d -> b d",
reduction=self.embedding_reduction_type,
)
results[key] = output
return results
def _get_targets(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> dict[str, torch.Tensor]:
"""
Method for extracting targets out of a batch.
Ultimately it is up to the individual task to determine how to obtain
a dictionary of target tensors to use for loss computation, but this
implements the base logic assuming everything is neatly in the "targets"
key of a batch.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of samples from the dataset.
Returns
-------
Dict[str, torch.Tensor]
A flat dictionary containing target tensors.
"""
target_dict = {}
assert len(self.task_keys) != 0, "No target keys were set!"
for key in self.task_keys:
target_dict[key] = batch["targets"][key]
return target_dict
def _filter_task_keys(
self,
keys: list[str],
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> list[str]:
"""
Implement a mechanism for filtering out keys for targets.
The base class simply returns the keys without modification.
Parameters
----------
keys : List[str]
List of task keys
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of training samples to inspect.
Returns
-------
List[str]
List of filtered task keys
"""
return keys
def _compute_losses(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> dict[str, torch.Tensor | dict[str, torch.Tensor]]:
"""
Compute pred versus target for every target, then sum.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of samples to evaluate on.
embeddings : Optional[torch.Tensor]
If provided, bypasses calling the encoder and obtains predictions
from processing the embeddings. Mainly intended for use with multitask
abstraction.
Returns
-------
Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]
Dictionary containing the joint loss, and a subdictionary
containing each individual target loss.
"""
# targets = self._get_targets(batch)
# predictions = self(batch)
# losses = {}
# for key in self.task_keys:
# target_val = targets[key]
# if self.uses_normalizers:
# target_val = self.normalizers[key].norm(target_val)
# losses[key] = self.loss_func(predictions[key], target_val)
# total_loss: torch.Tensor = sum(losses.values())
# return {"loss": total_loss, "log": losses}
targets = self._get_targets(batch)
predictions = self(batch)
losses = {}
accuracies = {}
precisions = {}
recalls = {}
f1s = {}
for key in self.task_keys:
target_val = targets[key]
if self.uses_normalizers:
target_val = self.normalizers[key].norm(target_val)
# if predictions[key].shape[-1] >1:
# preds = torch.argmax(predictions[key], axis=1)
# else:
preds = predictions[key]
if self.accuracy_func is not None:
accuracies[key] = self.accuracy_func(preds, target_val)
accuracies[f"{key}_5"] = self.accuracy_func_5(preds, target_val)
accuracies[f"{key}_10"] = self.accuracy_func_10(preds, target_val)
precisions[key] = self._precision(preds, target_val)
precisions[f"{key}_5"] = self._precision_5(preds, target_val)
precisions[f"{key}_10"] = self._precision_10(preds, target_val)
recalls[key] = self.recall(preds, target_val)
recalls[f"{key}_5"] = self.recall_5(preds, target_val)
recalls[f"{key}_10"] = self.recall_10(preds, target_val)
f1s[key] = self.f1(preds, target_val)
f1s[f"{key}_5"] = self.f1_5(preds, target_val)
f1s[f"{key}_10"] = self.f1_10(preds, target_val)
loss = self.loss_func(predictions[key], target_val)
loss = loss * self.task_loss_scaling[key]
losses[key] = loss
total_loss: torch.Tensor = sum(losses.values())
total_accuracy: torch.Tensor = sum(accuracies.values())
log_dict = {}
for k, v in losses.items():
log_dict[f"{k}"] = v
for k, v in accuracies.items():
log_dict[f"{k}_acc"] = v
for k, v in precisions.items():
log_dict[f"{k}_precision"] = v
for k, v in recalls.items():
log_dict[f"{k}_recall"] = v
for k, v in f1s.items():
log_dict[f"{k}_f1s"] = v
return {
"loss": total_loss,
"log": log_dict,
"acc": total_accuracy,
}
def configure_optimizers(self) -> torch.optim.AdamW:
opt = torch.optim.AdamW(
self.parameters(),
lr=self.hparams.lr,
weight_decay=self.hparams.weight_decay,
)
# configure schedulers as a nested dictionary
schedule_dict = getattr(self.hparams, "scheduler_kwargs", None)
schedulers = []
if schedule_dict:
for scheduler_name, params in schedule_dict.items():
# try get the scheduler class
scheduler_class = getattr(lr_scheduler, scheduler_name, None)
if not scheduler_class:
raise NameError(
f"{scheduler_class} was requested for LR scheduling, but is not in 'torch.optim.lr_scheduler'.",
)
scheduler = scheduler_class(opt, **params)
schedulers.append(scheduler)
return [opt], schedulers
def training_step(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
batch_idx: int,
):
loss_dict = self._compute_losses(batch)
metrics = {}
# prepending training flag for
for key, value in loss_dict["log"].items():
metrics[f"train_{key}"] = value
try:
batch_size = self.encoder.read_batch_size(batch)
except: # noqa: E722
warn(
"Unable to parse batch size from data, defaulting to `None` for logging.",
)
batch_size = None
self.log_dict(metrics, on_step=True, prog_bar=True, batch_size=batch_size)
return loss_dict
def validation_step(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
batch_idx: int,
):
loss_dict = self._compute_losses(batch)
metrics = {}
# prepending training flag for
for key, value in loss_dict["log"].items():
metrics[f"val_{key}"] = value
try:
batch_size = self.encoder.read_batch_size(batch)
except: # noqa: E722
warn(
"Unable to parse batch size from data, defaulting to `None` for logging.",
)
batch_size = None
self.log_dict(metrics, batch_size=batch_size, sync_dist=True)
return loss_dict
def test_step(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
batch_idx: int,
):
loss_dict = self._compute_losses(batch)
metrics = {}
# prepending training flag for
for key, value in loss_dict["log"].items():
metrics[f"test_{key}"] = value
try:
batch_size = self.encoder.read_batch_size(batch)
except: # noqa: E722
warn(
"Unable to parse batch size from data, defaulting to `None` for logging.",
)
batch_size = None
self.log_dict(metrics, batch_size=batch_size, sync_dist=True)
return loss_dict
def _make_normalizers(self) -> dict[str, Normalizer]:
"""
Instantiate a set of normalizers for targets associated with this task.
Assumes that task keys has been set correctly, and the default behavior
will use normalizers with a mean and standard deviation of zero and one.
Returns
-------
Dict[str, Normalizer]
Normalizers for each target
"""
if self.normalize_kwargs is not None:
norm_kwargs = self.normalize_kwargs
else:
norm_kwargs = {}
normalizers = {}
for key in self.task_keys:
mean = norm_kwargs.get(f"{key}_mean", 0.0)
std = norm_kwargs.get(f"{key}_std", 1.0)
normalizers[key] = Normalizer(mean=mean, std=std, device=self.device)
return normalizers
def predict(self, batch: BatchDict) -> dict[str, torch.Tensor]:
"""
Implements what is effectively the 'inference' logic of the task,
where run the forward pass on a batch of samples, and if normalizers
were used for training, we also apply the inverse operation to get
values in the right scale.
Not to be confused with `predict_step`, which is used by Lightning as
part of the prediction workflow. Since there is no one-size-fits-all
inference workflow we can define, this provides a convenient function
for users to call as a replacement.
Parameters
----------
batch : BatchDict
Batch of samples to pass to the model.
Returns
-------
dict[str, torch.Tensor]
Output dictionary as provided by the forward pass, but if
normalizers are available for a given task, we apply the
inverse norm on the value.
"""
# use EMA weights instead if they are available
if hasattr(self, "ema_module"):
wrapper = self.ema_module
else:
wrapper = self
outputs = wrapper(batch)
if self.uses_normalizers:
for key in self.task_keys:
if key in self.normalizers:
# apply the inverse transform if provided
outputs[key] = self.normalizers[key].denorm(outputs[key])
return outputs
@classmethod
def from_pretrained_encoder(cls, task_ckpt_path: str | Path, **kwargs):
"""
Attempts to instantiate a new task, adopting a previously trained encoder model.
This function will load in a saved PyTorch Lightning checkpoint,
copy over the hyperparameters needed to reconstruct the encoder,
and simply maps the encoder ``state_dict`` to the new instance.
``Kwargs`` are passed directly into the creation of the task, and so can
be thought of as just a task through the typical interface normally.
Parameters
----------
task_ckpt_path : Union[str, Path]
Path to an existing task checkpoint file. Typically, this
would be a PyTorch Lightning checkpoint.
Examples
--------
1. Create a new task simply from training another one
>>> new_task = ScalarRegressionTask.from_pretrained_encoder(
"epoch=10-step=100.ckpt"
)
2. Create a new task, modifying output heads
>>> new_taks = ForceRegressionTask.from_pretrained_encoder(
"epoch=5-step=12516.ckpt",
output_kwargs={
"num_hidden": 3,
"activation": "nn.ReLU"
}
)
"""
if isinstance(task_ckpt_path, str):
task_ckpt_path = Path(task_ckpt_path)
assert (
task_ckpt_path.exists()
), "Encoder checkpoint filepath specified but does not exist."
ckpt = torch.load(task_ckpt_path)
for key in ["encoder_class", "encoder_kwargs"]:
assert (
key in ckpt["hyper_parameters"]
), f"{key} expected to be in hyperparameters, but was not found."
# copy over the data for the new task
kwargs[key] = ckpt["hyper_parameters"][key]
# construct the new task with random weights
task = cls(**kwargs)
# this only copies over encoder weights, and removes the 'encoder.'
# pattern from keys
encoder_weights = {
key.replace("encoder.", ""): tensor
for key, tensor in ckpt["state_dict"].items()
if "encoder." in key
}
# load in pre-trained weights
task.encoder.load_state_dict(encoder_weights)
return task
@registry.register_task("ScalarRegressionTask")
class ScalarRegressionTask(BaseTaskModule):
__task__ = "regression"
"""
NOTE: You can have multiple targets, but each target is scalar.
"""
def __init__(
self,
encoder: nn.Module | None = None,
encoder_class: type[nn.Module] | None = None,
encoder_kwargs: dict[str, Any] | None = None,
loss_func: type[nn.Module] | nn.Module = nn.MSELoss,
task_keys: list[str] | None = None,
output_kwargs: dict[str, Any] = {},
**kwargs: Any,
) -> None:
super().__init__(
encoder,
encoder_class,
encoder_kwargs,
loss_func,
task_keys,
output_kwargs,
**kwargs,
)
self.save_hyperparameters(ignore=["encoder", "loss_func"])
def _make_output_heads(self) -> nn.ModuleDict:
modules = {}
for key in self.task_keys:
modules[key] = OutputHead(1, **self.output_kwargs).to(self.device)
return nn.ModuleDict(modules)
def _filter_task_keys(
self,
keys: list[str],
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> list[str]:
"""
Filters out task keys for scalar regression.
This routine will filter out keys with targets that are multidimensional, since
this is the _scalar_ regression task class.
Parameters
----------
keys : List[str]
List of task keys
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of training samples to inspect.
Returns
-------
List[str]
List of filtered task keys
"""
keys = super()._filter_task_keys(keys, batch)
def checker(key) -> bool:
# this ignores all non-tensor objects, and checks to make
# sure the last target dimension is scalar
target = batch["targets"][key]
if isinstance(target, torch.Tensor):
return target.size(-1) <= 1
return False
# this filters out targets that are multidimensional
keys = list(filter(checker, keys))
return keys
def on_train_batch_start(self, batch: Any, batch_idx: int) -> int | None:
"""
PyTorch Lightning hook to check OutputHeads are created.
This will take data from the batch to determine which key to retrieve
data from and how many heads to create.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of data from data loader.
batch_idx : int
Batch index.
unused
PyTorch Lightning hangover
Returns
-------
Optional[int]
Just returns the parent result.
"""
status = super().on_train_batch_start(batch, batch_idx)
# if there are no task keys set, task has not been initialized yet
if len(self.task_keys) == 0:
keys = batch["target_types"]["regression"]
self.task_keys = self._filter_task_keys(keys, batch)
# now add the parameters to our task's optimizer
opt = self.optimizers()
opt.add_param_group({"params": self.output_heads.parameters()})
# create normalizers for each target
self.normalizers = self._make_normalizers()
return status
def on_validation_batch_start(
self,
batch: any,
batch_idx: int,
dataloader_idx: int = 0,
):
self.on_train_batch_start(batch, batch_idx)
@registry.register_task("MaceEnergyForceTask")
class MaceEnergyForceTask(BaseTaskModule):
__task__ = "regression"
"""
Class for training MACE on energy and forces
"""
def __init__(
self,
encoder: Optional[nn.Module] = None,
encoder_class: Optional[Type[nn.Module]] = None,
encoder_kwargs: Optional[Dict[str, Any]] = None,
loss_func: Union[Type[nn.Module], nn.Module] = nn.MSELoss,
loss_coeff: Optional[Dict[str, Any]] = None,
task_keys: Optional[List[str]] = None,
output_kwargs: Dict[str, Any] = {},
**kwargs: Any,
) -> None:
super().__init__(
encoder,
encoder_class,
encoder_kwargs,
loss_func,
task_keys,
output_kwargs,
**kwargs,
)
self.save_hyperparameters(ignore=["encoder", "loss_func"])
self.loss_coeff = loss_coeff
def process_embedding(self, embeddings: Embeddings) -> Dict[str, torch.Tensor]:
"""
Given a set of embeddings, output predictions for each head.
Parameters
----------
embeddings : torch.Tensor
Batch of graph/point cloud embeddings
Returns
-------
Dict[str, torch.Tensor]
Predictions per output head
"""
results = {}
for key, head in self.output_heads.items():
# in the event that we get multiple embeddings, we average
# every dimension execpt the batch and dimensionality
output = head(embeddings.system_embedding[key])
output = reduce(output, "b ... d -> b d", reduction="mean")
results[key] = output
return results
def _compute_losses(
self,
batch: Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]],
) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]:
"""
Compute pred versus target for every target, then sum.
With coefficients defined for each key
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of samples to evaluate on.
embeddings : Optional[torch.Tensor]
If provided, bypasses calling the encoder and obtains predictions
from processing the embeddings. Mainly intended for use with multitask
abstraction.
Returns
-------
Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]
Dictionary containing the joint loss, and a subdictionary
containing each individual target loss.
"""
targets = self._get_targets(batch)
predictions = self(batch)
losses = {}
for key in self.task_keys:
target_val = targets[key]
if self.uses_normalizers:
target_val = self.normalizers[key].norm(target_val)
if self.loss_coeff is None:
coefficient = 1.0
else:
coefficient = self.loss_coeff[key]
losses[key] = self.loss_func(predictions[key], target_val) * (
coefficient / predictions[key].numel()
)
total_loss: torch.Tensor = sum(losses.values())
return {"loss": total_loss, "log": losses}
def _make_output_heads(self) -> nn.ModuleDict:
modules = {}
for key in self.task_keys:
modules[key] = OutputHead(**self.output_kwargs[key]).to(self.device)
return nn.ModuleDict(modules)
def _filter_task_keys(
self,
keys: List[str],
batch: Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]],
) -> List[str]:
"""
Filters out task keys for scalar regression.
This routine will filter out keys with targets that are multidimensional, since
this is the _scalar_ regression task class.
Parameters
----------
keys : List[str]
List of task keys
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of training samples to inspect.
Returns
-------
List[str]
List of filtered task keys
"""
keys = super()._filter_task_keys(keys, batch)
def checker(key) -> bool:
# this ignores all non-tensor objects, and checks to make
# sure the last target dimension is scalar
target = batch["targets"][key]
if isinstance(target, torch.Tensor):
return target.size(-1) <= 1
return False
# this filters out targets that are multidimensional
keys = list(filter(checker, keys))
return keys
def validation_step(
self,
batch: Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]],
batch_idx: int,
):
with torch.enable_grad(): # Enabled gradient for Force computation
loss_dict = self._compute_losses(batch)
metrics = {}
# prepending training flag for
for key, value in loss_dict["log"].items():
metrics[f"val_{key}"] = value
try:
batch_size = self.encoder.read_batch_size(batch)
except: # noqa: E722
warn(
"Unable to parse batch size from data, defaulting to `None` for logging."
)
batch_size = None
self.log_dict(metrics, batch_size=batch_size, sync_dist=True)
return loss_dict
def test_step(
self,
batch: Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]],
batch_idx: int,
):
with torch.enable_grad(): # Enabled gradient for Force computation
loss_dict = self._compute_losses(batch)
metrics = {}
# prepending training flag for
for key, value in loss_dict["log"].items():
metrics[f"test_{key}"] = value
try:
batch_size = self.encoder.read_batch_size(batch)
except: # noqa: E722
warn(
"Unable to parse batch size from data, defaulting to `None` for logging."
)
batch_size = None
self.log_dict(metrics, batch_size=batch_size, sync_dist=True)
return loss_dict
def on_train_batch_start(self, batch: Any, batch_idx: int) -> Optional[int]:
"""
PyTorch Lightning hook to check OutputHeads are created.
This will take data from the batch to determine which key to retrieve
data from and how many heads to create.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of data from data loader.
batch_idx : int
Batch index.
unused
PyTorch Lightning hangover
Returns
-------
Optional[int]
Just returns the parent result.
"""
status = super().on_train_batch_start(batch, batch_idx)
# if there are no task keys set, task has not been initialized yet
if len(self.task_keys) == 0:
keys = batch["target_types"]["regression"]
self.task_keys = self._filter_task_keys(keys, batch)
# now add the parameters to our task's optimizer
opt = self.optimizers()
opt.add_param_group({"params": self.output_heads.parameters()})
# create normalizers for each target
self.normalizers = self._make_normalizers()
return status
def on_validation_batch_start(
self, batch: any, batch_idx: int, dataloader_idx: int = 0
):
self.on_train_batch_start(batch, batch_idx)
@registry.register_task("BinaryClassificationTask")
class BinaryClassificationTask(BaseTaskModule):
__task__ = "classification"
"""
Same as the regression case; you can have multiple targets,
but each target has to be a binary classification task.
Output heads will produce logits by default alongside BCEWithLogitsLoss
for computation; if otherwise, requires user intervention.
"""
def __init__(
self,
encoder: nn.Module | None = None,
encoder_class: type[nn.Module] | None = None,
encoder_kwargs: dict[str, Any] | None = None,
loss_func: type[nn.Module] | nn.Module = nn.BCEWithLogitsLoss,
task_keys: list[str] | None = None,
output_kwargs: dict[str, Any] = {},
**kwargs,
) -> None:
super().__init__(
encoder,
encoder_class,
encoder_kwargs,
loss_func,
task_keys,
output_kwargs,
**kwargs,
)
self.save_hyperparameters(ignore=["encoder", "loss_func"])
def _make_output_heads(self) -> nn.ModuleDict:
modules = {}
for key in self.task_keys:
modules[key] = OutputHead(1, **self.output_kwargs).to(self.device)
return nn.ModuleDict(modules)
def on_train_batch_start(self, batch: Any, batch_idx: int) -> int | None:
"""
PyTorch Lightning hook to check OutputHeads are created.
This will take data from the batch to determine which key to retrieve
data from and how many heads to create.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of data from data loader.
batch_idx : int
Batch index.
unused
PyTorch Lightning hangover
Returns
-------
Optional[int]
Just returns the parent result.
"""
status = super().on_train_batch_start(batch, batch_idx)
# if there are no task keys set, task has not been initialized yet
if len(self.task_keys) == 0:
keys = batch["target_types"]["classification"]
self.task_keys = keys
# now add the parameters to our task's optimizer
opt = self.optimizers()
opt.add_param_group({"params": self.output_heads.parameters()})
return status
def on_validation_batch_start(
self,
batch: Any,
batch_idx: int,
dataloader_idx: int = 0,
):
self.on_train_batch_start(batch, batch_idx)
@registry.register_task("ForceRegressionTask")
class ForceRegressionTask(BaseTaskModule):
__task__ = "force_regression"
__needs_grads__ = ["pos"]
def __init__(
self,
encoder: nn.Module | None = None,
encoder_class: type[nn.Module] | None = None,
encoder_kwargs: dict[str, Any] | None = None,
loss_func: type[nn.Module] | nn.Module = nn.L1Loss,
task_keys: list[str] | None = None,
output_kwargs: dict[str, Any] = {},
embedding_reduction_type: str = "sum",
**kwargs,
) -> None:
super().__init__(
encoder,
encoder_class,
encoder_kwargs,
loss_func,
task_keys,
output_kwargs,
embedding_reduction_type=embedding_reduction_type,
**kwargs,
)
self.save_hyperparameters(ignore=["encoder", "loss_func"])
# have to enable double backprop
self.automatic_optimization = False
def _make_output_heads(self) -> nn.ModuleDict:
# this task only utilizes one output head
modules = {"energy": OutputHead(1, **self.output_kwargs).to(self.device)}
return nn.ModuleDict(modules)
def forward(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> dict[str, torch.Tensor]:
# for ease of use, this task will always compute forces
#del batch["embeddings"]
with dynamic_gradients_context(True, self.has_rnn):
# first ensure that positions tensor is backprop ready
if "graph" in batch:
graph = batch["graph"]
cell = batch["cell"]
# the DGL case
if hasattr(graph, "ndata"):
pos: torch.Tensor = graph.ndata.get("pos")
# for frame averaging
fa_rot = graph.ndata.get("fa_rot", None)
fa_pos = graph.ndata.get("fa_pos", None)
graph.ndata["pos"] = pos
else:
# otherwise assume it's PyG
pos: torch.Tensor = graph.pos
# for frame averaging
fa_rot = getattr(graph, "fa_rot", None)
fa_pos = getattr(graph, "fa_pos", None)
cell = getattr(graph, "cell", None)
else:
graph = None
# assume point cloud otherwise
pos: torch.Tensor = batch.get("pos")
# no frame averaging architecture yet for point clouds
fa_rot = None
fa_pos = None
if pos is None:
raise ValueError(
"No atomic positions were found in batch - neither as standalone tensor nor graph.",
)
if isinstance(pos, torch.Tensor):
pos.requires_grad_(True)
displacement = torch.zeros(
(1, 3, 3),
dtype=pos.dtype,
device=pos.device,
)
displacement.requires_grad_(True)
symmetric_displacement = 0.5 * (
displacement + displacement.transpose(-1, -2)
) # From https://github.com/mir-group/nequip
pos = pos + torch.einsum(
"be,bec->bc",
pos,
symmetric_displacement,
)
if "graph" in batch:
graph.pos = pos
if hasattr(graph, "ndata"):
graph.ndata["pos"] = pos
if fa_pos is not None:
for k in range(len(fa_pos)):
fa_pos[0].requires_grad_(True)
fa_pos[0] = fa_pos[0] + torch.einsum(
"be,bec->bc",
pos,
symmetric_displacement,
)
elif isinstance(pos, list):
[p.requires_grad_(True) for p in pos]
else:
raise ValueError(
f"'pos' data is required for force calculation, but isn't a tensor or a list of tensors: {type(pos)}.",
)
if isinstance(fa_pos, torch.Tensor):
fa_pos.requires_grad_(True)
elif isinstance(fa_pos, list):
[f_p.requires_grad_(True) for f_p in fa_pos]
if "embeddings" in batch:
embeddings = batch.get("embeddings")
else:
embeddings = self.encoder(batch)
natoms = batch.get("natoms", None)
outputs = self.process_embedding(
embeddings, pos, displacement, cell, fa_rot, fa_pos, natoms, graph
)
return outputs
def process_embedding(
self,
embeddings: Embeddings,
pos: torch.Tensor,
displacement: torch.Tensor,
cell: torch.Tensor,
fa_rot: None | torch.Tensor = None,
fa_pos: None | torch.Tensor = None,
natoms: None | torch.Tensor = None,
graph: None | AbstractGraph = None,
) -> dict[str, torch.Tensor]:
outputs = {}
# compute node-level contributions to the energy
node_energies = self.output_heads["energy"](embeddings.point_embedding)
# figure out how we're going to reduce node level energies
# depending on the representation and/or the graph framework
if graph is not None:
if isinstance(graph, dgl.DGLGraph):
graph.ndata["node_energies"] = node_energies
def readout(node_energies: torch.Tensor):
return dgl.readout_nodes(
graph, "node_energies", op=self.embedding_reduction_type
)
else:
# assumes a batched pyg graph
batch = graph.batch
from torch_geometric.utils import scatter
def readout(node_energies: torch.Tensor):
return scatter(
node_energies,
batch,
dim=-2,
reduce=self.embedding_reduction_type,
)
else:
def readout(node_energies: torch.Tensor):
return reduce(
node_energies, "b ... d -> b ()", self.embedding_reduction_type
)
def energy_and_force(
pos: torch.Tensor,
displacement: torch.Tensor,
cell: torch.Tensor,
node_energies: torch.Tensor,
readout: Callable,
) -> tuple[torch.Tensor, torch.Tensor]:
# we sum over points and keep dimension as 1
energy = readout(node_energies)
if energy.ndim == 1:
energy.unsqueeze(-1)
# now use autograd for force calculation
# force = (
# -1
# * torch.autograd.grad(
# energy,
# pos,
# grad_outputs=torch.ones_like(energy),
# create_graph=True,
# )[0]
# )
forces, virials = torch.autograd.grad(
outputs=[energy], # [n_graphs, ]
inputs=[pos, displacement], # [n_nodes, 3]
retain_graph=True, # Make sure the graph is not destroyed during training
create_graph=True, # Create graph for second derivative
allow_unused=True,
)
cell = cell.view(-1, 3, 3)
volume = torch.einsum(
"zi,zi->z",
cell[:, 0, :],
torch.cross(cell[:, 1, :], cell[:, 2, :], dim=1),
).unsqueeze(-1)
stress = virials / volume.view(-1, 1, 1)
return energy, -1 * forces, stress
# not using frame averaging
if fa_pos is None:
energy, force, stress = energy_and_force(
pos, displacement, cell, node_energies, readout
)
else:
energy = []
force = []
stress = []
for idx, pos in enumerate(fa_pos):
frame_embedding = node_energies[:, idx, :]
frame_energy, frame_force, frame_stress = energy_and_force(
pos, displacement, cell, frame_embedding, readout
)
force.append(frame_force)
energy.append(frame_energy.unsqueeze(-1))
stress.append(frame_stress)
# check to see if we are frame averaging
if fa_rot is not None:
all_forces = []
# loop over each frame prediction, and transform to guarantee
# equivariance of frame averaging method
natoms = natoms.squeeze(-1).to(int)
for frame_idx, frame_rot in enumerate(fa_rot):
repeat_rot = torch.repeat_interleave(
frame_rot,
natoms,
dim=0,
).to(self.device)
rotated_forces = (
force[frame_idx].view(-1, 1, 3).bmm(repeat_rot.transpose(1, 2))
)
all_forces.append(rotated_forces)
# combine all the force and energy data into a single tensor
# using frame averaging, the expected shapes after concatenation are:
# force - [num positions, num frames, 3]
# energy - [batch size, num frames, 1]
force = torch.cat(all_forces, dim=1)
energy = torch.cat(energy, dim=1)
stress = torch.cat(stress, dim=1)
# reduce outputs to what are expected shapes
outputs["force"] = reduce(
force,
"n ... d -> n d",
self.embedding_reduction_type,
d=3,
)
# this may not do anything if we aren't frame averaging
# since the reduction is also done in the energy_and_force call
outputs["energy"] = reduce(
energy,
"b ... d -> b d",
self.embedding_reduction_type,
d=1,
)
# this ensures that we get a scalar value for every node
# representing the energy contribution
outputs["node_energies"] = node_energies
outputs["stress"] = stress
return outputs
def predict(self, batch: BatchDict) -> dict[str, torch.Tensor]:
"""
Similar to the base method, but we make two minor modifications to
the denormalization logic as we want to potentially apply the same
energy normalization rescaling to the forces and node-level energies.
Parameters
----------
batch : BatchDict
Batch of samples to evaluate on.
Returns
-------
dict[str, torch.Tensor]
Output dictionary as provided by the forward call. For this task in
particular, we may also apply the energy rescaling to forces and
node energies if separate keys for them are not provided.
"""
output = super().predict(batch)
# for forces, in the event that a dedicated normalizer wasn't provided
# but we have an energy normalizer, we apply the same factors to the force
if self.uses_normalizers:
if "force" not in self.normalizers and "energy" in self.normalizers:
# for force only std is used to rescale
output["force"] = output["force"] * self.normalizers["energy"].std
output["stress"] = output["stress"] * self.normalizers["energy"].std
if "node_energies" not in self.normalizers and "energy" in self.normalizers:
output["node_energies"] = self.normalizers["energy"].denorm(
output["node_energies"]
)
# print('ye walla use krna hai')
return output
def _get_targets(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> dict[str, torch.Tensor]:
"""
Extract out the energy and force targets from a batch.
The intended behavior is similar to other tasks, however explicit because
we actually expect "energy" and "force" keys as opposed to inferring them from a batch.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of samples to evaluate
Returns
-------
Dict[str, torch.Tensor]
Dictionary containing targets to evaluate against
Raises
------
KeyError
If either "energy" or "force" keys aren't found in the "targets"
dictionary within a batch, we abort the program.
"""
target_dict = {}
for key in ["energy", "force"]:
try:
target_dict[key] = batch["targets"][key]
except KeyError as e:
raise KeyError(
f"{key} was not found in targets key in batch, which is needed for force regression task.",
) from e
return target_dict
def on_train_batch_start(self, batch: Any, batch_idx: int) -> int | None:
"""
PyTorch Lightning hook to check OutputHeads are created.
This will take data from the batch to determine which key to retrieve
data from and how many heads to create.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of data from data loader.
batch_idx : int
Batch index.
unused
PyTorch Lightning hangover
Returns
-------
Optional[int]
Just returns the parent result.
"""
status = super().on_train_batch_start(batch, batch_idx)
# if there are no task keys set, task has not been initialized yet
if len(self.task_keys) == 0:
# first round is used to initialize the output head
self.task_keys = ["energy"]
self.output_heads = self._make_output_heads()
# overwrite it so that the loss is computed but we don't make another head
# for force outputs
self._task_keys = ["energy", "force"]
# now add the parameters to our task's optimizer
opt = self.optimizers()
opt.add_param_group({"params": self.output_heads.parameters()})
# create normalizers for each target
self.normalizers = self._make_normalizers()
return status
def training_step(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
batch_idx: int,
):
"""
Implements the training logic for force regression.
This task uses manual optimization to facilitate double backprop, but by
in large functions in the same way as other tasks.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph]]
A dictionary of batched data from the S2EF dataset.
batch_idx : int
Index of the batch being processed.
Returns
-------
Dict[str, Union[float, Dict[str, float]]]
Nested dictionary of losses
"""
opt = self.optimizers()
self.on_before_zero_grad(opt)
opt.zero_grad()
# compute losses
loss_dict = self._compute_losses(batch)
loss = loss_dict["loss"]
# sandwich lightning callbacks
self.manual_backward(loss, retain_graph=True)
self.manual_backward(loss)
self.on_before_optimizer_step(opt)
opt.step()
metrics = {}
# prepending training flag
for key, value in loss_dict["log"].items():
metrics[f"train_{key}"] = value
try:
batch_size = self.encoder.read_batch_size(batch)
except: # noqa: E722
warn(
"Unable to parse batch size from data, defaulting to `None` for logging.",
)
batch_size = None
self.log_dict(metrics, on_step=True, prog_bar=True, batch_size=batch_size)
return loss_dict
@registry.register_task("GradFreeForceRegressionTask")
class GradFreeForceRegressionTask(ScalarRegressionTask):
__task__ = "gff_regression"
def __init__(
self,
encoder: nn.Module | None = None,
encoder_class: type[nn.Module] | None = None,
encoder_kwargs: dict[str, Any] | None = None,
loss_func: type[nn.Module] | nn.Module = nn.MSELoss,
output_kwargs: dict[str, Any] = {},
**kwargs: Any,
) -> None:
if "task_keys" in kwargs:
warn(
f"GradFreeForceRegressionTask does not `task_keys`; "
f"ignoring passed keys: {kwargs['task_keys']}",
)
del kwargs["task_keys"]
super().__init__(
encoder,
encoder_class,
encoder_kwargs,
loss_func,
["force"],
output_kwargs,
**kwargs,
)
def _make_output_heads(self) -> nn.ModuleDict:
modules = {"force": OutputHead(3, **self.output_kwargs).to(self.device)}
return nn.ModuleDict(modules)
def _get_targets(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> dict[str, torch.Tensor]:
"""
Extract out the energy and force targets from a batch.
The intended behavior is similar to other tasks, however explicit because
we actually expect "energy" and "force" keys as opposed to inferring them from a batch.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of samples to evaluate
Returns
-------
Dict[str, torch.Tensor]
Dictionary containing targets to evaluate against
Raises
------
KeyError
If either "energy" or "force" keys aren't found in the "targets"
dictionary within a batch, we abort the program.
"""
if "force" not in batch["targets"]:
raise KeyError(
f"Force key missing in batch targets: keys found: {batch['targets'].keys()}",
)
target_dict = {"force": batch["targets"]["force"]}
return target_dict
def forward(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> dict[str, torch.Tensor]:
if "embeddings" in batch:
embedding = batch.get("embeddings")
else:
embedding = self.encoder(batch)
# check for frame averaging
if "graph" in batch:
graph = batch["graph"]
if hasattr(graph, "ndata"):
fa_rot = getattr(graph.ndata, "fa_rot", None)
else:
fa_rot = getattr(graph, "fa_rot", None)
outputs = self.process_embedding(embedding, fa_rot)
return outputs
def process_embedding(
self,
embeddings: Embeddings,
fa_rot: None | torch.Tensor = None,
) -> dict[str, torch.Tensor]:
"""
Given point/node-level embeddings, predict forces of each point.
Parameters
----------
embeddings : Embeddings
Data structure containing system/graph and point/node-level embeddings.
Returns
-------
Dict[str, torch.Tensor]
Dictionary containing a ``force`` key that maps to predicted forces
per point/node
"""
results = {}
force_head = self.output_heads["force"]
forces = force_head(embeddings.point_embedding)
if isinstance(fa_rot, torch.Tensor):
natoms = forces.size(0)
all_forces = []
# loop over each frame prediction, and transform to guarantee
# equivariance of frame averaging method
for frame_idx, frame_rot in fa_rot:
repeat_rot = torch.repeat_interleave(
frame_rot,
natoms,
dim=0,
).to(self.device)
rotated_forces = (
forces[:, frame_idx, :]
.view(-1, 1, 3)
.bmm(
repeat_rot.transpose(1, 2),
)
)
all_forces.append(rotated_forces.view(natoms, 3))
# combine all the force data into a single tensor
forces = torch.stack(all_forces, dim=1)
# make sure forces are in the right shape
forces = reduce(forces, "n ... d -> n d", self.embedding_reduction_type, d=3)
results["force"] = forces
return results
@registry.register_task("CrystalSymmetryClassificationTask")
class CrystalSymmetryClassificationTask(BaseTaskModule):
__task__ = "symmetry"
def __init__(
self,
encoder: nn.Module | None = None,
encoder_class: type[nn.Module] | None = None,
encoder_kwargs: dict[str, Any] | None = None,
loss_func: type[nn.Module] | nn.Module = nn.CrossEntropyLoss,
output_kwargs: dict[str, Any] = {},
normalize_kwargs: dict[str, float] | None = None,
freeze_embedding: bool = False,
**kwargs,
) -> None:
super().__init__(
encoder,
encoder_class,
encoder_kwargs,
loss_func,
[
"spacegroup",
],
output_kwargs,
normalize_kwargs=normalize_kwargs,
**kwargs,
)
self.freeze_embedding = freeze_embedding
if self.freeze_embedding:
self.encoder.atom_embedding.requires_grad_(False)
def _make_output_heads(self) -> nn.ModuleDict:
# this task only utilizes one output head; 230 possible space groups
modules = {"spacegroup": OutputHead(230, **self.output_kwargs).to(self.device)}
return nn.ModuleDict(modules)
def on_train_batch_start(self, batch: Any, batch_idx: int) -> int | None:
"""
PyTorch Lightning hook to check OutputHeads are created.
This will take data from the batch to determine which key to retrieve
data from and how many heads to create.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of data from data loader.
batch_idx : int
Batch index.
unused
PyTorch Lightning hangover
Returns
-------
Optional[int]
Just returns the parent result.
"""
status = super().on_train_batch_start(batch, batch_idx)
# if there are no task keys set, task has not been initialized yet
if len(self.task_keys) == 0:
self.task_keys = [
"spacegroup",
]
# now add the parameters to our task's optimizer
opt = self.optimizers()
opt.add_param_group({"params": self.output_heads.parameters()})
return status
def on_validation_batch_start(
self,
batch: Any,
batch_idx: int,
dataloader_idx: int = 0,
):
self.on_train_batch_start(batch, batch_idx)
def _get_targets(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> dict[str, torch.Tensor]:
target_dict = {}
subdict = batch.get("symmetry", None)
if subdict is None:
raise ValueError(
"'symmetry' key is missing from batch, which is needed for space group classification.",
)
labels: torch.Tensor = subdict.get("number", None)
if labels is None:
raise ValueError(
"Point group numbers missing from symmetry key, which is needed for symmetry classification.",
)
# subtract one for zero-indexing
labels = labels.long() - 1
# cast to long type, and make sure it is 1D for cross entropy loss
if labels.ndim > 1:
labels = labels.flatten()
target_dict["spacegroup"] = labels
return target_dict
@registry.register_task("MultiTaskLitModule")
class MultiTaskLitModule(pl.LightningModule):
def __init__(
self,
*tasks: tuple[str, BaseTaskModule],
task_scaling: Iterable[float] | None = None,
task_keys: dict[str, list[str]] | None = None,
**encoder_opt_kwargs,
) -> None:
"""
High level module for orchestrating multiple tasks.
Keep in mind that multiple tasks is distinct from multiple datasets:
this class can be used for multiple tasks even with a single dataset
for example regression and classification in Materials Project.
Parameters
----------
*tasks : Tuple[str, BaseTaskModule]
A variable number of 2-tuples, each comprising the
dataset name and the task associated. Example would
be ('MaterialsProjectDataset', RegressionTask).
"""
super().__init__()
assert len(tasks) > 0, "No tasks provided."
# hold a set of dataset mappings
task_map = nn.ModuleDict()
self.encoder = tasks[0][1].encoder
dset_names = set()
subtask_hparams = {}
task_counts = {}
for index, entry in enumerate(tasks):
# unpack tuple
(dset_name, task) = entry
if dset_name not in task_map:
task_map[dset_name] = nn.ModuleDict()
# set the task's encoder to be the same model instance except
# the first to avoid recursion
if index != 0:
task.encoder = self.encoder
# nest the task based on its category
if task.__task__ in task_counts.keys():
task_counts[task.__task__] += 1
else:
task_counts[task.__task__] = 0
task_map[dset_name][f"{task.__task__}{task_counts[task.__task__]}"] = task
# task_map[dset_name][task.__task__] = task
# add dataset names to determine forward logic
dset_names.add(dset_name)
# save hyperparameters from subtasks
subtask_hparams[f"{dset_name}_{task.__class__.__name__}"] = task.hparams
self.save_hyperparameters(
{
"subtask_hparams": subtask_hparams,
"task_scaling": task_scaling,
"encoder_opt_kwargs": encoder_opt_kwargs,
},
)
self.task_map = task_map
self.dataset_names = dset_names
self.task_scaling = task_scaling
self.encoder_opt_kwargs = encoder_opt_kwargs
if task_keys is not None:
for pair in self.dataset_task_pairs:
# unpack 2-tuple
dataset_name, task_type = pair
relevant_keys = task_keys[dataset_name][task_type]
self._initialize_subtask_output(
dataset_name,
task_type,
task_keys=relevant_keys,
)
self.configure_optimizers()
self.automatic_optimization = False
@property
def task_list(self) -> list[BaseTaskModule]:
# return a flat list of tasks to iterate over
modules = []
for task_group in self.task_map.values():
for subtask in task_group.values():
modules.append(subtask)
return modules
@property
def dataset_task_pairs(self) -> list[tuple[str, str]]:
# Return a list of 2-tuples corresponding to (dataset name, task type)
pairs = []
for dataset in self.dataset_names:
task_types = self.task_map[dataset].keys()
for task_type in task_types:
pairs.append((dataset, task_type))
return pairs
def configure_optimizers(self) -> list[Optimizer]:
"""
Configure subtask optimizers, as well as the joint encoder optimizer.
The main logic of this function is to aggregate all of the subtask
optimizers together, if they haven't been added yet. This is done
by assuming dataset name/task type combinations are unique, and we
rely on the subtask's own `configure_optimizers` function.
The latter half of the function adds the encoder optimizer.
Returns
-------
List[Optimizer]
List of optimizers that are subsequently passed into Lightning's
internal mechanisms
"""
optimizers = []
# this keeps a list of 2-tuples to index optimizers
self.optimizer_names = []
# iterate over tasks
index = 0
for data_key, tasks in self.task_map.items():
for task_type, subtask in tasks.items():
combo = (data_key, task_type)
if combo not in self.optimizer_names:
output_head = getattr(subtask, "output_heads", None)
assert (
output_head is not None
), f"{subtask} does not contain output heads; ensure `task_keys` are set: {subtask.task_keys}"
optimizer = subtask.configure_optimizers()
if isinstance(optimizer, tuple):
# unpack the two things if a tuple is returned
optimizer, scheduler = optimizer
if isinstance(optimizer, list):
# we only work with one optimizer
optimizer = optimizer[0]
# remove all the optimizer parameters, and re-add only the output heads
optimizer.param_groups.clear()
optimizer.add_param_group({"params": output_head.parameters()})
# add optimizer to the pile
optimizers.append(optimizer)
self.optimizer_names.append((data_key, task_type))
index += 1
assert (
len(self.optimizer_names) > 1
), "Only one optimizer was found for multi-task training."
if ("Global", "Encoder") not in self.optimizer_names:
opt_kwargs = {"lr": 1e-4}
opt_kwargs.update(self.encoder_opt_kwargs)
optimizers.append(AdamW(self.encoder.parameters(), **opt_kwargs))
self.optimizer_names.append(("Global", "Encoder"))
return optimizers
@property
def dataset_names(self) -> list[str]:
return self._dataset_names
@dataset_names.setter
def dataset_names(self, values: set | list[str]) -> None:
if isinstance(values, set):
values = list(values)
self._dataset_names = values
@property
def task_scaling(self) -> list[float]:
"""
Returns a list of scaling factors used task importance.
These values are applied to the loss values prior to backprop.
Returns
-------
List[float]
List of scaling factors for each task
"""
return self._task_scaling
@task_scaling.setter
def task_scaling(self, values: Iterable[float] | None) -> None:
if values is None:
values = [1.0 for _ in range(self.num_tasks)]
assert (
len(values) == self.num_tasks
), "Number of provided task scaling values not equal to number of tasks."
self._task_scaling = values
@property
def num_tasks(self) -> int:
"""
Return the total number of tasks.
Returns
-------
int
Number of tasks, aggregated over all datasets.
"""
counter = 0
# basically loop over datasets, and add up number of tasks
# per dataset
for tasks in self.task_map.values():
counter += len(tasks)
return counter
@property
def is_multidata(self) -> bool:
# convenient property to determine how to unpack batches
return len(self.dataset_names) > 1
@property
def has_initialized(self) -> bool:
"""
Property to track if subtasks have been initialized.
Right now this is manually set, but would like to refactor this later to
check if subtask output heads are all set.
Returns
-------
bool
True if first batch has been run already, otherwise False
"""
return all([task.has_initialized for task in self.task_list])
@property
def input_grad_keys(self) -> dict[str, list[str]]:
"""
Property to returns a list of keys for inputs that need gradient tracking.
Returns
-------
Union[List[str], None]
If there are tasks in this multitask that need input variables to have
gradients tracked, this property will return a list of them. Otherwise,
this returns None.
"""
keys = {}
if self.is_multidata:
for dset_name, task_group in self.task_map.items():
if dset_name not in keys:
keys[dset_name] = set()
dset_keyset = keys.get(dset_name)
for subtask in task_group.values():
dset_keyset.update(subtask.__needs_grads__)
else:
tasks = list(self.task_map.values()).pop(0)
keys[self.dataset_names[0]] = set()
for task in tasks:
keys[self.dataset_names[0]].update(task.__needs_grads__)
keys = {dset_name: sorted(subkeys) for dset_name, subkeys in keys.items()}
return keys
@property
def has_rnn(self) -> bool:
"""
Property to determine whether or not this LightningModule contains
RNNs. This is primarily to determine whether or not to enable/disable
contexts with cudnn, as double backprop is not supported.
Returns
-------
bool
True if any module is a subclass of `RNNBase`, otherwise False.
"""
return any([isinstance(module, nn.RNNBase) for module in self.modules()])
@property
def needs_dynamic_grads(self) -> bool:
"""
Boolean property reflecting whether this multitask in general needs
gradient computation to override inference modes.
Returns
-------
bool
True if any datasets need input grads, otherwise False
"""
return sum([len(keys) for keys in self.input_grad_keys.values()]) > 0
def _toggle_input_grads(
self,
batch: dict[
str,
dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
],
) -> None:
"""
Inplace method that will automatically enable gradient tracking for tensors
needed by tasks/datasets.
This function will loop over a batch of data (in the multidata case) and
grabs the list of tensor keys as required by a given subtask. The list
of tensor keys are then used to grab the input data from the batch and/or
graph, and if it's found will then try and set requires_grad_(True).
Parameters
----------
batch : Dict[str, Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]]
Batch of data
"""
need_grad_keys = getattr(self, "input_grad_keys", None)
if need_grad_keys is not None:
if self.is_multidata:
# if this is a multidataset task, loop over each dataset
# and enable gradients for the inputs that need them
for dset_name, data in batch.items():
input_keys = need_grad_keys.get(dset_name)
for key in input_keys:
# set require grad for both point cloud and graph tensors
if "graph" in data:
g = data.get("g")
if isinstance(g, dgl.DGLGraph):
if key in g.ndata:
data["graph"].ndata[key].requires_grad_(True)
else:
# assume it's a PyG graph
if key in g:
getattr(g, key).requires_grad_(True)
if key in data:
target = data.get(key)
# for tensors just set them directly
if isinstance(target, torch.Tensor):
target.requires_grad_(True)
else:
# assume the remaining case are lists of tensors
try:
[t.requires_grad_(True) for t in target]
except AttributeError:
pass
else:
# in the single dataset case, we just need to loop over a single
# set of tasks
input_keys = list(self.input_grad_keys.values()).pop(0)
for key in input_keys:
# set require grad for both point cloud and graph tensors
if "graph" in data:
g = data.get("g")
if isinstance(g, dgl.DGLGraph):
if key in g.ndata:
data["graph"].ndata[key].requires_grad_(True)
else:
# assume it's a PyG graph
if key in g:
getattr(g, key).requires_grad_(True)
if key in data:
target = data.get(key)
# for tensors just set them directly
if isinstance(target, torch.Tensor):
target.requires_grad_(True)
else:
# assume the remaining case are lists of tensors
try:
[t.requires_grad_(True) for t in target]
except AttributeError:
pass
def forward(
self,
batch: dict[
str,
dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
],
) -> dict[str, dict[str, torch.Tensor]]:
"""
Forward method for `MultiTaskLitModule`.
This is devised slightly specially to comprise a variety of scenarios, including
wrapping the entire compute in gradient contexts (for force prediction tasks),
ensuring inputs that need gradients are enabled, as well as running the
encoder at the beginning and passing the embeddings onto downstream tasks.
Parameters
----------
batch : Dict[str, Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]]
Batches of samples per dataset
Returns
-------
Dict[str, Dict[str, torch.Tensor]]
Dictionary of predictions, per dataset per subtask
"""
# iterate over datasets in the batch
results = {}
_grads = getattr(
self,
"needs_dynamic_grads",
False,
) # default to not needing grads
with dynamic_gradients_context(_grads, self.has_rnn):
# this function switches of `requires_grad_` for input tensors that need them
self._toggle_input_grads(batch)
# compute embeddings for each dataset
if self.is_multidata:
for key, data in batch.items():
data["embeddings"] = self.encoder(data)
else:
batch["embeddings"] = self.encoder(batch)
# for single dataset usage, we assume the nested structure isn't used
if self.is_multidata:
for key, data in batch.items():
subtasks = self.task_map[key]
if key not in results:
results[key] = {}
# finally call the task with the data
for task_type, subtask in subtasks.items():
results[key][task_type] = subtask(data)
else:
# in the single dataset case, we can skip the outer loop
# and just pass the batch into the subtask
tasks = list(self.task_map.values()).pop(0)
for task_type, subtask in tasks.items():
results[task_type] = subtask(batch)
return results
def on_train_batch_start(self, batch: Any, batch_idx: int) -> None:
"""
This callback is used to dynamically initialize output heads.
In the event where `task_keys` are not explicitly provided by the user
into the creation of each task, we the incoming batch for tasks
that have not been initialized and create the output heads.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of samples to compute
batch_idx : int
Batch index
unused : int
Legacy PyTorch Lightning arg
"""
# this follows what's implemented in forward to ensure the
# output heads and optimizers are set properly
if not self.has_initialized:
if self.is_multidata:
for dataset in batch.keys():
subtasks = self.task_map[dataset]
for task_type in subtasks.keys():
self._initialize_subtask_output(dataset, task_type, batch)
else:
# skip grabbing dataset key from the batch
tasks = list(self.task_map.values()).pop(0)
dataset = list(self.task_map.keys()).pop(0)
for task_type in tasks.keys():
self._initialize_subtask_output(dataset, task_type, batch)
return None
def _compute_losses(
self,
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
):
"""
Function for computing the losses over a batch.
This relies on the `_compute_losses` function of each subtask. Between the single
dataset and multidataset settings, the difference is just how the tasks are retrieved;
the former skips going through the dataset/task hierarchy.
Parameters
----------
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of samples to calculate losses over
"""
# compute predictions for required models
losses = {}
if self.is_multidata:
for key, data in batch.items():
subtasks = self.task_map[key]
if key not in losses:
losses[key] = {}
for task_type, subtask in subtasks.items():
losses[key][task_type] = subtask._compute_losses(data)
else:
tasks = list(self.task_map.values()).pop(0)
for task_type, subtask in tasks.items():
losses[task_type] = subtask._compute_losses(batch)
return losses
def _initialize_subtask_output(
self,
dataset: str,
task_type: str,
batch: None
| (
dict[
str,
dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
]
) = None,
task_keys: list[str] | None = None,
):
"""
For a given dataset and task type, this function will check and initialize corresponding
output heads and add them to the corresponding optimizer.
The behavior of this function changes depending on whether or not the output heads were
initialized earlier (i.e. before `on_train_batch_start`), based on whether it sees an
incoming batch, or explicitly passed `task_keys`. In the former, we will add the output
head parameters to the appropriate optimizer as well.
Parameters
----------
dataset : str
Name of the dataset
task_type : str
String classification of the task type, e.g. "regression"
batch : Optional[Dict[str, Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]]]
For "dynamically" instantiating multitasks, this function relies on an incoming batch
to determine what output heads to instantiate.
"""
task_instance: BaseTaskModule = self.task_map[dataset][task_type]
if batch is None and task_keys is None:
raise ValueError(
f"Unable to initialize output heads for {dataset}-{task_type}; neither batch nor task keys provided.",
)
if not task_instance.has_initialized:
# get the task keys from the batch, depends on usage
if batch is not None:
if self.is_multidata:
subset = batch[dataset]
else:
subset = batch
if task_keys is None:
task_keys = subset["target_types"][task_type]
# if keys aren't explicitly provided, apply filter
task_keys = task_instance._filter_task_keys(task_keys, subset)
# set task keys, then call make output heads
task_instance.task_keys = task_keys
if task_type == "regression":
task_instance.normalizers = task_instance._make_normalizers()
if batch is not None:
# if batch was provided then this is done after configure_optimizers
# so we need to add their parameters to the right optimizer
ref = (dataset, task_type)
opt_index = self.optimizer_names.index(ref)
# this adds the output head weights to optimizer
self.optimizers()[opt_index].add_param_group(
{"params": task_instance.output_heads.parameters()},
)
def embed(self, *args, **kwargs) -> Any:
return self.encoder(*args, **kwargs)
def _calculate_batch_size(
self,
batch: dict[
str,
dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
],
) -> dict[str, int | dict[str, int]]:
"""
Compute the size of a given batch.
For multidata runs, this will sum over each of the subsets, providing a breakdown of
how many samples from each respective dataset as well.
Parameters
----------
batch : Dict[str, Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]]
Batch of samples.
Returns
-------
Dict[str, Union[int, Dict[str, int]]]
Dictionary holding the batch size. For multidata runs, an additional "breakdown"
key comprises the number of samples from each dataset.
"""
batch_info = {}
batch_size = 0
if self.is_multidata:
break_down = {}
for dataset, subset in batch.items():
# extract out targets to figure batch size for this subset of data
if "graph" in subset:
counts = subset["graph"].batch_size
elif len(subset["targets"]) > 0:
key = next(iter(batch["targets"]))
sample = subset["targets"][key]
if isinstance(sample, dgl.DGLGraph):
counts = sample.batch_size
elif isinstance(sample, torch.Tensor):
# assume first dimension is the batch size
counts = sample.size(0)
else:
# assume the object is like a list
counts = len(sample)
# track how much data from each dataset
break_down[dataset] = counts
batch_size += counts
batch_info["breakdown"] = break_down
else:
if "graph" in batch:
batch_size = batch["graph"].batch_size
elif len(batch["targets"]) > 0:
key = next(iter(batch["targets"]))
sample = batch["targets"][key]
if isinstance(sample, dgl.DGLGraph):
batch_size = sample.batch_size
elif isinstance(sample, torch.Tensor):
# assume first dimension is the batch size
batch_size = sample.size(0)
else:
# assume the object is like a list
batch_size = len(sample)
batch_info["batch_size"] = batch_size
return batch_info
def __repr__(self) -> str:
build_str = "MultiTask Training module:\n"
for dataset, tasks in self.task_map.items():
for task_type in tasks.keys():
build_str += f"{dataset}-{task_type}\n"
return build_str
def training_step(
self,
batch: dict[
str,
dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
],
batch_idx: int,
) -> dict[str, dict[str, torch.Tensor]]:
"""
Manual training logic for multi tasks.
We sequentially step through each loss returned, and perform
backpropagation. The logic looks complicated, because we have
to match each loss with its corresponding optimizer.
Parameters
----------
batch : Dict[str, Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]]
Batch of data from one or more datasets.
batch_idx : int
Index of current batch
"""
# zero all gradients
optimizers = self.optimizers()
for opt in optimizers:
self.on_before_zero_grad(opt)
opt.zero_grad(set_to_none=True)
losses = self._compute_losses(batch)
loss_logging = {}
# for multiple datasets, we step through each dataset
if self.is_multidata:
for dataset_name, task_loss in losses.items():
for task_name, subtask_loss in task_loss.items():
# get the right optimizer by indexing our lookup list
ref = (dataset_name, task_name)
opt_index = self.optimizer_names.index(ref)
# backprop gradients
opt = optimizers[opt_index]
is_last_opt = opt_index == len(self.optimizer_names) - 2
# run hooks between backward
self.on_before_backward(subtask_loss["loss"])
# scale loss values in task
scaling = self.task_scaling[opt_index]
subtask_loss["loss"] = subtask_loss["loss"] * scaling
subtask_loss["loss"].backward(retain_graph=not is_last_opt)
# self.manual_backward(
# subtask_loss["loss"] * scaling,
# retain_graph=not is_last_opt,
# )
self.on_after_backward()
prepend_affix(subtask_loss["log"], dataset_name)
loss_logging.update(subtask_loss["log"])
# for single dataset, we can just unpack the dictionary directly
else:
dataset_name = self.dataset_names[0]
for task_name, loss in losses.items():
opt_index = self.optimizer_names.index((dataset_name, task_name))
opt = optimizers[opt_index]
is_last_opt = opt_index == len(self.optimizer_names) - 2
# run hooks between backward
self.on_before_backward(loss["loss"])
# scale loss values in task
scaling = self.task_scaling[opt_index]
self.manual_backward(
loss["loss"] * scaling,
retain_graph=not is_last_opt,
)
self.on_after_backward()
loss_logging.update(loss["log"])
# run before step hooks
for opt_idx, opt in enumerate(optimizers):
self.on_before_optimizer_step(opt)
opt.step()
# compoute the joint loss for logging purposes
loss_logging["total_loss"] = sum(list(loss_logging.values()))
# add train prefix to metric logs
prepend_affix(loss_logging, "train")
batch_info = self._calculate_batch_size(batch)
if "breakdown" in batch_info:
for key, value in batch_info["breakdown"].items():
self.log(
f"{key}.num_samples",
float(value),
on_step=True,
on_epoch=False,
reduce_fx="min",
)
self.log_dict(
loss_logging,
on_step=True,
prog_bar=True,
batch_size=batch_info["batch_size"],
)
return losses
def validation_step(
self,
batch: dict[
str,
dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
],
batch_idx: int,
) -> dict[str, dict[str, torch.Tensor]]:
"""
Manual training logic for multi tasks.
We sequentially step through each loss returned, and perform
backpropagation. The logic looks complicated, because we have
to match each loss with its corresponding optimizer.
Parameters
----------
batch : Dict[str, Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]]
Batch of data from one or more datasets.
batch_idx : int
Index of current batch
"""
losses = self._compute_losses(batch)
loss_logging = {}
# for multiple datasets, we step through each dataset
if self.is_multidata:
for dataset_name, task_loss in losses.items():
for task_name, subtask_loss in task_loss.items():
prepend_affix(subtask_loss["log"], dataset_name)
loss_logging.update(subtask_loss["log"])
# for single dataset, we can just unpack the dictionary directly
else:
dataset_name = self.dataset_names[0]
for task_name, loss in losses.items():
loss_logging.update(loss["log"])
# compoute the joint loss for logging purposes
loss_logging["total_loss"] = sum(list(loss_logging.values()))
# add train prefix to metric logs
prepend_affix(loss_logging, "val")
batch_info = self._calculate_batch_size(batch)
if "breakdown" in batch_info:
for key, value in batch_info["breakdown"].items():
self.log(
f"{key}.num_samples",
float(value),
on_epoch=True,
reduce_fx="min",
sync_dist=True,
)
self.log_dict(
loss_logging,
on_epoch=True,
prog_bar=True,
batch_size=batch_info["batch_size"],
sync_dist=True,
)
return losses
@classmethod
def load_from_checkpoint(
cls,
checkpoint_path,
map_location=None,
hparams_file=None,
strict: bool = True,
**kwargs: Any,
):
raise NotImplementedError(
"MultiTask should be reloaded using the `matsciml.models.multitask_from_checkpoint` function instead.",
)
@classmethod
def from_pretrained_encoder(cls, task_ckpt_path: str | Path, **kwargs):
"""
Attempts to instantiate a new task, adopting a previously trained encoder model.
This function will load in a saved PyTorch Lightning checkpoint,
copy over the hyperparameters needed to reconstruct the encoder,
and simply maps the encoder ``state_dict`` to the new instance.
``Kwargs`` are passed directly into the creation of the task, and so can
be thought of as just a task through the typical interface normally.
Parameters
----------
task_ckpt_path : Union[str, Path]
Path to an existing task checkpoint file. Typically, this
would be a PyTorch Lightning checkpoint.
Examples
--------
1. Create a new task simply from training another one
>>> new_task = ScalarRegressionTask.from_pretrained_encoder(
"epoch=10-step=100.ckpt"
)
2. Create a new task, modifying output heads
>>> new_taks = ForceRegressionTask.from_pretrained_encoder(
"epoch=5-step=12516.ckpt",
output_kwargs={
"num_hidden": 3,
"activation": "nn.ReLU"
}
)
"""
if isinstance(task_ckpt_path, str):
task_ckpt_path = Path(task_ckpt_path)
assert (
task_ckpt_path.exists()
), "Encoder checkpoint filepath specified but does not exist."
ckpt = torch.load(task_ckpt_path)
for key in ["encoder_class", "encoder_kwargs"]:
assert (
key in ckpt["hyper_parameters"]
), f"{key} expected to be in hyperparameters, but was not found."
# copy over the data for the new task
kwargs[key] = ckpt["hyper_parameters"][key]
# construct the new task with random weights
task = cls(**kwargs)
# this only copies over encoder weights, and removes the 'encoder.'
# pattern from keys
encoder_weights = {
key.replace("encoder.", ""): tensor
for key, tensor in ckpt["state_dict"].items()
if "encoder." in key
}
# load in pre-trained weights
task.encoder.load_state_dict(encoder_weights)
return task
@registry.register_task("OpenCatalystInference")
class OpenCatalystInference(ABC, pl.LightningModule):
"""
Implement a set of bare bones LightningModules that are solely used
for OpenCatalyst leaderboard submissions.
"""
def __init__(self, pretrained_model: nn.Module) -> None:
super().__init__()
self.model = pretrained_model
def _raise_inference_error(self):
raise NotImplementedError(
f"{self.__class__.__name__} is solely used for OpenCatalyst leaderboard submissions; please call 'predict' from trainer.",
)
def training_step(self, *args: Any, **kwargs: Any) -> None:
self._raise_inference_error()
def validation_step(self, *args: Any, **kwargs: Any) -> None:
self._raise_inference_error()
def test_step(self, *args: Any, **kwargs: Any) -> None:
self._raise_inference_error()
@abstractmethod
def predict_step(
self, batch: Any, batch_idx: int, dataloader_idx: int = 0
) -> Any: ...
@registry.register_task("IS2REInference")
class IS2REInference(OpenCatalystInference):
def __init__(
self,
pretrained_model: AbstractEnergyModel | ScalarRegressionTask,
) -> None:
assert isinstance(
pretrained_model,
(AbstractEnergyModel, ScalarRegressionTask),
), "IS2REInference expects a pretrained energy model or 'ScalarRegressionTask' as input."
super().__init__(pretrained_model)
def forward(self, batch: BatchDict) -> DataDict:
predictions = self.model(batch)
return predictions
@registry.register_task("S2EFInference")
class S2EFInference(OpenCatalystInference):
def __init__(self, pretrained_model: ForceRegressionTask) -> None:
assert isinstance(
pretrained_model,
ForceRegressionTask,
), "S2EFInference expects a pretrained 'ForceRegressionTask' instance as input."
super().__init__(pretrained_model)
def forward(self, batch: BatchDict) -> DataDict:
predictions = self.model(batch)
return predictions
def on_predict_start(self) -> None:
self.apply(rnn_force_train_mode)
return super().on_predict_start()
def predict_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> Any:
# force gradients when running predictions
predictions = self(batch)
energy, force = predictions["energy"], predictions["force"]
energy = energy.detach().cpu().to(torch.float16)
force = force.detach().cpu()
ids, chunk_ids = batch.get("sid"), batch.get("fid")
# ids are formatted differently for force tasks
system_ids = [f"{i}_{j}" for i, j in zip(ids, chunk_ids)]
predictions = {
"ids": system_ids,
"chunk_ids": chunk_ids,
"energy": energy,
}
# processing the forces is a bit more complicated because apparently
# only the free atoms are considered
if self.regress_forces:
if "graph" in batch:
graph = batch.get("graph")
fixed = graph.ndata["fixed"]
else:
# otherwise it's a point cloud
fixed = batch.get("fixed")
fixed_mask = fixed == 0
# retrieve only forces corresponding to unfixed nodes
predictions["forces"] = force[fixed_mask]
natoms = tuple(batch.get("natoms").cpu().numpy().astype(int))
chunk_split = torch.split(fixed, natoms)
chunk_ids = []
for chunk in chunk_split:
ids = (len(chunk) - sum(chunk)).cpu().numpy().astype(int)
chunk_ids.append(int(ids))
predictions["chunk_ids"] = chunk_ids
return predictions
def on_predict_batch_end(
self,
outputs: Any,
batch: Any,
batch_idx: int,
dataloader_idx: int = 0,
) -> None:
# reset gradients to ensure no contamination between batches
self.zero_grad(set_to_none=True)
class NodeDenoisingTask(BaseTaskModule):
__task__ = "pretraining"
"""
This implements a node position denoising task, as described by Zaidi _et al._,
ICLR 2023.
This task is paired with the `NoisyPositions` pretraining data transform,
which generates the noise. A single output head is used to predict the noise
for every atom, using the MSE between the predicted and actual noise as the
loss function.
"""
def __init__(
self,
encoder: nn.Module | None = None,
encoder_class: type[nn.Module] | None = None,
encoder_kwargs: dict[str, Any] | None = None,
loss_func: type[nn.Module] | nn.Module | None = None,
task_keys: list[str] | None = None,
output_kwargs: dict[str, Any] = {},
lr: float = 0.0001,
weight_decay: float = 0,
embedding_reduction_type: str = "mean",
normalize_kwargs: dict[str, float] | None = None,
scheduler_kwargs: dict[str, dict[str, Any]] | None = None,
**kwargs,
) -> None:
if task_keys is not None:
warn("Task keys were passed to NodeDenoisingTask, but is not used.")
task_keys = ["denoise"]
super().__init__(
encoder,
encoder_class,
encoder_kwargs,
loss_func,
task_keys,
output_kwargs,
lr,
weight_decay,
embedding_reduction_type,
normalize_kwargs,
scheduler_kwargs,
**kwargs,
)
self.loss_func = nn.MSELoss()
def _make_output_heads(self) -> nn.ModuleDict:
# make a single output head for noise prediction applied to nodes
denoise = OutputHead(3, **self.output_kwargs).to(self.device)
return nn.ModuleDict({"denoise": denoise})
def _filter_task_keys(
self,
keys: list[str],
batch: dict[str, torch.Tensor | dgl.DGLGraph | dict[str, torch.Tensor]],
) -> list[str]:
"""
For the denoising task, we will only ever target the "denoise" key.
Parameters
----------
keys : List[str]
List of task keys
batch : Dict[str, Union[torch.Tensor, dgl.DGLGraph, Dict[str, torch.Tensor]]]
Batch of training samples to inspect.
Returns
-------
List[str]
List of filtered task keys
"""
return ["denoise"]
def process_embedding(self, embeddings: Embeddings) -> dict[str, torch.Tensor]:
"""
Override the base process embedding method, since we are assumed to only
have a single output head and we need to use the point/node-level embeddings.
Parameters
----------
embeddings : Embeddings
Embeddings data structure containing graph and node-level embeddings.
Returns
-------
dict[str, torch.Tensor]
Dictionary with a single 'denoise' key, corresponding to the
predicted noise.
"""
head = self.output_heads["denoise"]
# prediction node noise
pred_noise = head(embeddings.point_embedding)
return {"denoise": pred_noise}
def forward(
self,
batch: BatchDict,
) -> dict[str, torch.Tensor]:
"""
Modified forward call for denoising positions.
The goal of this task is to predict noise, given noisy coordinates,
and for this to happen we substitute the noise-free positions temporarily
for the noisy ones to prevent interference with other tasks.
Parameters
----------
batch : BatchDict
Batch of data samples
Returns
-------
dict[str, torch.Tensor]
Dictionary output from ``process_embedding``
Raises
------
KeyError:
Raises a ``KeyError`` ff the noisy positions are not found
in either the graph or point cloud dictionary.
"""
if "graph" in batch:
graph = batch["graph"]
if hasattr(graph, "ndata"):
target = graph.ndata
else:
target = graph
else:
target = batch
if "noisy_pos" not in target:
raise KeyError(
"'noisy_pos' was not found in data structure, please add the"
" NoisyPositions pretraining transform, and/or check that"
" 'noisy_pos' is included in the graph transform ``node_keys``."
)
temp_pos = target["pos"].clone().detach()
# swap out positions for the noisy ones
target["pos"] = target["noisy_pos"]
if "embeddings" in batch:
embedding = batch.get("embeddings")
else:
embedding = self.encoder(batch)
outputs = self.process_embedding(embedding)
target["pos"] = temp_pos
return outputs
|