File size: 366,671 Bytes
acb8cc7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 | """train_l2_gddr7_wikipedia.py
Unified L2-Pinned Configurable-Depth Reasoning Core + Dual-Tier GDDR7 Sparse
Memory Architecture on an NVIDIA RTX PRO 6000 Blackwell (96 GB GDDR7, 128 MiB L2).
Unified Architecture:
Input IDs ──(async CUDA stream: Engram N-gram gather)──────────────────┐
│ ▼
[tok_emb] ─► [Prelude Loops 1–2] ─► [+ Layer-2 Engram Gate] ─► Save h_anchor
│
┌──────────────────────────────────────────────────────────────────┘
▼
┌─► [Shared L2-Pinned Core × r loops (PLN Stochastic Depth + TBPTT b=6)] ─┐
│ • Gated Input Injection from h_anchor (prevents prompt washout) │
│ • F_seq: Fused 6-way QKV + FLA GDN-2 + SWA FlexAttention + MoLA │
│ • G_ffn: SwiGLU (100% tok, L2) + MoD-Gated UltraMemV2 (top 12.5%) │
└─────────────────────────────────────────────────────────────────────────┘
│
▼
[Coda Loops 1–2] ─► [Liger Fused Linear CE (16k L2-pinned sub-batch)]
Test-Time Thinking Effort Presets (total loops = Prelude 2 + Shared r + Coda 2):
low=8, medium=16, high=24, xhigh=32, max=40
"""
from __future__ import annotations
import math
import os
import sys
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
_cache_root = os.environ.get("A100_CACHE_DIR", os.path.expanduser("~/.cache/a100_train"))
os.makedirs(_cache_root, exist_ok=True)
os.environ.setdefault("TORCHINDUCTOR_CACHE_DIR", os.path.join(_cache_root, "torchinductor_cache"))
os.environ.setdefault("TRITON_CACHE_DIR", os.path.join(_cache_root, "triton_cache"))
os.environ.setdefault("TORCHINDUCTOR_FX_GRAPH_CACHE", "1")
os.environ.setdefault("TORCHINDUCTOR_AUTOGRAD_CACHE", "1")
import queue
import threading
import time
import unicodedata
import numpy as np
import pyarrow.parquet as pq
import json
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
from tokenizers import Tokenizer
# Optional high-performance kernels (auto-detected with graceful fallbacks)
try:
from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss
_HAS_LIGER_CE = True
except Exception:
LigerFusedLinearCrossEntropyLoss = None
_HAS_LIGER_CE = False
_CCE_IMPORT_ERR = None
try:
from cut_cross_entropy import linear_cross_entropy as _cce_linear_cross_entropy
_HAS_CUT_CE = True
except Exception as _exc:
_cce_linear_cross_entropy = None
_HAS_CUT_CE = False
_CCE_IMPORT_ERR = str(_exc)
_FLA_IMPORT_ERR = None
# Prevent broken tilelang (missing tvm_ffi/z3) from crashing fla.ops import
try:
import tvm_ffi # noqa: F401
except Exception:
sys.modules.setdefault("tilelang", None)
try:
from fla.ops.gated_delta_rule import chunk_gated_delta_rule as _fla_chunk_gdn
_HAS_FLA = True
except Exception as _exc:
_fla_chunk_gdn = None
_HAS_FLA = False
_FLA_IMPORT_ERR = str(_exc)
try:
from fla.modules import ShortConvolution as _FLAShortConv
_HAS_FLA_CONV = True
except Exception:
_FLAShortConv = None
_HAS_FLA_CONV = False
try:
from torch.nn.attention.flex_attention import create_block_mask, flex_attention
_HAS_FLEX_ATTN = True
except Exception:
create_block_mask = None
flex_attention = None
_HAS_FLEX_ATTN = False
try:
import triton
import triton.language as tl
_HAS_TRITON = True
except Exception:
triton = None
tl = None
_HAS_TRITON = False
try:
from quack.rmsnorm import rmsnorm as _quack_rmsnorm
_HAS_QUACK_RMS = True
except Exception:
_quack_rmsnorm = None
_HAS_QUACK_RMS = False
try:
_HAS_FLASH_QLA = False # sm_120-only; A100 (sm_80) uses FLA Triton chunk_gated_delta_rule
except Exception:
_HAS_FLASH_QLA = False
# ===================================================================== CONFIG
# Locked-in Final 200B-Token Architecture: 1.50B Engram + 10.00B UltraMemV2 (topK=32 total) = 11.50B sparse (~32.5 GiB GDDR7)
SEQ_LEN = 1024 # sequence length per sample
BATCH_SIZE = 32 # 32 * 1024 = 32,768 micro-tokens (~59-62 GiB peak w/ 11.50B sparse + expandable_segments)
GRAD_ACCUM_STEPS = 4 # effective batch = 131,072 tokens/step (4 sampled loop depths/step)
PREFETCH_BATCHES = 8 # fallback thread-prefetch queue depth
MAX_STEPS = 500 # number of optimizer steps to run
LOG_EVERY = 10 # print telemetry every N optimizer steps
EVAL_EVERY = 40 # validation / health check cadence
# Flat binary memmap cache (eliminates 100% CPU tokenization bottleneck)
USE_MEMMAP_CACHE = True
DATA_CACHE_DIR = os.environ.get("A100_DATA_DIR", os.path.expanduser("~/a100_data"))
MEMMAP_BIN_PATH = os.path.join(DATA_CACHE_DIR, "wiki_tokens.bin")
VAL_PROMPTS_JSON = os.path.join(DATA_CACHE_DIR, "wiki_val_prompts.json")
MEMMAP_MAX_TOKENS = int(os.environ.get("MEMMAP_MAX_TOKENS", "100000000"))
TOKENIZER_HF_REPO = os.environ.get("TOKENIZER_HF_REPO", "gpt2")
TOKENIZER_PATH = os.environ.get("TOKENIZER_PATH", "")
HF_DATASET_NAME = os.environ.get("HF_DATASET_NAME", "wikimedia/wikipedia")
HF_DATASET_CONFIG = os.environ.get("HF_DATASET_CONFIG", "20231101.en")
DATA_PARQUET_DIR = os.environ.get("DATA_PARQUET_DIR", "") # ~600 MB uint16 across all 29 shards (strict <1.0 epoch, kills memorization!)
VAL_RESERVE_TOKENS = 262_144 # held-out tail tokens for objective effort-scaling PPL eval
# Configurable Thinking Effort & Stochastic Depth (Huginn + Parcae + OrthoInj)
N_PRELUDE = 1 # slim 1-block Prelude (eliminates perimeter bypass & saves ~12.6M/L2!)
N_SHARED_CELL_BLOCKS = 2 # 2-block recurrent cell (~25 MiB FP8, fits comfortably in 128 MiB L2!)
N_CODA = 1 # slim 1-block Coda (forces shared_core to carry multi-step reasoning)
EFFORT_TOTAL_LOOPS = {
"low": 8, # 1 + 3*2 + 1 (3 cell iters)
"medium": 16, # 1 + 7*2 + 1 (7 cell iters)
"high": 24, # 1 + 11*2 + 1 (11 cell iters)
"xhigh": 32, # 1 + 15*2 + 1 (15 cell iters)
"max": 40, # 1 + 19*2 + 1 (19 cell iters)
}
# Deep-weighted bucket sampling over (8, 12, 16, 24, 32, 40) loops: 60% main / 68% anneal at >=24L!
PLN_ITER_BUCKETS = (3, 5, 7, 11, 15, 19) # total blocks: 8, 12, 16, 24, 32, 40
DEPTH_BUCKET_PROBS_MAIN = (0.10, 0.12, 0.18, 0.22, 0.20, 0.18) # mean 11.0 iters (24L), 18% at 40L
DEPTH_BUCKET_PROBS_ANNEAL = (0.06, 0.10, 0.16, 0.22, 0.24, 0.22) # mean 12.0 iters (26L), 22% at 40L
PLN_MAIN_MEAN_ITERS = 11.0
PLN_ANNEAL_MEAN_ITERS = 12.0
PLN_SIGMA = 0.65
TBPTT_BACKPROP_ITERS = 4 # max TBPTT window (= 8 shared blks, 0.999 BPTT cos)
# 4-stage progressive depth curriculum (0-60%: 10L/TBPTT=2 -> 60-65%: 16L/TBPTT=3 -> 65-90%: 24L/TBPTT=4 -> 90-100%: 26L/TBPTT=4)
ENABLE_PROGRESSIVE_DEPTH = True
PROGRESSIVE_DEPTH_STAGES = (
(0.60, 2, (3, 4, 5), (0.30, 0.40, 0.30), "S1-10L"),
(0.65, 3, (3, 5, 7, 9, 11), (0.12, 0.22, 0.32, 0.22, 0.12), "S2-16L"),
(0.90, 4, PLN_ITER_BUCKETS, DEPTH_BUCKET_PROBS_MAIN, "S3-24L"),
(1.01, 4, PLN_ITER_BUCKETS, DEPTH_BUCKET_PROBS_ANNEAL, "S4-26L"),
)
# Continuous sinusoidal/Fourier loop conditioning (zero-init identity; extrapolates cleanly to 2x+ post-train loops)
ENABLE_CONTINUOUS_LOOP_COND = True
LOOP_FOURIER_FREQS = 16
LOOP_COND_HIDDEN = 64
LOOP_COND_R_REF = 19 # 40L reference iteration count (smoothly extrapolates to 80L+ post-train)
# Option 1: Hoisted TALA-Base (arXiv:2611.39694) — token-anchored shared Base K/V added to Block 1 SWA
ENABLE_TALA_BASE = True
TALA_BASE_DIM = 512 # shared base latent width (computed once per sequence, reused across all loops)
# FP8 E4M3 + per-row FP32 w_scale sparse tables (-10.5 GiB VRAM, -50% sparse GDDR7 bandwidth, Philox SR)
# On 4x A100-80GB (4-way sharded), pure BF16 sparse tables use only ~8.4 GiB/GPU with zero quant noise.
# Set SPARSE_TABLE_USE_FP8=1 in env to enable software Triton FP8 sparse tables if desired.
SPARSE_TABLE_USE_FP8 = os.environ.get("SPARSE_TABLE_USE_FP8", "0") == "1"
FP8_E4M3_MAX = 448.0
# Async secondary CUDA stream overlapping sparse_adam_step behind opt_dense.step() (NorMuon)
ENABLE_ASYNC_SPARSE_ADAM = True
CONTRACTION_REG_COEFF = 0.005 # feather-light Banach contraction: ||dx_r|| <= 0.97 ||dx_{r-1}||
MONO_LOSS_COEFF = 0.25 # hinge forcing L(r_final) <= L(r_mid).detach() - 0.01
RMID_LOSS_COEFF = 0.15 # Ouro intermediate-depth NTP supervision weight
RMID_BATCH_FRAC = 0.125 # 12.5% batch fused into single CCE call with Main + ECHO
# Token-Sparse Gated Multi-Hop UltraMemV2 (MoD-style per-loop gate)
MEM_CAPACITY_FRAC = 0.25 # top 25.0% of tokens on Block 1 per cell iter (8,192 of 32,768 tok)
MEM_EVAL_THRESHOLD = 0.50 # test-time threshold: easy tokens never touch GDDR7
# Optimization hyperparameters
LR_CORE_MUON = 1.0e-2 # NorMuon exact-RMS calibrated LR for Prelude/Coda
LR_SHARED_MUON = 6.0e-3 # 0.6x depth-scaled Muon LR for weight-tied shared_core
LR_CORE_ADAMW = 1.5e-3 # FP32 AdamW learning rate on 1D/norm/router/skinny-gate/vocab
LR_ENGRAM_MULT = 2.5 # moderated Engram LR (prevents Layer-2 n-gram shortcut)
LR_ULTRAMEM_MULT = 5.0 # full 5x LR for UltraMemV2 factual slots
ENGRAM_DROPOUT = 0.10 # light dropout on Layer-2 Engram during training
WEIGHT_DECAY_CORE = 0.01 # weight decay for core & router (0.0 for sparse tables!)
ULTRAMEM_BIAS_GAMMA = 1.5e-2 # Asymmetric overload bias rate + key centering (MemEnt > 0.99, MaxLoad < 2x)
ULTRAMEM_ROUTER_SCALE = 16.0 # router softmax temperature scale to prevent load collapse
ECHO_LOSS_COEFF = 0.25 # ECHO multi-horizon auxiliary loss weight (paired with r_mid NTP)
ECHO_FIXED_DEPTH = 1 # fixed 1-horizon ECHO for static torch.compile graphs (None = DDS)
ECHO_BATCH_FRAC = 0.125 # 12.5% batch (16,384 tok/step): fused with Main + r_mid in 1 CCE call
MAX_GRAD_NORM = 1.0
# Acceleration & Precision flags
USE_TORCH_COMPILE = True # torch.compile on core, routers, & sparse Adam
CORE_COMPILE_MODE = "max-autotune-no-cudagraphs" # Blackwell-tuned Triton & cuBLAS GEMM schedules
USE_FP8_LINEAR = False # A100 (sm_80) has no hardware FP8 Tensor Cores; use native BF16 Tensor Cores
USE_NVFP4_CORE = False # set True to test NVFP4 (RHT+SR) on the 4 Shared Core linears only
USE_FLEX_ATTENTION = True # PyTorch FlexAttention for SWA-only (score_mod=None) + online-softmax MoLA
USE_FLA_GDN = True # uses installed flash-linear-attention Triton kernel (auto-fallbacks if absent)
CE_CHUNK_TOKENS = 1024 # chunk size for fallback linear cross-entropy
PREFER_CUT_CE = True # prefer Cut Cross-Entropy (apple/ml-cross-entropy) over Liger when installed
LIGER_SUB_BATCH_TOKENS = 16384 # keeps logits <= 96 MiB in L2 while halving 192 MiB tok_emb reads
SPARSE_OPT_CHUNK = 131_072 # chunk size for sparse_adam_step to keep L2 hot
# Architecture constants
D_TOTAL = 2048
D_STREAM = D_TOTAL // 2 # 1024 per reversible stream
D_VOCAB = 1024 # factorized tied vocab/LM-head dim (cuts LM-head FLOPs by 50%!)
SWIGLU_TILE_TOKENS = 512
N_HEADS = 8
HEAD_DIM = 64
ATTN_DIM = N_HEADS * HEAD_DIM # 512 per branch
GDN_CONV_KERNEL = 4
GDN_CHUNK_SIZE = 64 # power-of-2; 64 halves inter-chunk scan when using fallback WY
SWA_WINDOW = 256 # 256x16..32 loops = 4k-8k receptive field; halves FlexAttention BF16 IO
HISA_PHI = math.pi / 2.0
HISA_BLOCK_TOKENS = 128
HISA_CHUNK_PAIRS = 8
MOLA_MEM_SLOTS = 16
FFN_HIDDEN = 2688
ROPE_BASE = 10000.0
EPS = 1e-6
EPS_DEFAULT = EPS
DEFAULT_EPS = EPS
INIT_SCALE = 0.25
MUON_BLOCK_PAPER = 2048
# Exact published 5-step Polar Express coefficients (arXiv:2505.16932v2, Algorithm 1)
_POLAR_EXPRESS_RAW = (
(8.28721201814563, -23.595886519098837, 17.300387312530933),
(4.107059111542203, -2.9478499167379106, 0.5448431082926601),
(3.9486908534822946, -2.908902115962949, 0.5518191394370137),
(3.3184196573706015, -2.488488024314874, 0.51004894012372),
(2.300652019954817, -1.6689039845747493, 0.4188073119525673),
)
POLAR_EXPRESS_SAFE = tuple(
(a / 1.01, b / (1.01 ** 3), c / (1.01 ** 5))
for (a, b, c) in _POLAR_EXPRESS_RAW[:-1]
) + (_POLAR_EXPRESS_RAW[-1],)
MUON_NS_STEPS = 5
ECHO_DDS_PROBS = (0.6, 0.3, 0.1)
FP8_E4M3_MAX = 448.0
FP8_E5M2_MAX = 57344.0
FP4_E2M1_MAX = 6.0
# Locked-in Final Tier 1 (1.50B Engram) & Tier 2 (10.00B UltraMemV2 TDQKR, topK=32 total) config
SPARSE_MEMORY_CFG = {
"engram_heads": 8,
"engram_rows_per_head": 1_464_844, # 1,464,844 * 8 * 128 = 1.500B params (~4.33 GiB GDDR7)
"engram_dim": 128,
"ultramem_heads": 2,
"ultramem_k": 3125, # 3125^2 = 9.766M slots/head * 2 * 512 = 10.000B params (~28.18 GiB GDDR7)
"ultramem_dv": 512,
"ultramem_tucker_rank": 4,
"ultramem_cand_k0": 32,
"ultramem_topk": 16, # 16/head = 32 total retrieved slots/token
}
USE_TRITON_MOLA_IN_COMPILE = True # Registered via torch.library.custom_op -> 0 graph breaks in torch.compile!
USE_CACHED_FP8_CORE = False # Disabled on A100 (sm_80); native BF16 Tensor Cores + torch.compile
MiB = 2**20
GiB = 2**30
NON_MUON_2D_NAMES = {
"swa.mola_beta",
"mola_beta",
"tok_emb.weight",
"w_q_row.weight",
"w_q_col.weight",
}
NVFP4_SHARED_CORE_TARGETS = {
f"shared_core.{i}.{layer}"
for i in range(N_SHARED_CELL_BLOCKS)
for layer in ("qkv_fg_fused", "out_proj", "w_gate_up", "w_down")
}
# ============================================================ HELPER FUNCTIONS
def banner(title):
print("\n" + "=" * 84)
print(f" {title}")
print("=" * 84)
def rms_norm(x, weight=None, eps=EPS, out_dtype=None):
x32 = x.float()
normed = x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + eps)
if weight is not None:
normed = normed * weight.float()
return normed.to(out_dtype or x.dtype)
def l2_norm(x, eps=EPS):
x32 = x.float()
return (x32 * torch.rsqrt(x32.pow(2).sum(-1, keepdim=True) + eps)).to(x.dtype)
def get_progressive_depth_stage(step, max_steps):
"""Return (tbptt_iters, iter_buckets, probs, stage_label) for the current training fraction."""
if not ENABLE_PROGRESSIVE_DEPTH:
in_anneal = step > int(0.80 * max_steps)
probs = DEPTH_BUCKET_PROBS_ANNEAL if in_anneal else DEPTH_BUCKET_PROBS_MAIN
return TBPTT_BACKPROP_ITERS, PLN_ITER_BUCKETS, probs, ("FIX-26L" if in_anneal else "FIX-24L")
frac = float(step) / float(max(1, max_steps))
for end_frac, tbptt, buckets, probs, label in PROGRESSIVE_DEPTH_STAGES:
if frac <= end_frac:
return tbptt, buckets, probs, label
_, tbptt, buckets, probs, label = PROGRESSIVE_DEPTH_STAGES[-1]
return tbptt, buckets, probs, label
def sample_pln_shared_iters(step, max_steps, rng):
"""Deep-weighted or 4-stage progressive stochastic depth sampler over 2-block cell iterations."""
_, buckets, probs, _ = get_progressive_depth_stage(step, max_steps)
idx = int(rng.choice(len(buckets), p=probs))
return int(buckets[idx])
def invert_unit_lower_tri(A):
"""Exact functional inverse of unit lower-triangular [..., C, C] (power-of-2 C)."""
n = A.size(-1)
if n == 1:
return torch.ones_like(A)
if n == 2:
ones = torch.ones_like(A[..., 0, 0])
zeros = torch.zeros_like(ones)
row0 = torch.stack([ones, zeros], dim=-1)
row1 = torch.stack([-A[..., 1, 0], ones], dim=-1)
return torch.stack([row0, row1], dim=-2)
assert (n & (n - 1)) == 0, f"invert_unit_lower_tri requires power-of-2 size, got {n}"
h = n // 2
diag_pair = torch.stack([A[..., :h, :h], A[..., h:, h:]], dim=0)
inv_pair = invert_unit_lower_tri(diag_pair)
inv_tl, inv_br = inv_pair[0], inv_pair[1]
off = -torch.matmul(torch.matmul(inv_br, A[..., h:, :h]), inv_tl)
top = torch.cat([inv_tl, torch.zeros_like(off)], dim=-1)
bot = torch.cat([off, inv_br], dim=-1)
return torch.cat([top, bot], dim=-2)
def is_muon_matrix_param(name, p):
if p.ndim != 2 or min(p.shape) < 64:
return False
if name in NON_MUON_2D_NAMES or name.endswith(tuple(NON_MUON_2D_NAMES)):
return False
return True
def partition_muon_adamw_params(named_params):
muon_params, adamw_params = [], []
for name, p in named_params:
if not p.requires_grad:
continue
if is_muon_matrix_param(name, p):
muon_params.append(p)
else:
adamw_params.append(p)
return muon_params, adamw_params
def stochastic_round_bf16(x):
"""Unbiased FP32 -> BF16: E[result] == x, so sub-ULP updates accumulate."""
bits = x.float().contiguous().view(torch.int32)
noise = torch.randint(0, 1 << 16, bits.shape, device=bits.device, dtype=torch.int32)
return ((bits + noise) & -65536).view(torch.float32).to(torch.bfloat16)
def write_back_(param, new_fp32):
if param.dtype == torch.bfloat16:
param.copy_(stochastic_round_bf16(new_fp32))
else:
param.copy_(new_fp32)
def cast_model_preserve_fp32_1d(model, device):
"""Large 2D matrices & tok_emb -> BF16; AdamW norms/gains/keys/skinny gates stay FP32."""
model.to(device)
_, adamw_params = partition_muon_adamw_params(model.named_parameters())
keep_fp32 = {id(p) for p in adamw_params} - {id(model.tok_emb.weight)}
for p in model.parameters():
p.data = p.data.float() if id(p) in keep_fp32 else p.data.bfloat16()
return model
# ============================================== NVFP4 (SM120) & TORCHAO FP8
def _make_hadamard_16(device):
"""Normalized 16x16 Sylvester Hadamard matrix H (H @ H.T == I)."""
h = torch.tensor([[1.0]], device=device, dtype=torch.float32)
for _ in range(4):
h = torch.cat([torch.cat([h, h], dim=1), torch.cat([h, -h], dim=1)], dim=0)
return h / 4.0
_E2M1_LEVELS = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0)
def _quantize_e2m1_1d_blocks(x, stochastic=False):
"""NVFP4 1x16 block quantization with FP8 E4M3 block scales + FP32 global scale."""
orig_shape = x.shape
x32 = x.float().reshape(-1, 16)
g_scale = x32.abs().amax().clamp_min(1e-12) / (FP8_E4M3_MAX * FP4_E2M1_MAX)
blk_max = x32.abs().amax(dim=-1, keepdim=True)
blk_scale = (blk_max / (FP4_E2M1_MAX * g_scale)).clamp(min=1e-6, max=FP8_E4M3_MAX)
if hasattr(torch, "float8_e4m3fn"):
blk_scale = blk_scale.to(torch.float8_e4m3fn).float()
eff_scale = (blk_scale * g_scale).clamp_min(1e-12)
scaled = (x32 / eff_scale).clamp(-FP4_E2M1_MAX, FP4_E2M1_MAX)
signs = scaled.sign()
a = scaled.abs()
levels = torch.tensor(_E2M1_LEVELS, device=x.device, dtype=torch.float32)
idx_hi = torch.bucketize(a, levels).clamp(1, len(_E2M1_LEVELS) - 1)
lo = levels[idx_hi - 1]
hi = levels[idx_hi]
if stochastic:
prob_hi = ((a - lo) / (hi - lo).clamp_min(1e-12)).clamp(0.0, 1.0)
q_abs = torch.where(torch.rand_like(prob_hi) < prob_hi, hi, lo)
else:
q_abs = torch.where((a - lo) < (hi - a), lo, hi)
return (signs * q_abs * eff_scale).view(orig_shape).to(x.dtype)
def _quantize_e2m1_2d_blocks(w):
"""NVFP4 2D 16x16 weight block quantization (identical Q(W) in fwd and bwd)."""
out_f, in_f = w.shape
w32 = w.float().view(out_f // 16, 16, in_f // 16, 16).permute(0, 2, 1, 3)
g_scale = w32.abs().amax().clamp_min(1e-12) / (FP8_E4M3_MAX * FP4_E2M1_MAX)
blk_max = w32.abs().amax(dim=(-2, -1), keepdim=True)
blk_scale = (blk_max / (FP4_E2M1_MAX * g_scale)).clamp(min=1e-6, max=FP8_E4M3_MAX)
if hasattr(torch, "float8_e4m3fn"):
blk_scale = blk_scale.to(torch.float8_e4m3fn).float()
eff_scale = (blk_scale * g_scale).clamp_min(1e-12)
scaled = (w32 / eff_scale).clamp(-FP4_E2M1_MAX, FP4_E2M1_MAX)
signs = scaled.sign()
a = scaled.abs()
levels = torch.tensor(_E2M1_LEVELS, device=w.device, dtype=torch.float32)
idx_hi = torch.bucketize(a, levels).clamp(1, len(_E2M1_LEVELS) - 1)
lo = levels[idx_hi - 1]
hi = levels[idx_hi]
q_abs = torch.where((a - lo) < (hi - a), lo, hi)
q = (signs * q_abs * eff_scale).permute(0, 2, 1, 3).contiguous().view(out_f, in_f)
return q.to(w.dtype)
class _NVFP4SoftwareLinearFn(torch.autograd.Function):
"""Reference NVFP4 training recipe (arXiv:2509.25149):
- 2D 16x16 weight RTN scaling (identical Q(W) in fwd/bwd)
- 1D 1x16 activation RTN scaling
- 1D 1x16 Stochastic Rounding on dY
- 16x16 Random Hadamard Transform (RHT) on Wgrad only
"""
@staticmethod
def forward(ctx, x, weight, h16):
x2d = x.reshape(-1, x.size(-1))
xq = _quantize_e2m1_1d_blocks(x2d, stochastic=False)
wq = _quantize_e2m1_2d_blocks(weight)
out = F.linear(xq, wq)
ctx.save_for_backward(x2d, wq, h16)
ctx.x_shape = x.shape
return out.view(*x.shape[:-1], weight.size(0))
@staticmethod
def backward(ctx, grad_out):
x2d, wq, h16 = ctx.saved_tensors
dy2d = grad_out.reshape(-1, wq.size(0))
dy_sr = _quantize_e2m1_1d_blocks(dy2d, stochastic=True)
dx = torch.matmul(dy_sr, wq)
# 16x16 Random Hadamard Transform on Wgrad reduction dim (M)
m_rows = x2d.size(0)
pad = (-m_rows) % 16
x_m = F.pad(x2d, (0, 0, 0, pad)) if pad else x2d
dy_m = F.pad(dy2d, (0, 0, 0, pad)) if pad else dy2d
signs = (torch.randint(0, 2, (16,), device=x2d.device, dtype=torch.float32) * 2.0 - 1.0)
rh = (h16 * signs.unsqueeze(0)).to(x2d.dtype)
# Apply H along M-blocks of 16: dW = (dY^T H)(H^T X)
x_rot = torch.matmul(rh.t(), x_m.view(-1, 16, x2d.size(1))).reshape(-1, x2d.size(1))
dy_rot = torch.matmul(rh.t(), dy_m.view(-1, 16, dy2d.size(1))).reshape(-1, dy2d.size(1))
x_rot_q = _quantize_e2m1_1d_blocks(x_rot.t().contiguous(), stochastic=False)
dy_rot_q = _quantize_e2m1_1d_blocks(dy_rot.t().contiguous(), stochastic=True)
dw = torch.matmul(dy_rot_q, x_rot_q.t())
return dx.view(ctx.x_shape), dw.to(wq.dtype), None
class NVFP4Linear(nn.Module):
"""NVFP4 wrapper keeping the original nn.Linear weight parameter."""
def __init__(self, linear, h16):
super().__init__()
assert linear.bias is None
self.weight = linear.weight
self.in_features = linear.in_features
self.out_features = linear.out_features
self.register_buffer("h16", h16, persistent=False)
def forward(self, x):
return _NVFP4SoftwareLinearFn.apply(x, self.weight, self.h16)
def enable_precision_recipes(model, device):
"""Apply NVFP4 (optional, 4 Shared Core GEMMs only) and torchao FP8 (remaining large linears).
High-precision perimeter (tok_emb/LM head, RMSNorm, GDN-2 gates, Flex+MoLA,
Engram/UltraMemV2 routers, Prelude 1-2, Coda 1-2) never uses NVFP4.
"""
n_nvfp4 = 0
nvfp4_backend = "disabled"
nvfp4_fqns = set()
if USE_NVFP4_CORE and device.type == "cuda":
# Prefer hardware sm120-nvfp4-training kernel if installed; else software RHT+SR recipe
try:
import sm120_nvfp4 # type: ignore
if hasattr(sm120_nvfp4, "convert_linear"):
for name, mod in list(model.named_modules()):
if name in NVFP4_SHARED_CORE_TARGETS and isinstance(mod, nn.Linear):
parent_name, attr = name.rsplit(".", 1)
parent = model.get_submodule(parent_name)
setattr(parent, attr, sm120_nvfp4.convert_linear(mod))
nvfp4_fqns.add(name)
n_nvfp4 += 1
nvfp4_backend = "sm120_nvfp4_hardware"
except Exception:
h16 = _make_hadamard_16(device)
for name, mod in list(model.named_modules()):
if name in NVFP4_SHARED_CORE_TARGETS and isinstance(mod, nn.Linear):
parent_name, attr = name.rsplit(".", 1)
parent = model.get_submodule(parent_name)
setattr(parent, attr, NVFP4Linear(mod, h16))
nvfp4_fqns.add(name)
n_nvfp4 += 1
nvfp4_backend = "software_rht_sr_reference"
n_fp8 = 0
if USE_CACHED_FP8_CORE and USE_FP8_LINEAR and (not USE_NVFP4_CORE) and device.type == "cuda":
try:
wrapped = wrap_shared_core_with_cached_fp8(model, use_rowwise=True)
n_fp8 += len(wrapped)
except Exception as exc:
print(f" CachedFP8Linear wrap skipped ({exc}); falling back to torchao FP8.")
if USE_FP8_LINEAR and device.type == "cuda":
try:
from torchao.float8 import Float8LinearConfig, convert_to_float8_training
converted_count = [0]
def module_filter_fn(mod, fqn):
if fqn in nvfp4_fqns or not isinstance(mod, nn.Linear) or mod.bias is not None:
return False
# Lower threshold to >=512 so emb_up, lm_down, UltraMemV2 & Engram projections also run FP8!
ok = (
min(mod.in_features, mod.out_features) >= 512
and mod.in_features % 16 == 0
and mod.out_features % 16 == 0
)
if ok:
converted_count[0] += 1
return ok
convert_to_float8_training(
model, config=Float8LinearConfig(), module_filter_fn=module_filter_fn
)
n_fp8 += converted_count[0]
except Exception as exc:
print(f" torchao FP8 unavailable ({exc}); using BF16 linear layers.")
return n_fp8, n_nvfp4, nvfp4_backend
# ===================================== INTERNET HF TOKENIZER & DATA STREAMING
def init_distributed():
"""Initialize torch.distributed when launched via torchrun; no-op for single-GPU runs."""
world_size = int(os.environ.get("WORLD_SIZE", "1"))
if world_size > 1 and not dist.is_initialized():
local_rank = int(os.environ.get("LOCAL_RANK", "0"))
if torch.cuda.is_available():
torch.cuda.set_device(local_rank)
dist.init_process_group(backend="nccl" if torch.cuda.is_available() else "gloo")
rank = dist.get_rank()
device = torch.device(f"cuda:{local_rank}" if torch.cuda.is_available() else "cpu")
return rank, local_rank, world_size, device
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
return 0, 0, 1, device
def dist_is_active():
return dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1
class _DistAllToAllFn(torch.autograd.Function):
"""Differentiable equal-split all_to_all_single for 4-way head-sharded Engram."""
@staticmethod
def forward(ctx, x):
out = torch.empty_like(x)
dist.all_to_all_single(out, x.contiguous())
return out
@staticmethod
def backward(ctx, grad_out):
grad_in = torch.empty_like(grad_out)
dist.all_to_all_single(grad_in, grad_out.contiguous())
return grad_in
class _DistAllGatherFn(torch.autograd.Function):
"""Differentiable all_gather (backward = reduce_scatter sum) for sharded UltraMemV2 weights."""
@staticmethod
def forward(ctx, x):
w = dist.get_world_size()
out = torch.empty((w, *x.shape), device=x.device, dtype=x.dtype)
dist.all_gather_into_tensor(out, x.contiguous())
return out
@staticmethod
def backward(ctx, grad_out):
grad_in = torch.empty(grad_out.shape[1:], device=grad_out.device, dtype=grad_out.dtype)
dist.reduce_scatter_tensor(grad_in, grad_out.contiguous(), op=dist.ReduceOp.SUM)
return grad_in
class _DistReduceScatterSumFn(torch.autograd.Function):
"""Differentiable reduce_scatter sum (backward = all_gather) for sharded UltraMemV2 outputs."""
@staticmethod
def forward(ctx, x):
out = torch.empty(x.shape[1:], device=x.device, dtype=x.dtype)
dist.reduce_scatter_tensor(out, x.contiguous(), op=dist.ReduceOp.SUM)
return out
@staticmethod
def backward(ctx, grad_out):
w = dist.get_world_size()
grad_in = torch.empty((w, *grad_out.shape), device=grad_out.device, dtype=grad_out.dtype)
dist.all_gather_into_tensor(grad_in, grad_out.contiguous())
return grad_in
def load_internet_tokenizer():
"""Load tokenizer from TOKENIZER_PATH if provided, else download from Hugging Face Hub."""
if TOKENIZER_PATH and os.path.exists(TOKENIZER_PATH):
return Tokenizer.from_file(TOKENIZER_PATH)
return Tokenizer.from_pretrained(TOKENIZER_HF_REPO)
def prepare_internet_wiki_memmap(
tokenizer,
vocab_size,
out_path=MEMMAP_BIN_PATH,
prompts_path=VAL_PROMPTS_JSON,
max_tokens=MEMMAP_MAX_TOKENS,
):
"""Build or reuse a local uint16/uint32 token memmap from local parquets or HF streaming Wikipedia."""
os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
np_dtype = np.uint16 if vocab_size < 65536 else np.uint32
item_bytes = np.dtype(np_dtype).itemsize
if os.path.exists(out_path) and os.path.getsize(out_path) >= 1_000_000 * item_bytes:
n_tok = os.path.getsize(out_path) // item_bytes
val_prompts = []
if os.path.exists(prompts_path):
try:
val_prompts = json.loads(Path(prompts_path).read_text(encoding="utf-8"))
except Exception:
val_prompts = []
return n_tok, np_dtype, val_prompts
# Optional local parquet folder override
if DATA_PARQUET_DIR and os.path.isdir(DATA_PARQUET_DIR):
pfiles = sorted(
os.path.join(dp, fn)
for dp, _, fns in os.walk(DATA_PARQUET_DIR)
for fn in fns
if fn.endswith(".parquet")
)
if pfiles:
n_tok, dt, val_prompts = pretokenize_parquet_to_bin(
pfiles, tokenizer, vocab_size, out_path=out_path, max_tokens=max_tokens
)
Path(prompts_path).write_text(json.dumps(val_prompts), encoding="utf-8")
return n_tok, dt, val_prompts
# Default: stream directly from Hugging Face Hub over A100 VM internet
from datasets import load_dataset
eos_id = _resolve_eos_id(tokenizer)
ds = load_dataset(HF_DATASET_NAME, HF_DATASET_CONFIG, split="train", streaming=True)
tmp_path = out_path + ".tmp"
t0 = time.perf_counter()
written = 0
val_prompts = []
text_buf = []
BATCH_DOCS = 256
print(
f" Streaming {HF_DATASET_NAME} ({HF_DATASET_CONFIG}) -> {out_path} "
f"(target {max_tokens / 1e6:.0f}M tokens, {np_dtype.__name__})..."
)
with open(tmp_path, "wb") as f:
for row in ds:
txt = row.get("text") or row.get("content") or ""
if not isinstance(txt, str) or len(txt) < 40:
continue
if len(val_prompts) < 8 and len(txt) > 80:
snip = " ".join(txt.strip().split()[:24])
if len(snip) > 30:
val_prompts.append(snip)
text_buf.append(txt)
if len(text_buf) >= BATCH_DOCS:
encs = tokenizer.encode_batch(text_buf)
text_buf.clear()
ids_chunk = []
for e in encs:
if e.ids:
ids_chunk.extend(e.ids)
ids_chunk.append(eos_id)
if ids_chunk:
arr = np.asarray(ids_chunk, dtype=np_dtype)
rem = max_tokens - written
if arr.size > rem:
arr = arr[:rem]
f.write(arr.tobytes())
written += int(arr.size)
if written >= max_tokens:
break
if text_buf and written < max_tokens:
encs = tokenizer.encode_batch(text_buf)
ids_chunk = []
for e in encs:
if e.ids:
ids_chunk.extend(e.ids)
ids_chunk.append(eos_id)
if ids_chunk:
arr = np.asarray(ids_chunk, dtype=np_dtype)[: max_tokens - written]
f.write(arr.tobytes())
written += int(arr.size)
os.replace(tmp_path, out_path)
Path(prompts_path).write_text(json.dumps(val_prompts), encoding="utf-8")
dt_s = max(time.perf_counter() - t0, 1e-6)
print(f" Pretokenized {written:,d} tokens in {dt_s:.1f}s ({written / dt_s / 1e6:.2f}M tok/s).")
return written, np_dtype, val_prompts
def build_engram_canonical_map(tokenizer, vocab_size, device):
vocab = tokenizer.get_vocab()
id_to_token = {idx: tok for tok, idx in vocab.items() if idx < vocab_size}
canonical_to_id = {}
proj = torch.arange(vocab_size, dtype=torch.long)
for idx in range(vocab_size):
tok = id_to_token.get(idx, "")
clean = tok.replace("Ġ", " ").replace("▁", " ")
norm = unicodedata.normalize("NFKC", clean).lower().strip()
if not norm:
norm = tok
if norm not in canonical_to_id:
canonical_to_id[norm] = idx
proj[idx] = canonical_to_id[norm]
compression_ratio = 1.0 - (len(canonical_to_id) / max(vocab_size, 1))
return proj.to(device), len(canonical_to_id), compression_ratio
def _resolve_eos_id(tokenizer):
for cand in ("</s>", "<|endoftext|>", "[SEP]"):
tid = tokenizer.token_to_id(cand)
if tid is not None:
return tid
return 0
def collect_val_prompts(parquet_files, limit=8):
prompts = []
for path in parquet_files:
pf = pq.ParquetFile(path)
col = "text" if "text" in pf.schema.names else pf.schema.names[-1]
for rb in pf.iter_batches(batch_size=64, columns=[col]):
for t in rb.column(0).to_pylist():
if isinstance(t, str) and len(t) > 80:
snippet = " ".join(t.strip().split()[:24])
if len(snippet) > 30:
prompts.append(snippet)
if len(prompts) >= limit:
return prompts
return prompts
def pretokenize_parquet_to_bin(
parquet_files,
tokenizer,
vocab_size,
out_path=MEMMAP_BIN_PATH,
max_tokens=MEMMAP_MAX_TOKENS,
):
np_dtype = np.uint16 if vocab_size < 65536 else np.uint32
item_bytes = np.dtype(np_dtype).itemsize
if os.path.exists(out_path) and os.path.getsize(out_path) >= 1_000_000 * item_bytes:
n_tok = os.path.getsize(out_path) // item_bytes
return n_tok, np_dtype, collect_val_prompts(parquet_files)
os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
eos_id = _resolve_eos_id(tokenizer)
written = 0
val_prompts = []
t0 = time.perf_counter()
with open(out_path, "wb") as f:
for path in parquet_files:
pf = pq.ParquetFile(path)
col = "text" if "text" in pf.schema.names else pf.schema.names[-1]
for rb in pf.iter_batches(batch_size=1024, columns=[col]):
texts = [
t for t in rb.column(0).to_pylist()
if isinstance(t, str) and len(t) > 80
]
if not texts:
continue
if len(val_prompts) < 8:
for t in texts[:4]:
snippet = " ".join(t.strip().split()[:24])
if len(snippet) > 30 and len(val_prompts) < 8:
val_prompts.append(snippet)
ids = []
for enc in tokenizer.encode_batch(texts):
if len(enc.ids) > 16:
ids.extend(enc.ids)
ids.append(eos_id)
if not ids:
continue
arr = np.asarray(ids, dtype=np_dtype)
arr.tofile(f)
written += arr.size
if written >= max_tokens:
dt = time.perf_counter() - t0
print(
f" Pre-tokenized {written:,d} tokens ({np_dtype.__name__}) to {out_path} in {dt:.1f}s"
)
return written, np_dtype, val_prompts
dt = time.perf_counter() - t0
print(f" Pre-tokenized {written:,d} tokens ({np_dtype.__name__}) to {out_path} in {dt:.1f}s")
return written, np_dtype, val_prompts
class FastMemmapLoader:
"""Async background-threaded shuffled memmap loader with pinned H2D transfer."""
def __init__(
self,
bin_path,
np_dtype,
seq_len,
batch_size,
device,
extra_horizon=2,
val_prompts=None,
seed=42,
prefetch=4,
):
self.data = np.memmap(bin_path, dtype=np_dtype, mode="r")
self.seq_len = seq_len
self.batch_size = batch_size
self.device = device
self.extra_horizon = extra_horizon
self.span = seq_len + extra_horizon
self.pin_memory = device.type == "cuda"
self.val_prompts = val_prompts or []
self.val_reserve = min(VAL_RESERVE_TOKENS, len(self.data) // 10)
self.train_len = max(self.span + 1, len(self.data) - self.val_reserve)
self._rng = np.random.default_rng(seed)
self._queue = queue.Queue(maxsize=max(2, prefetch))
self._stop_event = threading.Event()
self._worker_error = None
self._thread = threading.Thread(
target=self._prefetch_loop, name="memmap-prefetch", daemon=True
)
self._thread.start()
def _prefetch_loop(self):
try:
n_seqs = max(1, (self.train_len - self.span) // self.span)
order = self._rng.permutation(n_seqs)
cursor = 0
while not self._stop_event.is_set():
if cursor + self.batch_size > n_seqs:
order = self._rng.permutation(n_seqs)
cursor = 0
seq_ids = order[cursor : cursor + self.batch_size]
cursor += self.batch_size
offsets = seq_ids * self.span
rows = np.stack(
[self.data[o : o + self.span] for o in offsets], axis=0
).astype(np.int64)
chunk = torch.from_numpy(rows)
if self.pin_memory:
chunk = chunk.pin_memory()
while not self._stop_event.is_set():
try:
self._queue.put(chunk, timeout=0.2)
break
except queue.Full:
continue
except Exception as exc:
self._worker_error = exc
def next_batch(self):
while True:
if self._worker_error is not None:
raise RuntimeError("Memmap prefetch worker failed") from self._worker_error
try:
chunk = self._queue.get(timeout=0.2)
break
except queue.Empty:
continue
arr = chunk.to(self.device, non_blocking=self.pin_memory)
return arr[:, : self.seq_len], [
arr[:, k : k + self.seq_len] for k in range(1, self.extra_horizon + 1)
]
def close(self):
self._stop_event.set()
while not self._queue.empty():
try:
self._queue.get_nowait()
except queue.Empty:
break
if self._thread.is_alive():
self._thread.join(timeout=2.0)
class WikipediaParquetStreamLoader:
"""Fallback background-threaded streaming token packer when memmap cache is disabled."""
def __init__(
self,
parquet_files,
tokenizer,
seq_len,
batch_size,
device,
extra_horizon=2,
prefetch_batches=PREFETCH_BATCHES,
):
self.parquet_files = parquet_files
self.tokenizer = tokenizer
self.seq_len = seq_len
self.batch_size = batch_size
self.device = device
self.extra_horizon = extra_horizon
self.pin_memory = device.type == "cuda"
self.eos_id = _resolve_eos_id(tokenizer)
self.token_buffer = []
self.val_prompts = []
self._file_idx = 0
self._batch_iter = None
self._text_col = None
span = self.seq_len + self.extra_horizon
self._fill_buffer(self.batch_size * span + 1024)
self._queue = queue.Queue(maxsize=max(2, prefetch_batches))
self._stop_event = threading.Event()
self._worker_error = None
self._thread = threading.Thread(
target=self._prefetch_loop, name="parquet-prefetch", daemon=True
)
self._thread.start()
def _open_next_file(self):
if not self.parquet_files:
return False
path = self.parquet_files[self._file_idx % len(self.parquet_files)]
self._file_idx += 1
pf = pq.ParquetFile(path)
cols = pf.schema.names
self._text_col = "text" if "text" in cols else cols[-1]
self._batch_iter = pf.iter_batches(batch_size=256, columns=[self._text_col])
return True
def _fill_buffer(self, min_tokens):
while len(self.token_buffer) < min_tokens:
if self._batch_iter is None:
if not self._open_next_file():
synth = torch.randint(10, 5000, (min_tokens,)).tolist()
self.token_buffer.extend(synth)
return
try:
record_batch = next(self._batch_iter)
except StopIteration:
self._batch_iter = None
continue
texts = [
t for t in record_batch.column(0).to_pylist()
if isinstance(t, str) and len(t) > 80
]
if not texts:
continue
if len(self.val_prompts) < 8:
for t in texts[:4]:
snippet = " ".join(t.strip().split()[:24])
if len(snippet) > 30 and len(self.val_prompts) < 8:
self.val_prompts.append(snippet)
encodings = self.tokenizer.encode_batch(texts)
for enc in encodings:
if len(enc.ids) > 16:
self.token_buffer.extend(enc.ids)
self.token_buffer.append(self.eos_id)
def _make_cpu_batch(self):
span = self.seq_len + self.extra_horizon
needed = self.batch_size * span
self._fill_buffer(needed + 1024)
chunk = self.token_buffer[:needed]
del self.token_buffer[:needed]
arr = torch.tensor(chunk, dtype=torch.long).view(self.batch_size, span)
if self.pin_memory:
arr = arr.pin_memory()
return arr
def _prefetch_loop(self):
try:
while not self._stop_event.is_set():
arr = self._make_cpu_batch()
while not self._stop_event.is_set():
try:
self._queue.put(arr, timeout=0.2)
break
except queue.Full:
continue
except Exception as exc:
self._worker_error = exc
def next_batch(self):
while True:
if self._worker_error is not None:
raise RuntimeError("Prefetch worker failed") from self._worker_error
try:
arr_cpu = self._queue.get(timeout=0.2)
break
except queue.Empty:
continue
arr = arr_cpu.to(self.device, non_blocking=self.pin_memory)
x = arr[:, : self.seq_len]
targets = [
arr[:, k : k + self.seq_len] for k in range(1, self.extra_horizon + 1)
]
return x, targets
def close(self):
self._stop_event.set()
while not self._queue.empty():
try:
self._queue.get_nowait()
except queue.Empty:
break
if self._thread.is_alive():
self._thread.join(timeout=2.0)
# ===================== COALESCED GDDR7 SPARSE GATHER & LAZY 8-BIT SPARSE ADAM
if _HAS_TRITON:
@triton.jit
def _triton_fp8_plain_lookup_kernel(
w_ptr, wscale_ptr, idx_ptr, out_ptr,
N, n_rows, D,
BLOCK_D: tl.constexpr,
USE_FP8: tl.constexpr,
):
"""1-pass coalesced FP8/BF16 plain embedding lookup with per-row FP32 w_scale."""
pid_n = tl.program_id(0)
if pid_n >= N:
return
tok_i64 = pid_n.to(tl.int64)
slot = tl.load(idx_ptr + tok_i64).to(tl.int64)
offs_d = tl.arange(0, BLOCK_D).to(tl.int64)
mask_d = offs_d < D
slot_ok = (slot >= 0) & (slot < n_rows)
val = tl.load(w_ptr + slot * D + offs_d, mask=mask_d & slot_ok, other=0.0).to(tl.float32)
if USE_FP8:
sc = tl.load(wscale_ptr + slot, mask=slot_ok, other=1.0).to(tl.float32)
val = val * sc
tl.store(out_ptr + tok_i64 * D + offs_d, val.to(tl.bfloat16), mask=mask_d)
def _sparse_plain_lookup_impl(weight, w_scale, flat_indices, use_fp8):
"""Fast FP8-aware or BF16 plain lookup returning [N, D] BF16."""
N = flat_indices.numel()
n_rows, D = weight.shape
if N == 0:
return torch.empty((0, D), device=weight.device, dtype=torch.bfloat16)
if use_fp8:
if _HAS_TRITON and weight.is_cuda and D <= 1024:
out = torch.empty((N, D), device=weight.device, dtype=torch.bfloat16)
block_d = 1 << (max(1, D) - 1).bit_length()
_triton_fp8_plain_lookup_kernel[(N,)](
weight.contiguous(), w_scale.contiguous(), flat_indices.contiguous(), out,
N, n_rows, D, BLOCK_D=block_d, USE_FP8=True,
num_warps=4 if block_d <= 256 else 8,
)
return out
idx_l = flat_indices.to(torch.long)
return (weight[idx_l].float() * w_scale[idx_l].unsqueeze(-1)).to(torch.bfloat16)
return F.embedding(flat_indices, weight)
class CoalescedSparseGatherFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, weight, w_scale, flat_indices, grad_buffer_list, grad_hook, use_fp8):
out = _sparse_plain_lookup_impl(weight, w_scale, flat_indices, use_fp8)
ctx.save_for_backward(flat_indices)
ctx.grad_buffer_list = grad_buffer_list
ctx.row_dim = weight.size(1)
return out
@staticmethod
def backward(ctx, grad_out):
(flat_indices,) = ctx.saved_tensors
ctx.grad_buffer_list.append(
(flat_indices.detach(), grad_out.reshape(-1, ctx.row_dim).detach())
)
return None, None, None, None, None, None
if _HAS_TRITON:
@triton.jit
def _triton_sparse_adam_rowv_kernel(
w_ptr, wscale_ptr, qm_ptr, msc_ptr, vrow_ptr, step_ptr,
uidx_ptr, g_ptr,
lr, b1, b2, log_b1, log_b2, eps, seed,
n_unique,
D: tl.constexpr,
STORE_FP8: tl.constexpr,
):
"""1-pass fused Triton Sparse Adam (FP8 E4M3 per-row w_scale OR BF16 SR + INT8 m + FP32 v_row)."""
pid = tl.program_id(0)
if pid >= n_unique:
return
row_id = tl.load(uidx_ptr + pid).to(tl.int64)
offs = tl.arange(0, D).to(tl.int64)
row_base = row_id * D + offs
g_base = pid.to(tl.int64) * D + offs
w_raw = tl.load(w_ptr + row_base).to(tl.float32)
if STORE_FP8:
w_sc = tl.load(wscale_ptr + row_id).to(tl.float32)
w = w_raw * w_sc
else:
w = w_raw
g = tl.load(g_ptr + g_base).to(tl.float32)
qm = tl.load(qm_ptr + row_base).to(tl.float32)
msc = tl.load(msc_ptr + row_id).to(tl.float32)
v_prev = tl.load(vrow_ptr + row_id).to(tl.float32)
cnt = tl.load(step_ptr + row_id) + 1
tl.store(step_ptr + row_id, cnt)
m_prev = qm * msc
m_new = b1 * m_prev + (1.0 - b1) * g
g2_mean = tl.sum(g * g, axis=0) / D
v_new = b2 * v_prev + (1.0 - b2) * g2_mean
cnt_f = cnt.to(tl.float32)
bc1 = 1.0 - tl.exp(cnt_f * log_b1)
bc2 = 1.0 - tl.exp(cnt_f * log_b2)
denom = tl.sqrt(v_new / bc2) + eps
w_new = w - lr * (m_new / bc1) / denom
# Unbiased Philox-4x32-7 stochastic rounding for FP8 E4M3 (per-row scaled) or BF16
r_bits = tl.randint(seed, row_base.to(tl.int32))
if STORE_FP8:
w_amax = tl.max(tl.abs(w_new), axis=0)
new_wsc = tl.maximum(w_amax / 448.0, 1e-12)
w_scaled = tl.minimum(tl.maximum(w_new / new_wsc, -448.0), 448.0)
u_rand = ((r_bits & 0xFFFF).to(tl.float32) / 65536.0) - 0.5
w_dither = tl.minimum(
tl.maximum(w_scaled + u_rand * tl.maximum(tl.abs(w_scaled) * 0.0625, 1e-4), -448.0),
448.0,
)
tl.store(w_ptr + row_base, w_dither.to(w_ptr.dtype.element_ty))
tl.store(wscale_ptr + row_id, new_wsc)
else:
noise = (r_bits & 0xFFFF).to(tl.int32)
w_bits = w_new.to(tl.int32, bitcast=True)
w_bf16 = ((w_bits + noise) & (-65536)).to(tl.float32, bitcast=True).to(tl.bfloat16)
tl.store(w_ptr + row_base, w_bf16)
m_absmax = tl.max(tl.abs(m_new), axis=0)
new_msc = tl.maximum(m_absmax / 127.0, 1e-12)
qm_f = tl.minimum(tl.maximum(tl.floor(m_new / new_msc + 0.5), -127.0), 127.0)
tl.store(qm_ptr + row_base, qm_f.to(tl.int8))
tl.store(msc_ptr + row_id, new_msc)
tl.store(vrow_ptr + row_id, v_new)
def _sparse_adam_math_rowwise_v(
w_active, g_sum, m_prev, v_row_prev, row_counts, lr_t, b1, b2, eps
):
"""Row-wise FP32 v_row sparse Adam fallback (-25% VRAM & GDDR7 IO, 0.00% v quant error)."""
m_new = b1 * m_prev + (1.0 - b1) * g_sum
v_row_new = b2 * v_row_prev + (1.0 - b2) * (g_sum * g_sum).mean(dim=-1)
bc1 = 1.0 - (b1 ** row_counts)
bc2 = 1.0 - (b2 ** row_counts.squeeze(-1))
denom = (v_row_new / bc2).sqrt().unsqueeze(-1) + eps
w_new = w_active - lr_t * (m_new / bc1) / denom
w_bf16 = stochastic_round_bf16(w_new)
m_sc = (m_new.abs().amax(dim=-1) / 127.0).clamp_min(1e-12)
qm_new = torch.clamp(torch.round(m_new / m_sc.unsqueeze(-1)), -127, 127).to(torch.int8)
return w_bf16, qm_new, m_sc, v_row_new
# ===================================================== CUSTOM TRITON KERNELS
_HAS_TORCH = True
HAS_TRITON = _HAS_TRITON
WINDOW_SIZE = GDN_CONV_KERNEL
DEFAULT_BLOCK_T = 64
NEG_INF_SCORE = -1e9
FP8_DTYPE = getattr(torch, 'float8_e4m3fn', None)
FP8_SCALE_EPS = 1e-12
def _is_power_of_two(x: int) -> bool:
return x > 0 and (x & (x - 1)) == 0
# --- Kernel Suite 1: UltraMemV2 Gather-Reduce + Compact Sparse Grad Coalescing ---
if _HAS_TRITON:
@triton.jit
def _triton_ultramem_gather_reduce_fwd(
weight_ptr,
wscale_ptr,
slots_ptr,
weights_ptr,
out_ptr,
N,
n_rows,
D,
M_TOTAL: tl.constexpr,
BLOCK_D: tl.constexpr,
OUT_BF16: tl.constexpr,
USE_FP8: tl.constexpr,
):
"""Fused gather + weighted reduction (FP8 per-row scaled or BF16):
v_agg[tok, d] = sum_{k=0..M-1} weights[tok, k] * (weight[slots[tok, k], d] * w_scale[slots[tok, k]]).
"""
pid_n = tl.program_id(0)
if pid_n >= N:
return
pid_d = tl.program_id(1)
tok_i64 = pid_n.to(tl.int64)
offs_d = pid_d.to(tl.int64) * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64)
mask_d = offs_d < D
tok_m_base = tok_i64 * M_TOTAL
acc = tl.zeros((BLOCK_D,), dtype=tl.float32)
for k in range(M_TOTAL):
slot = tl.load(slots_ptr + tok_m_base + k).to(tl.int64)
w_scalar = tl.load(weights_ptr + tok_m_base + k).to(tl.float32)
slot_ok = (slot >= 0) & (slot < n_rows)
valid = mask_d & slot_ok
# CRITICAL int64 addressing: slot (int64) * D + offs_d (int64) avoids int32 overflow (>2.14B)
row_offs = slot * D + offs_d
val = tl.load(weight_ptr + row_offs, mask=valid, other=0.0).to(tl.float32)
if USE_FP8:
sc = tl.load(wscale_ptr + slot, mask=slot_ok, other=1.0).to(tl.float32)
w_scalar = w_scalar * sc
acc += val * w_scalar
out_offs = tok_i64 * D + offs_d
if OUT_BF16:
tl.store(out_ptr + out_offs, acc.to(tl.bfloat16), mask=mask_d)
else:
tl.store(out_ptr + out_offs, acc, mask=mask_d)
@triton.jit
def _triton_ultramem_dweights_bwd(
weight_ptr,
wscale_ptr,
slots_ptr,
dv_agg_ptr,
dweights_ptr,
N,
n_rows,
D,
M_TOTAL: tl.constexpr,
BLOCK_D: tl.constexpr,
SINGLE_TILE: tl.constexpr,
OUT_BF16: tl.constexpr,
USE_FP8: tl.constexpr,
):
"""Fused routing-weight gradient (FP8 per-row scaled or BF16):
d_weights[tok, k] = sum_d(d_v_agg[tok, d] * weight[slots[tok, k], d] * w_scale[slots[tok, k]]).
"""
pid_n = tl.program_id(0)
if pid_n >= N:
return
tok_i64 = pid_n.to(tl.int64)
tok_d_base = tok_i64 * D
tok_m_base = tok_i64 * M_TOTAL
if SINGLE_TILE:
offs_d = tl.arange(0, BLOCK_D).to(tl.int64)
mask_d = offs_d < D
dv = tl.load(dv_agg_ptr + tok_d_base + offs_d, mask=mask_d, other=0.0).to(tl.float32)
for k in range(M_TOTAL):
slot = tl.load(slots_ptr + tok_m_base + k).to(tl.int64)
slot_ok = (slot >= 0) & (slot < n_rows)
valid = mask_d & slot_ok
row_offs = slot * D + offs_d
val = tl.load(weight_ptr + row_offs, mask=valid, other=0.0).to(tl.float32)
dot = tl.sum(dv * val, axis=0)
if USE_FP8:
sc = tl.load(wscale_ptr + slot, mask=slot_ok, other=1.0).to(tl.float32)
dot = dot * sc
if OUT_BF16:
tl.store(dweights_ptr + tok_m_base + k, dot.to(tl.bfloat16))
else:
tl.store(dweights_ptr + tok_m_base + k, dot)
else:
# General multi-tile path when D > BLOCK_D
for k in range(M_TOTAL):
slot = tl.load(slots_ptr + tok_m_base + k).to(tl.int64)
slot_ok = (slot >= 0) & (slot < n_rows)
dot = tl.zeros((), dtype=tl.float32)
d_start = 0
while d_start < D:
offs_d = tl.arange(0, BLOCK_D).to(tl.int64) + d_start
mask_d = offs_d < D
dv = tl.load(dv_agg_ptr + tok_d_base + offs_d, mask=mask_d, other=0.0).to(tl.float32)
val = tl.load(
weight_ptr + slot * D + offs_d,
mask=mask_d & slot_ok,
other=0.0,
).to(tl.float32)
dot += tl.sum(dv * val, axis=0)
d_start += BLOCK_D
if USE_FP8:
sc = tl.load(wscale_ptr + slot, mask=slot_ok, other=1.0).to(tl.float32)
dot = dot * sc
if OUT_BF16:
tl.store(dweights_ptr + tok_m_base + k, dot.to(tl.bfloat16))
else:
tl.store(dweights_ptr + tok_m_base + k, dot)
@triton.jit
def _triton_ultramem_scatter_grad(
inv_ptr,
weights_ptr,
dv_agg_ptr,
g_sum_ptr,
N,
n_unique,
D,
M_TOTAL: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""Fused compact sparse-grad coalescing:
g_sum[inv[tok, k], d] += weights[tok, k] * d_v_agg[tok, d] (in FP32).
Grid: (N, cdiv(D, BLOCK_D))
Loads d_v_agg[tok, :] ONCE into FP32 registers and scatters weighted contributions
directly into the coalesced FP32 unique-slot gradient buffer g_sum [n_unique, D],
completely avoiding materialization of [N, H, topK, D].
"""
pid_n = tl.program_id(0)
if pid_n >= N:
return
pid_d = tl.program_id(1)
tok_i64 = pid_n.to(tl.int64)
offs_d = pid_d.to(tl.int64) * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64)
mask_d = offs_d < D
tok_d_base = tok_i64 * D
tok_m_base = tok_i64 * M_TOTAL
dv = tl.load(dv_agg_ptr + tok_d_base + offs_d, mask=mask_d, other=0.0).to(tl.float32)
for k in range(M_TOTAL):
u_row = tl.load(inv_ptr + tok_m_base + k).to(tl.int64)
w_scalar = tl.load(weights_ptr + tok_m_base + k).to(tl.float32)
valid = mask_d & (u_row >= 0) & (u_row < n_unique)
g_offs = u_row * D + offs_d
tl.atomic_add(g_sum_ptr + g_offs, dv * w_scalar, mask=valid)
# =============================================================================
# 2. LAUNCHERS & MEMORY-LEAN PYTORCH FALLBACKS
# =============================================================================
def _next_pow2(n: int) -> int:
return 1 << (max(1, n) - 1).bit_length()
def _select_block_d(D: int) -> int:
return min(1024, _next_pow2(D))
def _ultramem_gather_reduce_fwd_impl(
weight: "torch.Tensor",
slots_2d: "torch.Tensor",
weights_2d: "torch.Tensor",
out_dtype: "torch.dtype",
chunk_tokens: int = 256,
w_scale: Optional["torch.Tensor"] = None,
) -> "torch.Tensor":
"""Forward dispatcher: Triton kernel on CUDA (FP8 per-row scaled or BF16), chunked fallback otherwise."""
N, M = slots_2d.shape
n_rows, D = weight.shape
use_fp8 = w_scale is not None
if N == 0:
return torch.empty((0, D), device=weight.device, dtype=out_dtype)
use_triton = (
_HAS_TRITON
and weight.is_cuda
and slots_2d.is_cuda
and weights_2d.is_cuda
and out_dtype in (torch.bfloat16, torch.float32)
)
if use_triton:
w_c = weight.contiguous()
wsc_c = w_scale.contiguous() if use_fp8 else weights_2d
s_c = slots_2d.contiguous()
wt_c = weights_2d.contiguous()
out = torch.empty((N, D), device=weight.device, dtype=out_dtype)
block_d = _select_block_d(D)
grid = (N, triton.cdiv(D, block_d))
_triton_ultramem_gather_reduce_fwd[grid](
w_c,
wsc_c,
s_c,
wt_c,
out,
N,
n_rows,
D,
M_TOTAL=M,
BLOCK_D=block_d,
OUT_BF16=(out_dtype == torch.bfloat16),
USE_FP8=use_fp8,
num_warps=8 if block_d >= 512 else 4,
)
return out
# Memory-lean chunked PyTorch fallback (avoids full [N, M, D] allocation when N is large)
out = torch.empty((N, D), device=weight.device, dtype=out_dtype)
for n0 in range(0, N, chunk_tokens):
n1 = min(N, n0 + chunk_tokens)
s_c = slots_2d[n0:n1].to(torch.long)
wt_c = weights_2d[n0:n1].float().unsqueeze(-1) # [C, M, 1]
if use_fp8:
vals_c = weight[s_c.reshape(-1)].float().view(n1 - n0, M, D)
sc_c = w_scale[s_c.reshape(-1)].view(n1 - n0, M, 1)
vals_c = vals_c * sc_c
else:
vals_c = F.embedding(s_c.reshape(-1), weight).view(n1 - n0, M, D).float()
out[n0:n1] = (vals_c * wt_c).sum(dim=1).to(out_dtype)
return out
def _ultramem_dweights_bwd_impl(
weight: "torch.Tensor",
slots_2d: "torch.Tensor",
dv_agg: "torch.Tensor",
out_dtype: "torch.dtype",
chunk_tokens: int = 256,
w_scale: Optional["torch.Tensor"] = None,
) -> "torch.Tensor":
"""Backward d_weights dispatcher: Triton kernel on CUDA (FP8 per-row scaled or BF16), chunked fallback otherwise."""
N, M = slots_2d.shape
n_rows, D = weight.shape
use_fp8 = w_scale is not None
if N == 0:
return torch.empty((0, M), device=weight.device, dtype=out_dtype)
use_triton = (
_HAS_TRITON
and weight.is_cuda
and slots_2d.is_cuda
and dv_agg.is_cuda
and out_dtype in (torch.bfloat16, torch.float32)
)
if use_triton:
w_c = weight.contiguous()
wsc_c = w_scale.contiguous() if use_fp8 else dv_agg
s_c = slots_2d.contiguous()
dv_c = dv_agg.contiguous()
d_weights = torch.empty((N, M), device=weight.device, dtype=out_dtype)
block_d = _select_block_d(D)
single_tile = D <= block_d
_triton_ultramem_dweights_bwd[(N,)](
w_c,
wsc_c,
s_c,
dv_c,
d_weights,
N,
n_rows,
D,
M_TOTAL=M,
BLOCK_D=block_d,
SINGLE_TILE=single_tile,
OUT_BF16=(out_dtype == torch.bfloat16),
USE_FP8=use_fp8,
num_warps=8 if block_d >= 512 else 4,
)
return d_weights
# Memory-lean chunked PyTorch fallback
d_weights = torch.empty((N, M), device=weight.device, dtype=out_dtype)
for n0 in range(0, N, chunk_tokens):
n1 = min(N, n0 + chunk_tokens)
s_c = slots_2d[n0:n1].to(torch.long)
dv_c = dv_agg[n0:n1].float().unsqueeze(1) # [C, 1, D]
if use_fp8:
vals_c = weight[s_c.reshape(-1)].float().view(n1 - n0, M, D)
sc_c = w_scale[s_c.reshape(-1)].view(n1 - n0, M, 1)
vals_c = vals_c * sc_c
else:
vals_c = F.embedding(s_c.reshape(-1), weight).view(n1 - n0, M, D).float()
d_weights[n0:n1] = (vals_c * dv_c).sum(dim=-1).to(out_dtype)
return d_weights
def coalesce_compact_sparse_grads(
grad_buffer: Sequence[Tuple["torch.Tensor", ...]],
dim: int,
device: Optional["torch.device"] = None,
chunk_tokens: int = 256,
) -> Tuple["torch.Tensor", "torch.Tensor"]:
"""Materialize coalesced `(u_idx, g_sum)` FP32 gradients from compact 3-tuples
`(slots [N, M], weights [N, M], d_v_agg [N, D])` AND/OR legacy 2-tuples `(flat_idx, grad_out)`.
Never allocates `[N_total, M, D]`. Uses `_triton_ultramem_scatter_grad` on CUDA+Triton
and a chunked `index_add_` fallback on CPU or without Triton.
"""
if not grad_buffer:
dev = device if device is not None else torch.device("cpu")
return (
torch.empty((0,), device=dev, dtype=torch.long),
torch.empty((0, dim), device=dev, dtype=torch.float32),
)
compact_entries: List[Tuple["torch.Tensor", "torch.Tensor", "torch.Tensor"]] = []
legacy_entries: List[Tuple["torch.Tensor", "torch.Tensor"]] = []
for item in grad_buffer:
if len(item) == 3:
compact_entries.append((item[0], item[1], item[2]))
elif len(item) == 2:
legacy_entries.append((item[0], item[1]))
else:
raise ValueError(f"Unsupported grad_buffer entry tuple length: {len(item)}")
# Gather all flat slot IDs once to compute a single global unique index map
flat_idx_parts: List["torch.Tensor"] = []
compact_counts: List[int] = []
for slots_2d, _, _ in compact_entries:
flat_s = slots_2d.reshape(-1).to(torch.long)
flat_idx_parts.append(flat_s)
compact_counts.append(flat_s.numel())
legacy_counts: List[int] = []
for flat_idx, _ in legacy_entries:
flat_s = flat_idx.reshape(-1).to(torch.long)
flat_idx_parts.append(flat_s)
legacy_counts.append(flat_s.numel())
all_idx = flat_idx_parts[0] if len(flat_idx_parts) == 1 else torch.cat(flat_idx_parts, dim=0)
dev = device if device is not None else all_idx.device
u_idx, inv = torch.unique(all_idx, return_inverse=True)
n_unique = u_idx.numel()
g_sum = torch.zeros((n_unique, dim), device=dev, dtype=torch.float32)
offset = 0
for (slots_2d, weights_2d, dv_agg), count in zip(compact_entries, compact_counts):
N, M = slots_2d.shape
inv_2d = inv[offset : offset + count].view(N, M)
offset += count
if N == 0:
continue
if _HAS_TRITON and g_sum.is_cuda and dv_agg.is_cuda and weights_2d.is_cuda:
block_d = _select_block_d(dim)
grid = (N, triton.cdiv(dim, block_d))
_triton_ultramem_scatter_grad[grid](
inv_2d.contiguous(),
weights_2d.contiguous(),
dv_agg.contiguous(),
g_sum,
N,
n_unique,
dim,
M_TOTAL=M,
BLOCK_D=block_d,
num_warps=8 if block_d >= 512 else 4,
)
else:
for n0 in range(0, N, chunk_tokens):
n1 = min(N, n0 + chunk_tokens)
inv_c = inv_2d[n0:n1].reshape(-1)
wt_c = weights_2d[n0:n1].float().unsqueeze(-1) # [C, M, 1]
dv_c = dv_agg[n0:n1].float().unsqueeze(1) # [C, 1, D]
contrib = (wt_c * dv_c).reshape(-1, dim)
g_sum.index_add_(0, inv_c, contrib)
for (_, grad_out), count in zip(legacy_entries, legacy_counts):
inv_seg = inv[offset : offset + count]
offset += count
if count > 0:
g_sum.index_add_(0, inv_seg, grad_out.reshape(-1, dim).float())
return u_idx, g_sum
# =============================================================================
# 3. PYTORCH AUTOGRAD WRAPPER & DROP-IN INTEGRATION HELPERS
# =============================================================================
if True:
class FusedUltraMemGatherReduceFunction(torch.autograd.Function):
"""Autograd wrapper fusing GDDR7 sparse gather + weighted reduction.
Forward inputs:
weight: [V, D] BF16/FP32 sparse table (e.g. [29_337_800, 512])
global_slots: [N, H, topK] (or [N, M]) int64/int32 slot indices
weights: [N, H, topK] (or [N, M]) BF16/FP32 routing weights
grad_buffer_list: GDDR7SparseTable.grad_buffer (or compact_grad_buffer), or None
grad_hook: optional 0-elem requires_grad tensor (used only if weights.requires_grad is False)
Forward output:
v_agg: [N, D] (same dtype as `weights`, typically BF16)
Backward:
- Computes `d_weights` via `_triton_ultramem_dweights_bwd` (zero [N, H, topK, D] materialization).
- Appends compact 3-tuple `(slots_i32_or_i64, weights_2d, d_v_agg)` (~4.75 MiB/block for N=4096)
to `grad_buffer_list` for coalesced update in `GDDR7SparseTable.sparse_adam_step`.
"""
@staticmethod
def forward(ctx, weight, global_slots, weights, grad_buffer_list, grad_hook, w_scale):
orig_weight_shape = weights.shape
N = orig_weight_shape[0]
M = weights.numel() // max(1, N)
slots_2d = global_slots.reshape(N, M)
weights_2d = weights.reshape(N, M)
out_dtype = weights.dtype
v_agg = _ultramem_gather_reduce_fwd_impl(
weight, slots_2d, weights_2d, out_dtype=out_dtype, w_scale=w_scale
)
# Store int32 slots when safe (29,337,800 < 2^31-1) to halve TBPTT buffer size for slots!
slots_saved = (
slots_2d.to(torch.int32)
if weight.size(0) <= 2_147_483_647
else slots_2d.to(torch.int64)
)
ctx.has_w_scale = w_scale is not None
if w_scale is not None:
ctx.save_for_backward(weight, slots_saved, weights_2d, w_scale)
else:
ctx.save_for_backward(weight, slots_saved, weights_2d)
ctx.orig_weight_shape = orig_weight_shape
ctx.weights_dtype = weights.dtype
ctx.grad_buffer_list = grad_buffer_list
return v_agg
@staticmethod
def backward(ctx, d_v_agg):
if ctx.has_w_scale:
weight, slots_saved, weights_2d, w_scale = ctx.saved_tensors
else:
weight, slots_saved, weights_2d = ctx.saved_tensors
w_scale = None
dv_c = d_v_agg.contiguous()
# 1. Compact sparse gradient buffering for GDDR7SparseTable (no [N, H, topK, D]!)
d_weight = None
if ctx.grad_buffer_list is not None:
ctx.grad_buffer_list.append(
(slots_saved.detach(), weights_2d.detach(), dv_c.detach())
)
elif ctx.needs_input_grad[0]:
# Standalone autograd fallback (e.g. unit testing / gradcheck without GDDR7SparseTable)
u_idx, g_sum = coalesce_compact_sparse_grads(
[(slots_saved, weights_2d, dv_c)], dim=weight.size(1), device=weight.device
)
d_weight = torch.zeros_like(weight, dtype=torch.float32)
d_weight.index_add_(0, u_idx, g_sum)
d_weight = d_weight.to(weight.dtype)
# 2. Fused routing-weight gradient d_weights [N, H, topK]
d_weights = None
if ctx.needs_input_grad[2]:
d_weights_2d = _ultramem_dweights_bwd_impl(
weight, slots_saved, dv_c, out_dtype=ctx.weights_dtype, w_scale=w_scale
)
d_weights = d_weights_2d.view(ctx.orig_weight_shape)
return d_weight, None, d_weights, None, None, None
def fused_ultramem_gather_reduce(
weight: "torch.Tensor",
global_slots: "torch.Tensor",
weights: "torch.Tensor",
grad_buffer_list: Optional[list] = None,
w_scale: Optional["torch.Tensor"] = None,
) -> "torch.Tensor":
"""Public entry point matching `GDDR7SparseTable` + `UltraMemV2TDQKRBridge`.
Drop-in replacement in `UltraMemV2TDQKRBridge.forward_flat`:
# Before (materialized 134 MB [N, 2, 16, 512] intermediate!):
# vals = self.sparse_table.lookup(global_slots)
# v_agg = (vals * weights.unsqueeze(-1)).sum(dim=(1, 2))
#
# After (fused in registers, 4 MB output + ~4.75 MB compact grad buffer):
# v_agg = fused_ultramem_gather_reduce(
# self.sparse_table.weight, global_slots, weights, self.sparse_table.grad_buffer
# )
"""
if not _HAS_TORCH:
raise RuntimeError("PyTorch is required to call fused_ultramem_gather_reduce.")
if not torch.is_grad_enabled():
N = weights.shape[0]
M = weights.numel() // max(1, N)
return _ultramem_gather_reduce_fwd_impl(
weight, global_slots.reshape(N, M), weights.reshape(N, M),
out_dtype=weights.dtype, w_scale=w_scale,
)
grad_hook = None
if grad_buffer_list is not None and not weights.requires_grad:
grad_hook = torch.empty(0, device=weight.device, requires_grad=True)
return FusedUltraMemGatherReduceFunction.apply(
weight, global_slots, weights, grad_buffer_list, grad_hook, w_scale
)
def patch_gddr7_sparse_table(table) -> None:
"""Optional runtime helper to attach `lookup_and_reduce` and compact-grad `sparse_adam_step`
support to an existing `GDDR7SparseTable` instance without modifying its `__init__`.
Inside `GDDR7SparseTable.sparse_adam_step`, replace lines 1056-1067 with:
u_idx, g_sum = coalesce_compact_sparse_grads(self.grad_buffer, self.dim, device=self.device)
self.grad_buffer.clear()
Everything downstream (visited_mask, grad norm clip, `_triton_sparse_adam_rowv_kernel`) stays identical!
"""
import types
def lookup_and_reduce(self, global_slots, weights):
return fused_ultramem_gather_reduce(
self.weight, global_slots, weights, self.grad_buffer
)
table.lookup_and_reduce = types.MethodType(lookup_and_reduce, table)
# --- Kernel Suite 2: TDQKR Tucker-TopK + OrthoInj-ZOH ---
if _HAS_TRITON:
@triton.jit
def _tdqkr_tucker_topk_fwd_kernel(
sr_ptr,
sc_ptr,
g_ptr,
inv_temp_ptr,
top_scores_ptr,
sub_r_ptr,
sub_c_ptr,
weights_ptr,
# Input strides
stride_sr_n,
stride_sr_h,
stride_sr_r,
stride_sr_k,
stride_sc_n,
stride_sc_h,
stride_sc_r,
stride_sc_k,
stride_g_h,
stride_g_r,
stride_g_s,
stride_it_h,
# Output strides
stride_out_n,
stride_out_h,
stride_out_k,
# Runtime dimensions
H,
# Compile-time power-of-2 constants
R: tl.constexpr,
K0: tl.constexpr,
K0_SQ: tl.constexpr,
TOPK: tl.constexpr,
):
"""One program per (n, h) pair.
Computes S[i, j] = sum_{r, s} sr[n, h, r, i] * G[h, r, s] * sc[n, h, s, j]
strictly in registers without writing [N, H, K0, K0] to GDDR7, selects the
exact top-TOPK entries via iterative argmax, computes FP32 softmax(top * inv_temp),
and writes only [N, H, TOPK] outputs.
"""
pid = tl.program_id(0)
n = pid // H
h = pid % H
n_i64 = n.to(tl.int64)
h_i64 = h.to(tl.int64)
offs_k0 = tl.arange(0, K0)
offs_k0_i64 = offs_k0.to(tl.int64)
sr_base = n_i64 * stride_sr_n + h_i64 * stride_sr_h
sc_base = n_i64 * stride_sc_n + h_i64 * stride_sc_h
g_base = h_i64 * stride_g_h
# Compute S = (sr^T @ G) @ sc in FP32 registers via static rank unrolling.
# Avoids tl.dot minimum-tile (>=16) restrictions for R=4 and avoids
# materializing any [R, K0, K0] intermediate tensor.
s_grid = tl.zeros([K0, K0], dtype=tl.float32)
for s in tl.static_range(R):
sc_s = tl.load(
sc_ptr + sc_base + s * stride_sc_r + offs_k0_i64 * stride_sc_k
).to(tl.float32)
m_s = tl.zeros([K0], dtype=tl.float32)
for r in tl.static_range(R):
sr_r = tl.load(
sr_ptr + sr_base + r * stride_sr_r + offs_k0_i64 * stride_sr_k
).to(tl.float32)
g_rs = tl.load(g_ptr + g_base + r * stride_g_r + s * stride_g_s).to(
tl.float32
)
m_s += sr_r * g_rs
s_grid += m_s[:, None] * sc_s[None, :]
# Flatten [K0, K0] -> [K0_SQ] (1024) in registers and run exact top-K selection.
s_work = tl.reshape(s_grid, [K0_SQ])
offs_flat = tl.arange(0, K0_SQ)
offs_top = tl.arange(0, TOPK)
neg_inf = tl.full([K0_SQ], float("-inf"), dtype=tl.float32)
top_vals = tl.zeros([TOPK], dtype=tl.float32)
top_idxs = tl.zeros([TOPK], dtype=tl.int32)
for k in tl.static_range(TOPK):
val = tl.max(s_work, axis=0)
idx = tl.argmax(s_work, axis=0).to(tl.int32)
top_vals = tl.where(offs_top == k, val, top_vals)
top_idxs = tl.where(offs_top == k, idx, top_idxs)
s_work = tl.where(offs_flat == idx, neg_inf, s_work)
# Decode 2D coordinates inside the K0 x K0 candidate grid.
sub_r = (top_idxs // K0).to(tl.int64)
sub_c = (top_idxs % K0).to(tl.int64)
# Numerically stable FP32 softmax over top-K scores.
inv_temp_val = tl.load(inv_temp_ptr + h_i64 * stride_it_h).to(tl.float32)
scaled = top_vals * inv_temp_val
max_scaled = tl.max(scaled, axis=0)
exps = tl.exp(scaled - max_scaled)
denom = tl.sum(exps, axis=0)
weights = exps / denom
# Coalesced 16-element vector stores to GDDR7.
out_base = n_i64 * stride_out_n + h_i64 * stride_out_h
out_offs = out_base + offs_top.to(tl.int64) * stride_out_k
tl.store(top_scores_ptr + out_offs, top_vals)
tl.store(sub_r_ptr + out_offs, sub_r)
tl.store(sub_c_ptr + out_offs, sub_c)
tl.store(weights_ptr + out_offs, weights)
@triton.jit
def _orthoinj_zoh_fwd_kernel(
x_ptr,
a_ptr,
lam_ptr,
g_ptr,
x_out_ptr,
p_out_ptr,
q_norm2_out_ptr,
stride_x_n,
stride_a_n,
stride_out_n,
D,
eps,
BLOCK_D: tl.constexpr,
):
"""Single-pass OrthoInj + ZOH forward kernel (one program per token row).
Loads x, a, lam, g once into registers, computes FP32 reductions for
p = sum(lx * q) / (sum(q^2) + eps), writes x_out = (lx - p * q) + q,
and saves scalar (p, q_norm2) for single-pass backward.
"""
row = tl.program_id(0)
row_i64 = row.to(tl.int64)
offs = tl.arange(0, BLOCK_D)
offs_i64 = offs.to(tl.int64)
mask = offs < D
x = tl.load(x_ptr + row_i64 * stride_x_n + offs_i64, mask=mask, other=0.0).to(
tl.float32
)
a = tl.load(a_ptr + row_i64 * stride_a_n + offs_i64, mask=mask, other=0.0).to(
tl.float32
)
lam = tl.load(lam_ptr + offs_i64, mask=mask, other=0.0).to(tl.float32)
g = tl.load(g_ptr + offs_i64, mask=mask, other=0.0).to(tl.float32)
q = g * a
lx = lam * x
num = tl.sum(lx * q, axis=0)
q_norm2 = tl.sum(q * q, axis=0)
p = num / (q_norm2 + eps)
x_out = (lx - p * q) + q
tl.store(x_out_ptr + row_i64 * stride_out_n + offs_i64, x_out.to(x_out_ptr.dtype.element_ty), mask=mask)
tl.store(p_out_ptr + row_i64, p)
tl.store(q_norm2_out_ptr + row_i64, q_norm2)
@triton.jit
def _orthoinj_zoh_bwd_kernel(
dy_ptr,
x_ptr,
a_ptr,
lam_ptr,
g_ptr,
p_ptr,
q_norm2_ptr,
dx_ptr,
da_ptr,
dlam_ptr,
dg_ptr,
stride_dy_n,
stride_x_n,
stride_a_n,
stride_dx_n,
stride_da_n,
N,
D,
eps,
BLOCK_D: tl.constexpr,
):
"""Single-pass persistent-grid OrthoInj + ZOH backward kernel.
Each program loads lam and g once into registers, strides across rows
computing exact dx, da in one pass per row, accumulates partial dlam and dg
in FP32 registers, and performs a single atomic_add per program at exit.
"""
pid = tl.program_id(0)
num_pids = tl.num_programs(0)
offs = tl.arange(0, BLOCK_D)
offs_i64 = offs.to(tl.int64)
mask = offs < D
lam = tl.load(lam_ptr + offs_i64, mask=mask, other=0.0).to(tl.float32)
g = tl.load(g_ptr + offs_i64, mask=mask, other=0.0).to(tl.float32)
acc_dlam = tl.zeros([BLOCK_D], dtype=tl.float32)
acc_dg = tl.zeros([BLOCK_D], dtype=tl.float32)
for row in range(pid, N, num_pids):
row_i64 = row.to(tl.int64)
dy = tl.load(
dy_ptr + row_i64 * stride_dy_n + offs_i64, mask=mask, other=0.0
).to(tl.float32)
x = tl.load(
x_ptr + row_i64 * stride_x_n + offs_i64, mask=mask, other=0.0
).to(tl.float32)
a = tl.load(
a_ptr + row_i64 * stride_a_n + offs_i64, mask=mask, other=0.0
).to(tl.float32)
p = tl.load(p_ptr + row_i64).to(tl.float32)
q_norm2 = tl.load(q_norm2_ptr + row_i64).to(tl.float32)
q = g * a
lx = lam * x
denom = q_norm2 + eps
dy_dot_q = tl.sum(dy * q, axis=0)
alpha = -dy_dot_q / denom
dlx = dy + alpha * q
dq = (1.0 - p) * dy + alpha * (lx - 2.0 * p * q)
dx = dlx * lam
da = dq * g
tl.store(dx_ptr + row_i64 * stride_dx_n + offs_i64, dx.to(dx_ptr.dtype.element_ty), mask=mask)
tl.store(da_ptr + row_i64 * stride_da_n + offs_i64, da.to(da_ptr.dtype.element_ty), mask=mask)
acc_dlam += dlx * x
acc_dg += dq * a
tl.atomic_add(dlam_ptr + offs_i64, acc_dlam, mask=mask)
tl.atomic_add(dg_ptr + offs_i64, acc_dg, mask=mask)
# =============================================================================
# 2. PYTORCH FALLBACKS & AUTOGRAD FUNCTIONS
# =============================================================================
if True:
def _tdqkr_tucker_topk_fwd_pytorch(
sr_sub: torch.Tensor,
sc_sub: torch.Tensor,
tucker_core: torch.Tensor,
inv_temp: torch.Tensor,
topk: int = 16,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Reference PyTorch forward for `fused_tdqkr_tucker_topk`."""
sr_f = sr_sub.float()
sc_f = sc_sub.float()
g_f = tucker_core.float()
it_f = inv_temp.float()
N, H, _R, K0 = sr_f.shape
# M[n, h, i, s] = sum_r sr[n, h, r, i] * G[h, r, s]
# S[n, h, i, j] = sum_s M[n, h, i, s] * sc[n, h, s, j]
s_grid = torch.einsum("nhri,hrs,nhsj->nhij", sr_f, g_f, sc_f)
top_scores, flat_idx = torch.topk(
s_grid.reshape(N, H, K0 * K0), k=topk, dim=-1
)
sub_r = (flat_idx // K0).to(torch.int64)
sub_c = (flat_idx % K0).to(torch.int64)
weights = F.softmax(top_scores * it_f, dim=-1)
return top_scores, sub_r, sub_c, weights
def _tdqkr_tucker_topk_bwd_sparse_pytorch(
sr_sub: torch.Tensor,
sc_sub: torch.Tensor,
tucker_core: torch.Tensor,
inv_temp: torch.Tensor,
top_scores: torch.Tensor,
sub_r: torch.Tensor,
sub_c: torch.Tensor,
weights: torch.Tensor,
grad_top_scores: Optional[torch.Tensor],
grad_weights: Optional[torch.Tensor],
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Exact sparse backward strictly over the topK selected (sub_r, sub_c) pairs.
Performs 64x less compute than dense [N, H, 32, 32] backward for K0=32, topK=16.
"""
sr_f = sr_sub.float()
sc_f = sc_sub.float()
g_f = tucker_core.float()
it_f = inv_temp.float()
N, H, R, K0 = sr_f.shape
K = top_scores.shape[-1]
g_top = torch.zeros_like(top_scores, dtype=torch.float32)
if grad_top_scores is not None:
g_top = g_top + grad_top_scores.float()
d_inv_temp = torch.zeros_like(it_f, dtype=torch.float32)
if grad_weights is not None:
gw = grad_weights.float()
w = weights.float()
dot = (gw * w).sum(dim=-1, keepdim=True)
dz = w * (gw - dot)
g_top = g_top + dz * it_f
d_inv_temp = (dz * top_scores.float()).sum(dim=(0, 2)).view(1, H, 1)
# Gather selected row & col rank vectors: [N, H, R, K] -> [N, H, K, R]
idx_r_exp = sub_r.unsqueeze(2).expand(N, H, R, K)
idx_c_exp = sub_c.unsqueeze(2).expand(N, H, R, K)
u = torch.gather(sr_f, dim=-1, index=idx_r_exp).transpose(-1, -2) # [N, H, K, R]
v = torch.gather(sc_f, dim=-1, index=idx_c_exp).transpose(-1, -2) # [N, H, K, R]
# Sparse gradients over only K=16 active pairs:
# du[n, h, k, r] = g_top[n, h, k] * sum_s G[h, r, s] * v[n, h, k, s]
# dv[n, h, k, s] = g_top[n, h, k] * sum_r u[n, h, k, r] * G[h, r, s]
# dG[h, r, s] = sum_{n, k} g_top[n, h, k] * u[n, h, k, r] * v[n, h, k, s]
gv = torch.einsum("hrs,nhks->nhkr", g_f, v)
ug = torch.einsum("nhkr,hrs->nhks", u, g_f)
du = (g_top.unsqueeze(-1) * gv).transpose(-1, -2) # [N, H, R, K]
dv = (g_top.unsqueeze(-1) * ug).transpose(-1, -2) # [N, H, R, K]
d_sr_sub = torch.zeros_like(sr_f)
d_sc_sub = torch.zeros_like(sc_f)
d_sr_sub.scatter_add_(dim=-1, index=idx_r_exp, src=du)
d_sc_sub.scatter_add_(dim=-1, index=idx_c_exp, src=dv)
d_tucker_core = torch.einsum("nhk,nhkr,nhks->hrs", g_top, u, v)
return (
d_sr_sub.to(sr_sub.dtype),
d_sc_sub.to(sc_sub.dtype),
d_tucker_core.to(tucker_core.dtype),
d_inv_temp.to(inv_temp.dtype),
)
class _FusedTDQKRTuckerTopKFn(torch.autograd.Function):
@staticmethod
def forward(
ctx,
sr_sub: torch.Tensor,
sc_sub: torch.Tensor,
tucker_core: torch.Tensor,
inv_temp: torch.Tensor,
topk: int,
):
N, H, R, K0 = sr_sub.shape
use_triton = (
_HAS_TRITON
and sr_sub.is_cuda
and sc_sub.is_cuda
and tucker_core.is_cuda
and inv_temp.is_cuda
and _is_power_of_two(R)
and _is_power_of_two(K0)
and _is_power_of_two(topk)
and topk <= K0 * K0
)
if use_triton:
sr_c = sr_sub.contiguous().float()
sc_c = sc_sub.contiguous().float()
g_c = tucker_core.contiguous().float()
it_c = inv_temp.contiguous().float()
top_scores = torch.empty(
(N, H, topk), device=sr_c.device, dtype=torch.float32
)
sub_r = torch.empty((N, H, topk), device=sr_c.device, dtype=torch.int64)
sub_c = torch.empty((N, H, topk), device=sr_c.device, dtype=torch.int64)
weights = torch.empty(
(N, H, topk), device=sr_c.device, dtype=torch.float32
)
grid = (N * H,)
_tdqkr_tucker_topk_fwd_kernel[grid](
sr_c,
sc_c,
g_c,
it_c,
top_scores,
sub_r,
sub_c,
weights,
sr_c.stride(0),
sr_c.stride(1),
sr_c.stride(2),
sr_c.stride(3),
sc_c.stride(0),
sc_c.stride(1),
sc_c.stride(2),
sc_c.stride(3),
g_c.stride(0),
g_c.stride(1),
g_c.stride(2),
it_c.stride(1),
top_scores.stride(0),
top_scores.stride(1),
top_scores.stride(2),
H,
R=R,
K0=K0,
K0_SQ=K0 * K0,
TOPK=topk,
num_warps=4,
)
else:
top_scores, sub_r, sub_c, weights = _tdqkr_tucker_topk_fwd_pytorch(
sr_sub, sc_sub, tucker_core, inv_temp, topk=topk
)
ctx.save_for_backward(
sr_sub, sc_sub, tucker_core, inv_temp, top_scores, sub_r, sub_c, weights
)
ctx.mark_non_differentiable(sub_r, sub_c)
return top_scores, sub_r, sub_c, weights
@staticmethod
def backward(ctx, grad_top_scores, grad_sub_r, grad_sub_c, grad_weights):
(
sr_sub,
sc_sub,
tucker_core,
inv_temp,
top_scores,
sub_r,
sub_c,
weights,
) = ctx.saved_tensors
d_sr, d_sc, d_g, d_it = _tdqkr_tucker_topk_bwd_sparse_pytorch(
sr_sub,
sc_sub,
tucker_core,
inv_temp,
top_scores,
sub_r,
sub_c,
weights,
grad_top_scores,
grad_weights,
)
return d_sr, d_sc, d_g, d_it, None
def fused_tdqkr_tucker_topk(
sr_sub: torch.Tensor,
sc_sub: torch.Tensor,
tucker_core: torch.Tensor,
inv_temp: torch.Tensor,
topk: int = 16,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Fused Tucker score grid + exact top-K + softmax with sparse 64x-faster backward.
Args:
sr_sub: [N, H, R, cand_k0] FP32 (locked-in: [N, 2, 4, 32])
sc_sub: [N, H, R, cand_k0] FP32 (locked-in: [N, 2, 4, 32])
tucker_core: [H, R, R] FP32 (locked-in: [2, 4, 4])
inv_temp: [1, H, 1] FP32 (locked-in: [1, 2, 1])
topk: number of top slots to select (locked-in: 16)
Returns:
(top_scores [N, H, topk], sub_r [N, H, topk], sub_c [N, H, topk], weights [N, H, topk])
"""
return _FusedTDQKRTuckerTopKFn.apply(
sr_sub, sc_sub, tucker_core, inv_temp, topk
)
def _orthoinj_zoh_fwd_pytorch(
x: torch.Tensor,
a: torch.Tensor,
lam: torch.Tensor,
g: torch.Tensor,
eps: float = EPS_DEFAULT,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Reference PyTorch forward for `fused_orthoinj_zoh`."""
x_f = x.float()
a_f = a.float()
lam_f = lam.float()
g_f = g.float()
q = g_f * a_f
lx = lam_f * x_f
num = (lx * q).sum(dim=-1, keepdim=True)
q_norm2 = (q * q).sum(dim=-1, keepdim=True)
p = num / (q_norm2 + eps)
x_out = (lx - p * q) + q
return x_out.to(x.dtype), p.squeeze(-1), q_norm2.squeeze(-1)
def _orthoinj_zoh_bwd_pytorch(
dy: torch.Tensor,
x: torch.Tensor,
a: torch.Tensor,
lam: torch.Tensor,
g: torch.Tensor,
p: torch.Tensor,
q_norm2: torch.Tensor,
eps: float = EPS_DEFAULT,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Reference PyTorch backward for `fused_orthoinj_zoh`."""
dy_f = dy.float()
x_f = x.float()
a_f = a.float()
lam_f = lam.float()
g_f = g.float()
p_f = p.float().unsqueeze(-1)
denom = q_norm2.float().unsqueeze(-1) + eps
q = g_f * a_f
lx = lam_f * x_f
dy_dot_q = (dy_f * q).sum(dim=-1, keepdim=True)
alpha = -dy_dot_q / denom
dlx = dy_f + alpha * q
dq = (1.0 - p_f) * dy_f + alpha * (lx - 2.0 * p_f * q)
dx = (dlx * lam_f).to(x.dtype)
da = (dq * g_f).to(a.dtype)
dlam = (dlx * x_f).sum(dim=0).to(lam.dtype)
dg = (dq * a_f).sum(dim=0).to(g.dtype)
return dx, da, dlam, dg
class _FusedOrthoInjZOHFn(torch.autograd.Function):
@staticmethod
def forward(
ctx,
x: torch.Tensor,
a: torch.Tensor,
lam: torch.Tensor,
g: torch.Tensor,
eps: float,
):
orig_shape = x.shape
D = orig_shape[-1]
x_2d = x.reshape(-1, D).contiguous()
a_2d = a.reshape(-1, D).contiguous()
lam_c = lam.contiguous().float()
g_c = g.contiguous().float()
N = x_2d.shape[0]
use_triton = (
_HAS_TRITON
and x_2d.is_cuda
and a_2d.is_cuda
and lam_c.is_cuda
and g_c.is_cuda
and D <= 4096
)
if use_triton:
block_d = triton.next_power_of_2(D)
x_out_2d = torch.empty_like(x_2d)
p_out = torch.empty((N,), device=x_2d.device, dtype=torch.float32)
q_norm2_out = torch.empty((N,), device=x_2d.device, dtype=torch.float32)
_orthoinj_zoh_fwd_kernel[(N,)](
x_2d,
a_2d,
lam_c,
g_c,
x_out_2d,
p_out,
q_norm2_out,
x_2d.stride(0),
a_2d.stride(0),
x_out_2d.stride(0),
D,
float(eps),
BLOCK_D=block_d,
num_warps=4,
)
else:
x_out_2d, p_out, q_norm2_out = _orthoinj_zoh_fwd_pytorch(
x_2d, a_2d, lam_c, g_c, eps=eps
)
ctx.save_for_backward(x_2d, a_2d, lam_c, g_c, p_out, q_norm2_out)
ctx.orig_shape = orig_shape
ctx.eps = float(eps)
ctx.use_triton = use_triton
ctx.lam_dtype = lam.dtype
ctx.g_dtype = g.dtype
return x_out_2d.view(orig_shape)
@staticmethod
def backward(ctx, grad_output):
x_2d, a_2d, lam_c, g_c, p_out, q_norm2_out = ctx.saved_tensors
orig_shape = ctx.orig_shape
D = orig_shape[-1]
N = x_2d.shape[0]
dy_2d = grad_output.reshape(-1, D).contiguous()
if ctx.use_triton and _HAS_TRITON and dy_2d.is_cuda:
block_d = triton.next_power_of_2(D)
dx_2d = torch.empty_like(x_2d)
da_2d = torch.empty_like(a_2d)
dlam = torch.zeros((D,), device=x_2d.device, dtype=torch.float32)
dg = torch.zeros((D,), device=x_2d.device, dtype=torch.float32)
num_progs = min(N, 128) if N > 0 else 1
_orthoinj_zoh_bwd_kernel[(num_progs,)](
dy_2d,
x_2d,
a_2d,
lam_c,
g_c,
p_out,
q_norm2_out,
dx_2d,
da_2d,
dlam,
dg,
dy_2d.stride(0),
x_2d.stride(0),
a_2d.stride(0),
dx_2d.stride(0),
da_2d.stride(0),
N,
D,
ctx.eps,
BLOCK_D=block_d,
num_warps=4,
)
dlam = dlam.to(ctx.lam_dtype)
dg = dg.to(ctx.g_dtype)
else:
dx_2d, da_2d, dlam, dg = _orthoinj_zoh_bwd_pytorch(
dy_2d, x_2d, a_2d, lam_c, g_c, p_out, q_norm2_out, eps=ctx.eps
)
dlam = dlam.to(ctx.lam_dtype)
dg = dg.to(ctx.g_dtype)
return dx_2d.view(orig_shape), da_2d.view(orig_shape), dlam, dg, None
def fused_orthoinj_zoh(
x: torch.Tensor,
a: torch.Tensor,
lam: torch.Tensor,
g: torch.Tensor,
eps: float = EPS_DEFAULT,
) -> torch.Tensor:
"""Fused single-pass OrthoInj + Parcae ZOH forward and backward.
Computes:
q = g * a
lx = lam * x
p = sum(lx * q) / (sum(q^2) + eps)
x_out = (lx - p * q) + q
Args:
x: [..., D] stream activations (D=1024 for Block 0)
a: [..., D] anchor activations
lam: [D] FP32 precomputed exp(-softplus(zoh_log_decay))
g: [D] FP32 precomputed sigmoid(anchor_gate)
eps: numerical stability epsilon (default 1e-6)
Returns:
x_out with same shape and dtype as `x`.
"""
return _FusedOrthoInjZOHFn.apply(x, a, lam, g, eps)
# =============================================================================
# --- Kernel Suite 3: Pre-RoPE MoLA Online-Softmax Merge ---
if _HAS_TRITON:
@triton.jit
def _triton_mola_online_merge_fwd(
o_tok_ptr,
lse_tok_ptr,
q_ptr,
k_mem_ptr,
v_mem_ptr,
beta_ptr,
out_ptr,
lse_mem_ptr,
# Strides for o_tok [B, H, T, D]
s_ot_b, s_ot_h, s_ot_t, s_ot_d,
# Strides for lse_tok [B, H, T]
s_lt_b, s_lt_h, s_lt_t,
# Strides for q_normed [B, H, T, D]
s_q_b, s_q_h, s_q_t, s_q_d,
# Strides for k_mem_n [H, M, D]
s_km_h, s_km_m, s_km_d,
# Strides for v_mem [H, M, D]
s_vm_h, s_vm_m, s_vm_d,
# Strides for out [B, H, T, D]
s_out_b, s_out_h, s_out_t, s_out_d,
# Strides for lse_mem [B, H, T]
s_lm_b, s_lm_h, s_lm_t,
# Dimensions
H,
T,
# Compile-time constants (strict power-of-2 + scalar constexpr)
SCALE: tl.constexpr,
BLOCK_T: tl.constexpr,
HEAD_DIM: tl.constexpr,
M_MOLA: tl.constexpr,
INPUT_PRECISION: tl.constexpr,
):
"""Fused MoLA forward + online-softmax merge for one (b, h, t_tile)."""
pid_t = tl.program_id(0)
pid_bh = tl.program_id(1)
b = pid_bh // H
h = pid_bh % H
offs_t = pid_t * BLOCK_T + tl.arange(0, BLOCK_T)
offs_d = tl.arange(0, HEAD_DIM)
offs_m = tl.arange(0, M_MOLA)
t_mask = offs_t < T
# Load per-head MoLA memory keys/values/bias once into registers
km_ptrs = k_mem_ptr + h * s_km_h + offs_m[:, None] * s_km_m + offs_d[None, :] * s_km_d
vm_ptrs = v_mem_ptr + h * s_vm_h + offs_m[:, None] * s_vm_m + offs_d[None, :] * s_vm_d
k_mem = tl.load(km_ptrs) # [M_MOLA, HEAD_DIM]
v_mem = tl.load(vm_ptrs) # [M_MOLA, HEAD_DIM]
beta_h = tl.load(beta_ptr + h).to(tl.float32) # scalar FP32
# Load token tile: q_normed [BLOCK_T, HEAD_DIM], o_tok [BLOCK_T, HEAD_DIM], lse_tok [BLOCK_T]
q_ptrs = q_ptr + b * s_q_b + h * s_q_h + offs_t[:, None] * s_q_t + offs_d[None, :] * s_q_d
ot_ptrs = o_tok_ptr + b * s_ot_b + h * s_ot_h + offs_t[:, None] * s_ot_t + offs_d[None, :] * s_ot_d
lt_ptrs = lse_tok_ptr + b * s_lt_b + h * s_lt_h + offs_t * s_lt_t
q_tile = tl.load(q_ptrs, mask=t_mask[:, None], other=0.0)
o_tok = tl.load(ot_ptrs, mask=t_mask[:, None], other=0.0)
lse_tok = tl.load(lt_ptrs, mask=t_mask, other=0.0).to(tl.float32)
# scores = (q_normed @ k_mem_n^T) * (1 / sqrt(HEAD_DIM)) + beta_h [BLOCK_T, M_MOLA]
scores = tl.dot(
q_tile,
tl.trans(k_mem),
out_dtype=tl.float32,
input_precision=INPUT_PRECISION,
) * SCALE + beta_h
# Numerically stable logsumexp & softmax over M_MOLA
m_max = tl.max(scores, axis=1) # [BLOCK_T]
exp_s = tl.exp(scores - m_max[:, None]) # [BLOCK_T, M_MOLA]
sum_exp = tl.sum(exp_s, axis=1) # [BLOCK_T]
lse_mem = m_max + tl.log(sum_exp) # [BLOCK_T]
p_mem = exp_s / sum_exp[:, None] # [BLOCK_T, M_MOLA], FP32
# o_mem = p_mem @ v_mem in registers [BLOCK_T, HEAD_DIM], FP32 accum
o_mem = tl.dot(
p_mem.to(v_mem.dtype),
v_mem,
out_dtype=tl.float32,
input_precision=INPUT_PRECISION,
)
# Overflow-safe sigmoid: alpha = sigmoid(lse_mem - lse_tok)
diff = lse_mem - lse_tok
pos_sig = 1.0 / (1.0 + tl.exp(-tl.where(diff >= 0.0, diff, 0.0)))
exp_neg = tl.exp(tl.where(diff < 0.0, diff, 0.0))
neg_sig = exp_neg / (1.0 + exp_neg)
alpha = tl.where(diff >= 0.0, pos_sig, neg_sig) # [BLOCK_T], FP32
# Online-softmax merge: out = (1 - alpha) * o_tok + alpha * o_mem
out_f32 = (1.0 - alpha[:, None]) * o_tok.to(tl.float32) + alpha[:, None] * o_mem
# Store only out [B, H, T, D] and lse_mem [B, H, T]
out_ptrs = out_ptr + b * s_out_b + h * s_out_h + offs_t[:, None] * s_out_t + offs_d[None, :] * s_out_d
lm_ptrs = lse_mem_ptr + b * s_lm_b + h * s_lm_h + offs_t * s_lm_t
tl.store(out_ptrs, out_f32.to(o_tok.dtype), mask=t_mask[:, None])
tl.store(lm_ptrs, lse_mem, mask=t_mask)
@triton.jit
def _triton_mola_online_merge_bwd(
d_out_ptr,
out_ptr,
lse_tok_ptr,
lse_mem_ptr,
q_ptr,
k_mem_ptr,
v_mem_ptr,
beta_ptr,
# Output gradients
d_ot_ptr,
d_q_ptr,
d_km_ptr, # FP32 zero-initialized [H, M, D], accumulated via atomic_add
d_vm_ptr, # FP32 zero-initialized [H, M, D], accumulated via atomic_add
d_beta_ptr, # FP32 zero-initialized [H], accumulated via atomic_add
# Strides for d_out [B, H, T, D]
s_do_b, s_do_h, s_do_t, s_do_d,
# Strides for out [B, H, T, D]
s_out_b, s_out_h, s_out_t, s_out_d,
# Strides for lse_tok [B, H, T]
s_lt_b, s_lt_h, s_lt_t,
# Strides for lse_mem [B, H, T]
s_lm_b, s_lm_h, s_lm_t,
# Strides for q_normed [B, H, T, D]
s_q_b, s_q_h, s_q_t, s_q_d,
# Strides for k_mem_n [H, M, D]
s_km_h, s_km_m, s_km_d,
# Strides for v_mem [H, M, D]
s_vm_h, s_vm_m, s_vm_d,
# Strides for d_o_tok [B, H, T, D]
s_dot_b, s_dot_h, s_dot_t, s_dot_d,
# Strides for d_q_normed [B, H, T, D]
s_dq_b, s_dq_h, s_dq_t, s_dq_d,
# Strides for d_k_mem_n [H, M, D] (FP32)
s_dkm_h, s_dkm_m, s_dkm_d,
# Strides for d_v_mem [H, M, D] (FP32)
s_dvm_h, s_dvm_m, s_dvm_d,
# Dimensions
H,
T,
# Compile-time constants
SCALE: tl.constexpr,
BLOCK_T: tl.constexpr,
HEAD_DIM: tl.constexpr,
M_MOLA: tl.constexpr,
INPUT_PRECISION: tl.constexpr,
):
"""Fused MoLA backward for one (b, h, t_tile).
Computes exact analytical gradients:
d_o_tok = (1 - alpha) * d_out
D_out = sum_d(d_out * out)
ds = (alpha * p_mem) * (d_out @ v_mem^T - D_out)
d_q_normed = (ds @ k_mem_n) * SCALE
d_k_mem_n += (ds^T @ q_normed) * SCALE
d_v_mem += (alpha * p_mem)^T @ d_out
d_beta += sum_{t,m}(ds)
"""
pid_t = tl.program_id(0)
pid_bh = tl.program_id(1)
b = pid_bh // H
h = pid_bh % H
offs_t = pid_t * BLOCK_T + tl.arange(0, BLOCK_T)
offs_d = tl.arange(0, HEAD_DIM)
offs_m = tl.arange(0, M_MOLA)
t_mask = offs_t < T
# Load per-head MoLA parameters once into registers
km_ptrs = k_mem_ptr + h * s_km_h + offs_m[:, None] * s_km_m + offs_d[None, :] * s_km_d
vm_ptrs = v_mem_ptr + h * s_vm_h + offs_m[:, None] * s_vm_m + offs_d[None, :] * s_vm_d
k_mem = tl.load(km_ptrs) # [M_MOLA, HEAD_DIM]
v_mem = tl.load(vm_ptrs) # [M_MOLA, HEAD_DIM]
beta_h = tl.load(beta_ptr + h).to(tl.float32)
# Load token tiles
do_ptrs = d_out_ptr + b * s_do_b + h * s_do_h + offs_t[:, None] * s_do_t + offs_d[None, :] * s_do_d
out_ptrs = out_ptr + b * s_out_b + h * s_out_h + offs_t[:, None] * s_out_t + offs_d[None, :] * s_out_d
q_ptrs = q_ptr + b * s_q_b + h * s_q_h + offs_t[:, None] * s_q_t + offs_d[None, :] * s_q_d
lt_ptrs = lse_tok_ptr + b * s_lt_b + h * s_lt_h + offs_t * s_lt_t
lm_ptrs = lse_mem_ptr + b * s_lm_b + h * s_lm_h + offs_t * s_lm_t
g_tile = tl.load(do_ptrs, mask=t_mask[:, None], other=0.0)
out_tile = tl.load(out_ptrs, mask=t_mask[:, None], other=0.0)
q_tile = tl.load(q_ptrs, mask=t_mask[:, None], other=0.0)
lse_tok = tl.load(lt_ptrs, mask=t_mask, other=0.0).to(tl.float32)
lse_mem = tl.load(lm_ptrs, mask=t_mask, other=0.0).to(tl.float32)
g_f32 = g_tile.to(tl.float32)
out_f32 = out_tile.to(tl.float32)
# Recompute alpha = sigmoid(lse_mem - lse_tok)
diff = lse_mem - lse_tok
pos_sig = 1.0 / (1.0 + tl.exp(-tl.where(diff >= 0.0, diff, 0.0)))
exp_neg = tl.exp(tl.where(diff < 0.0, diff, 0.0))
neg_sig = exp_neg / (1.0 + exp_neg)
alpha = tl.where(diff >= 0.0, pos_sig, neg_sig) # [BLOCK_T], FP32
# 1) d_o_tok = (1 - alpha) * g
d_ot_f32 = (1.0 - alpha[:, None]) * g_f32
dot_ptrs = d_ot_ptr + b * s_dot_b + h * s_dot_h + offs_t[:, None] * s_dot_t + offs_d[None, :] * s_dot_d
tl.store(dot_ptrs, d_ot_f32.to(g_tile.dtype), mask=t_mask[:, None])
# Recompute p_mem = exp(scores - lse_mem) in registers
scores = tl.dot(
q_tile,
tl.trans(k_mem),
out_dtype=tl.float32,
input_precision=INPUT_PRECISION,
) * SCALE + beta_h
p_mem = tl.exp(scores - lse_mem[:, None]) # [BLOCK_T, M_MOLA]
p_masked = tl.where(t_mask[:, None], p_mem, 0.0)
# Effective joint probability on memory slots: ap = alpha * p_mem
ap_masked = alpha[:, None] * p_masked # [BLOCK_T, M_MOLA]
# FlashAttention-2 joint-softmax identity:
# D_out = sum_d(g * out) = (1 - alpha) * <g, o_tok> + alpha * <g, o_mem>
# ds = (alpha * p_mem) * (g @ v_mem^T - D_out)
d_out_dot = tl.sum(g_f32 * out_f32, axis=1) # [BLOCK_T]
gv = tl.dot(
g_tile,
tl.trans(v_mem),
out_dtype=tl.float32,
input_precision=INPUT_PRECISION,
) # [BLOCK_T, M_MOLA]
ds = ap_masked * (gv - d_out_dot[:, None]) # [BLOCK_T, M_MOLA], already zeroed where ~t_mask
# 2) d_q_normed = (ds @ k_mem_n) * SCALE
dq_f32 = tl.dot(
ds.to(k_mem.dtype),
k_mem,
out_dtype=tl.float32,
input_precision=INPUT_PRECISION,
) * SCALE
dq_ptrs = d_q_ptr + b * s_dq_b + h * s_dq_h + offs_t[:, None] * s_dq_t + offs_d[None, :] * s_dq_d
tl.store(dq_ptrs, dq_f32.to(q_tile.dtype), mask=t_mask[:, None])
# 3) d_k_mem_n += (ds^T @ q_normed) * SCALE
dk_tile = tl.dot(
tl.trans(ds.to(q_tile.dtype)),
q_tile,
out_dtype=tl.float32,
input_precision=INPUT_PRECISION,
) * SCALE
dkm_ptrs = d_km_ptr + h * s_dkm_h + offs_m[:, None] * s_dkm_m + offs_d[None, :] * s_dkm_d
tl.atomic_add(dkm_ptrs, dk_tile)
# 4) d_v_mem += (alpha * p_mem)^T @ g
dv_tile = tl.dot(
tl.trans(ap_masked.to(g_tile.dtype)),
g_tile,
out_dtype=tl.float32,
input_precision=INPUT_PRECISION,
)
dvm_ptrs = d_vm_ptr + h * s_dvm_h + offs_m[:, None] * s_dvm_m + offs_d[None, :] * s_dvm_d
tl.atomic_add(dvm_ptrs, dv_tile)
# 5) d_beta += sum_{t,m}(ds)
dbeta_val = tl.sum(tl.sum(ds, axis=1), axis=0)
tl.atomic_add(d_beta_ptr + h, dbeta_val)
if True:
def fused_mola_online_merge_ref(
o_tok: "torch.Tensor",
lse_tok: "torch.Tensor",
q_normed: "torch.Tensor",
k_mem_n: "torch.Tensor",
v_mem: "torch.Tensor",
beta: "torch.Tensor",
) -> "torch.Tensor":
"""Exact PyTorch reference matching HiSASlidingWindowAttention (lines 1940-1950)."""
dt = o_tok.dtype
_, H, _, D = q_normed.shape
scores_mem = (
torch.matmul(q_normed, k_mem_n.to(dt).transpose(-1, -2)).float()
/ math.sqrt(D)
+ beta.float().view(1, H, 1, 1)
)
lse_mem = torch.logsumexp(scores_mem, dim=-1)
p_mem = torch.softmax(scores_mem, dim=-1).to(dt)
o_mem = torch.matmul(p_mem, v_mem.to(dt))
alpha = torch.sigmoid(lse_mem - lse_tok.detach().float()).unsqueeze(-1).to(dt)
return (1.0 - alpha) * o_tok + alpha * o_mem
class _FusedMoLAOnlineMergeFn(torch.autograd.Function):
"""Autograd wrapper around `_triton_mola_online_merge_{fwd,bwd}`."""
@staticmethod
def forward(
ctx,
o_tok: "torch.Tensor",
lse_tok: "torch.Tensor",
q_normed: "torch.Tensor",
k_mem_n: "torch.Tensor",
v_mem: "torch.Tensor",
beta: "torch.Tensor",
) -> "torch.Tensor":
B, H, T, D = q_normed.shape
M = k_mem_n.shape[1]
dt = o_tok.dtype
orig_ot_dtype = o_tok.dtype
orig_q_dtype = q_normed.dtype
orig_km_dtype = k_mem_n.dtype
orig_vm_dtype = v_mem.dtype
orig_beta_dtype = beta.dtype
# Ensure matching dtype and contiguous innermost dim (zero-copy for .transpose(1, 2))
if o_tok.stride(-1) != 1:
o_tok = o_tok.contiguous()
if q_normed.dtype != dt:
q_normed = q_normed.to(dt)
if q_normed.stride(-1) != 1:
q_normed = q_normed.contiguous()
if k_mem_n.dtype != dt or not k_mem_n.is_contiguous():
k_mem_n = k_mem_n.to(dt).contiguous()
if v_mem.dtype != dt or not v_mem.is_contiguous():
v_mem = v_mem.to(dt).contiguous()
lse_tok_f32 = lse_tok.detach().float()
if lse_tok_f32.stride(-1) != 1:
lse_tok_f32 = lse_tok_f32.contiguous()
beta_f32 = beta.float().contiguous()
out = torch.empty((B, H, T, D), device=o_tok.device, dtype=dt)
lse_mem = torch.empty((B, H, T), device=o_tok.device, dtype=torch.float32)
BLOCK_T = 64
scale = 1.0 / math.sqrt(D)
input_precision = "ieee" if dt == torch.float32 else "tf32"
grid = (triton.cdiv(T, BLOCK_T), B * H)
_triton_mola_online_merge_fwd[grid](
o_tok, lse_tok_f32, q_normed, k_mem_n, v_mem, beta_f32,
out, lse_mem,
o_tok.stride(0), o_tok.stride(1), o_tok.stride(2), o_tok.stride(3),
lse_tok_f32.stride(0), lse_tok_f32.stride(1), lse_tok_f32.stride(2),
q_normed.stride(0), q_normed.stride(1), q_normed.stride(2), q_normed.stride(3),
k_mem_n.stride(0), k_mem_n.stride(1), k_mem_n.stride(2),
v_mem.stride(0), v_mem.stride(1), v_mem.stride(2),
out.stride(0), out.stride(1), out.stride(2), out.stride(3),
lse_mem.stride(0), lse_mem.stride(1), lse_mem.stride(2),
H, T,
SCALE=scale,
BLOCK_T=BLOCK_T,
HEAD_DIM=D,
M_MOLA=M,
INPUT_PRECISION=input_precision,
num_warps=4,
num_stages=2,
)
ctx.save_for_backward(out, lse_tok_f32, lse_mem, q_normed, k_mem_n, v_mem, beta_f32)
ctx.meta = (
scale,
BLOCK_T,
D,
M,
input_precision,
orig_ot_dtype,
orig_q_dtype,
orig_km_dtype,
orig_vm_dtype,
orig_beta_dtype,
)
return out
@staticmethod
def backward(ctx, d_out: "torch.Tensor"):
out, lse_tok_f32, lse_mem, q_normed, k_mem_n, v_mem, beta_f32 = ctx.saved_tensors
(
scale,
BLOCK_T,
D,
M,
input_precision,
ot_dtype,
q_dtype,
km_dtype,
vm_dtype,
beta_dtype,
) = ctx.meta
B, H, T, _ = q_normed.shape
if d_out.dtype != out.dtype:
d_out = d_out.to(out.dtype)
if d_out.stride(-1) != 1:
d_out = d_out.contiguous()
d_o_tok = torch.empty((B, H, T, D), device=d_out.device, dtype=out.dtype)
d_q_normed = torch.empty((B, H, T, D), device=d_out.device, dtype=out.dtype)
d_k_mem_n = torch.zeros((H, M, D), device=d_out.device, dtype=torch.float32)
d_v_mem = torch.zeros((H, M, D), device=d_out.device, dtype=torch.float32)
d_beta = torch.zeros((H,), device=d_out.device, dtype=torch.float32)
grid = (triton.cdiv(T, BLOCK_T), B * H)
_triton_mola_online_merge_bwd[grid](
d_out, out, lse_tok_f32, lse_mem, q_normed, k_mem_n, v_mem, beta_f32,
d_o_tok, d_q_normed, d_k_mem_n, d_v_mem, d_beta,
d_out.stride(0), d_out.stride(1), d_out.stride(2), d_out.stride(3),
out.stride(0), out.stride(1), out.stride(2), out.stride(3),
lse_tok_f32.stride(0), lse_tok_f32.stride(1), lse_tok_f32.stride(2),
lse_mem.stride(0), lse_mem.stride(1), lse_mem.stride(2),
q_normed.stride(0), q_normed.stride(1), q_normed.stride(2), q_normed.stride(3),
k_mem_n.stride(0), k_mem_n.stride(1), k_mem_n.stride(2),
v_mem.stride(0), v_mem.stride(1), v_mem.stride(2),
d_o_tok.stride(0), d_o_tok.stride(1), d_o_tok.stride(2), d_o_tok.stride(3),
d_q_normed.stride(0), d_q_normed.stride(1), d_q_normed.stride(2), d_q_normed.stride(3),
d_k_mem_n.stride(0), d_k_mem_n.stride(1), d_k_mem_n.stride(2),
d_v_mem.stride(0), d_v_mem.stride(1), d_v_mem.stride(2),
H, T,
SCALE=scale,
BLOCK_T=BLOCK_T,
HEAD_DIM=D,
M_MOLA=M,
INPUT_PRECISION=input_precision,
num_warps=4,
num_stages=2,
)
# d_lse_tok is strictly None (lse_tok.detach() in forward)
return (
d_o_tok.to(ot_dtype),
None,
d_q_normed.to(q_dtype),
d_k_mem_n.to(km_dtype),
d_v_mem.to(vm_dtype),
d_beta.to(beta_dtype),
)
def fused_mola_online_merge(
o_tok: "torch.Tensor",
lse_tok: "torch.Tensor",
q_normed: "torch.Tensor",
k_mem_n: "torch.Tensor",
v_mem: "torch.Tensor",
beta: "torch.Tensor",
) -> "torch.Tensor":
"""Drop-in replacement for lines 1940-1950 of `HiSASlidingWindowAttention.forward`.
Dispatches to the fused Triton kernel on CUDA when `HEAD_DIM >= 16` and
`M_MOLA >= 16` are powers of 2; otherwise falls back cleanly to PyTorch.
"""
D = q_normed.shape[-1]
M = k_mem_n.shape[1]
if (
_HAS_TRITON
and o_tok.is_cuda
and D >= 16
and M >= 16
and _is_power_of_two(D)
and _is_power_of_two(M)
):
return _FusedMoLAOnlineMergeFn.apply(
o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta
)
return fused_mola_online_merge_ref(
o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta
)
# =====================================================================
# --- Kernel Suite 4: 1-Pass Triton SWGDN2-G1 Local SWA (custom_op, 0 graph breaks) ---
if _HAS_TRITON:
@triton.jit
def _triton_swgdn2_local_swa_fwd(
# Input tensors: [B, T, H, D]
q_ptr,
k_ptr,
v_ptr,
kn_ptr,
# Pre-rotated pseudo-queries: [3, 4, H, D]
prot_ptr,
# Output tensors: [B, T, H, D] and [B, 3, 4, T, H] FP32
q_out_ptr,
k_out_ptr,
v_out_ptr,
attn_ptr,
# Strides for q, k, v, k_n
sq_b, sq_t, sq_h, sq_d,
sk_b, sk_t, sk_h, sk_d,
sv_b, sv_t, sv_h, sv_d,
skn_b, skn_t, skn_h, skn_d,
# Strides for p_rot: [3, 4, H, D]
sp_x, sp_w, sp_h, sp_d,
# Strides for outputs q_mix, k_mix, v_mix: [B, T, H, D]
soq_b, soq_t, soq_h, soq_d,
sok_b, sok_t, sok_h, sok_d,
sov_b, sov_t, sov_h, sov_d,
# Strides for attn: [B, 3, 4, T, H]
sa_b, sa_x, sa_w, sa_t, sa_h,
# Dimensions & scale
T,
scale,
BLOCK_T: tl.constexpr,
HEAD_DIM: tl.constexpr,
):
pid_b = tl.program_id(0).to(tl.int64)
pid_h = tl.program_id(1).to(tl.int64)
pid_tile = tl.program_id(2).to(tl.int64)
t_start = pid_tile * BLOCK_T
t_offs = t_start + tl.arange(0, BLOCK_T).to(tl.int64) # [BLOCK_T]
d_offs = tl.arange(0, HEAD_DIM).to(tl.int64) # [HEAD_DIM]
m_t = t_offs < T # [BLOCK_T]
# Valid masks and clamped causal indices for w in {0, 1, 2, 3}
t0 = t_offs
t1 = t_offs - 1
t2 = t_offs - 2
t3 = t_offs - 3
m0 = m_t & (t0 >= 0)
m1 = m_t & (t1 >= 0)
m2 = m_t & (t2 >= 0)
m3 = m_t & (t3 >= 0)
t0_c = tl.where(m0, t0, 0)
t1_c = tl.where(m1, t1, 0)
t2_c = tl.where(m2, t2, 0)
t3_c = tl.where(m3, t3, 0)
# Cast strides to int64
skn_b64 = tl.cast(skn_b, tl.int64)
skn_t64 = tl.cast(skn_t, tl.int64)
skn_h64 = tl.cast(skn_h, tl.int64)
skn_d64 = tl.cast(skn_d, tl.int64)
# Load k_n[b, t - w, h, :] ONCE for all 3 branches (FP32)
kn_base = pid_b * skn_b64 + pid_h * skn_h64
kn0 = tl.load(
kn_ptr + kn_base + t0_c[:, None] * skn_t64 + d_offs[None, :] * skn_d64,
mask=m0[:, None],
other=0.0,
).to(tl.float32)
kn1 = tl.load(
kn_ptr + kn_base + t1_c[:, None] * skn_t64 + d_offs[None, :] * skn_d64,
mask=m1[:, None],
other=0.0,
).to(tl.float32)
kn2 = tl.load(
kn_ptr + kn_base + t2_c[:, None] * skn_t64 + d_offs[None, :] * skn_d64,
mask=m2[:, None],
other=0.0,
).to(tl.float32)
kn3 = tl.load(
kn_ptr + kn_base + t3_c[:, None] * skn_t64 + d_offs[None, :] * skn_d64,
mask=m3[:, None],
other=0.0,
).to(tl.float32)
# Load p_rot[0..2, 0..3, h, :] ONCE into registers (12 x HEAD_DIM FP32)
sp_x64 = tl.cast(sp_x, tl.int64)
sp_w64 = tl.cast(sp_w, tl.int64)
sp_h64 = tl.cast(sp_h, tl.int64)
sp_d64 = tl.cast(sp_d, tl.int64)
p_h_base = pid_h * sp_h64 + d_offs * sp_d64
p00 = tl.load(prot_ptr + 0 * sp_x64 + 0 * sp_w64 + p_h_base).to(tl.float32)
p01 = tl.load(prot_ptr + 0 * sp_x64 + 1 * sp_w64 + p_h_base).to(tl.float32)
p02 = tl.load(prot_ptr + 0 * sp_x64 + 2 * sp_w64 + p_h_base).to(tl.float32)
p03 = tl.load(prot_ptr + 0 * sp_x64 + 3 * sp_w64 + p_h_base).to(tl.float32)
p10 = tl.load(prot_ptr + 1 * sp_x64 + 0 * sp_w64 + p_h_base).to(tl.float32)
p11 = tl.load(prot_ptr + 1 * sp_x64 + 1 * sp_w64 + p_h_base).to(tl.float32)
p12 = tl.load(prot_ptr + 1 * sp_x64 + 2 * sp_w64 + p_h_base).to(tl.float32)
p13 = tl.load(prot_ptr + 1 * sp_x64 + 3 * sp_w64 + p_h_base).to(tl.float32)
p20 = tl.load(prot_ptr + 2 * sp_x64 + 0 * sp_w64 + p_h_base).to(tl.float32)
p21 = tl.load(prot_ptr + 2 * sp_x64 + 1 * sp_w64 + p_h_base).to(tl.float32)
p22 = tl.load(prot_ptr + 2 * sp_x64 + 2 * sp_w64 + p_h_base).to(tl.float32)
p23 = tl.load(prot_ptr + 2 * sp_x64 + 3 * sp_w64 + p_h_base).to(tl.float32)
sa_b64 = tl.cast(sa_b, tl.int64)
sa_x64 = tl.cast(sa_x, tl.int64)
sa_w64 = tl.cast(sa_w, tl.int64)
sa_t64 = tl.cast(sa_t, tl.int64)
sa_h64 = tl.cast(sa_h, tl.int64)
a_base = pid_b * sa_b64 + pid_h * sa_h64 + t_offs * sa_t64
neg_inf = -1e9
# ---------------- Branch 0: Q ----------------
s0 = tl.where(m0, tl.sum(kn0 * p00[None, :], axis=1) * scale, neg_inf)
s1 = tl.where(m1, tl.sum(kn1 * p01[None, :], axis=1) * scale, neg_inf)
s2 = tl.where(m2, tl.sum(kn2 * p02[None, :], axis=1) * scale, neg_inf)
s3 = tl.where(m3, tl.sum(kn3 * p03[None, :], axis=1) * scale, neg_inf)
m_max = tl.maximum(tl.maximum(s0, s1), tl.maximum(s2, s3))
e0 = tl.exp(s0 - m_max)
e1 = tl.exp(s1 - m_max)
e2 = tl.exp(s2 - m_max)
e3 = tl.exp(s3 - m_max)
inv_s = 1.0 / (e0 + e1 + e2 + e3)
a0 = e0 * inv_s
a1 = e1 * inv_s
a2 = e2 * inv_s
a3 = e3 * inv_s
tl.store(attn_ptr + a_base + 0 * sa_x64 + 0 * sa_w64, a0, mask=m_t)
tl.store(attn_ptr + a_base + 0 * sa_x64 + 1 * sa_w64, a1, mask=m_t)
tl.store(attn_ptr + a_base + 0 * sa_x64 + 2 * sa_w64, a2, mask=m_t)
tl.store(attn_ptr + a_base + 0 * sa_x64 + 3 * sa_w64, a3, mask=m_t)
sq_b64 = tl.cast(sq_b, tl.int64)
sq_t64 = tl.cast(sq_t, tl.int64)
sq_h64 = tl.cast(sq_h, tl.int64)
sq_d64 = tl.cast(sq_d, tl.int64)
q_base = pid_b * sq_b64 + pid_h * sq_h64
x0 = tl.load(q_ptr + q_base + t0_c[:, None] * sq_t64 + d_offs[None, :] * sq_d64, mask=m0[:, None], other=0.0).to(tl.float32)
x1 = tl.load(q_ptr + q_base + t1_c[:, None] * sq_t64 + d_offs[None, :] * sq_d64, mask=m1[:, None], other=0.0).to(tl.float32)
x2 = tl.load(q_ptr + q_base + t2_c[:, None] * sq_t64 + d_offs[None, :] * sq_d64, mask=m2[:, None], other=0.0).to(tl.float32)
x3 = tl.load(q_ptr + q_base + t3_c[:, None] * sq_t64 + d_offs[None, :] * sq_d64, mask=m3[:, None], other=0.0).to(tl.float32)
u = a0[:, None] * x0 + a1[:, None] * x1 + a2[:, None] * x2 + a3[:, None] * x3
y = u * tl.sigmoid(u)
soq_b64 = tl.cast(soq_b, tl.int64)
soq_t64 = tl.cast(soq_t, tl.int64)
soq_h64 = tl.cast(soq_h, tl.int64)
soq_d64 = tl.cast(soq_d, tl.int64)
tl.store(
q_out_ptr + pid_b * soq_b64 + t_offs[:, None] * soq_t64 + pid_h * soq_h64 + d_offs[None, :] * soq_d64,
y.to(q_out_ptr.dtype.element_ty),
mask=m_t[:, None],
)
# ---------------- Branch 1: K ----------------
s0 = tl.where(m0, tl.sum(kn0 * p10[None, :], axis=1) * scale, neg_inf)
s1 = tl.where(m1, tl.sum(kn1 * p11[None, :], axis=1) * scale, neg_inf)
s2 = tl.where(m2, tl.sum(kn2 * p12[None, :], axis=1) * scale, neg_inf)
s3 = tl.where(m3, tl.sum(kn3 * p13[None, :], axis=1) * scale, neg_inf)
m_max = tl.maximum(tl.maximum(s0, s1), tl.maximum(s2, s3))
e0 = tl.exp(s0 - m_max)
e1 = tl.exp(s1 - m_max)
e2 = tl.exp(s2 - m_max)
e3 = tl.exp(s3 - m_max)
inv_s = 1.0 / (e0 + e1 + e2 + e3)
a0 = e0 * inv_s
a1 = e1 * inv_s
a2 = e2 * inv_s
a3 = e3 * inv_s
tl.store(attn_ptr + a_base + 1 * sa_x64 + 0 * sa_w64, a0, mask=m_t)
tl.store(attn_ptr + a_base + 1 * sa_x64 + 1 * sa_w64, a1, mask=m_t)
tl.store(attn_ptr + a_base + 1 * sa_x64 + 2 * sa_w64, a2, mask=m_t)
tl.store(attn_ptr + a_base + 1 * sa_x64 + 3 * sa_w64, a3, mask=m_t)
sk_b64 = tl.cast(sk_b, tl.int64)
sk_t64 = tl.cast(sk_t, tl.int64)
sk_h64 = tl.cast(sk_h, tl.int64)
sk_d64 = tl.cast(sk_d, tl.int64)
k_base = pid_b * sk_b64 + pid_h * sk_h64
x0 = tl.load(k_ptr + k_base + t0_c[:, None] * sk_t64 + d_offs[None, :] * sk_d64, mask=m0[:, None], other=0.0).to(tl.float32)
x1 = tl.load(k_ptr + k_base + t1_c[:, None] * sk_t64 + d_offs[None, :] * sk_d64, mask=m1[:, None], other=0.0).to(tl.float32)
x2 = tl.load(k_ptr + k_base + t2_c[:, None] * sk_t64 + d_offs[None, :] * sk_d64, mask=m2[:, None], other=0.0).to(tl.float32)
x3 = tl.load(k_ptr + k_base + t3_c[:, None] * sk_t64 + d_offs[None, :] * sk_d64, mask=m3[:, None], other=0.0).to(tl.float32)
u = a0[:, None] * x0 + a1[:, None] * x1 + a2[:, None] * x2 + a3[:, None] * x3
y = u * tl.sigmoid(u)
sok_b64 = tl.cast(sok_b, tl.int64)
sok_t64 = tl.cast(sok_t, tl.int64)
sok_h64 = tl.cast(sok_h, tl.int64)
sok_d64 = tl.cast(sok_d, tl.int64)
tl.store(
k_out_ptr + pid_b * sok_b64 + t_offs[:, None] * sok_t64 + pid_h * sok_h64 + d_offs[None, :] * sok_d64,
y.to(k_out_ptr.dtype.element_ty),
mask=m_t[:, None],
)
# ---------------- Branch 2: V ----------------
s0 = tl.where(m0, tl.sum(kn0 * p20[None, :], axis=1) * scale, neg_inf)
s1 = tl.where(m1, tl.sum(kn1 * p21[None, :], axis=1) * scale, neg_inf)
s2 = tl.where(m2, tl.sum(kn2 * p22[None, :], axis=1) * scale, neg_inf)
s3 = tl.where(m3, tl.sum(kn3 * p23[None, :], axis=1) * scale, neg_inf)
m_max = tl.maximum(tl.maximum(s0, s1), tl.maximum(s2, s3))
e0 = tl.exp(s0 - m_max)
e1 = tl.exp(s1 - m_max)
e2 = tl.exp(s2 - m_max)
e3 = tl.exp(s3 - m_max)
inv_s = 1.0 / (e0 + e1 + e2 + e3)
a0 = e0 * inv_s
a1 = e1 * inv_s
a2 = e2 * inv_s
a3 = e3 * inv_s
tl.store(attn_ptr + a_base + 2 * sa_x64 + 0 * sa_w64, a0, mask=m_t)
tl.store(attn_ptr + a_base + 2 * sa_x64 + 1 * sa_w64, a1, mask=m_t)
tl.store(attn_ptr + a_base + 2 * sa_x64 + 2 * sa_w64, a2, mask=m_t)
tl.store(attn_ptr + a_base + 2 * sa_x64 + 3 * sa_w64, a3, mask=m_t)
sv_b64 = tl.cast(sv_b, tl.int64)
sv_t64 = tl.cast(sv_t, tl.int64)
sv_h64 = tl.cast(sv_h, tl.int64)
sv_d64 = tl.cast(sv_d, tl.int64)
v_base = pid_b * sv_b64 + pid_h * sv_h64
x0 = tl.load(v_ptr + v_base + t0_c[:, None] * sv_t64 + d_offs[None, :] * sv_d64, mask=m0[:, None], other=0.0).to(tl.float32)
x1 = tl.load(v_ptr + v_base + t1_c[:, None] * sv_t64 + d_offs[None, :] * sv_d64, mask=m1[:, None], other=0.0).to(tl.float32)
x2 = tl.load(v_ptr + v_base + t2_c[:, None] * sv_t64 + d_offs[None, :] * sv_d64, mask=m2[:, None], other=0.0).to(tl.float32)
x3 = tl.load(v_ptr + v_base + t3_c[:, None] * sv_t64 + d_offs[None, :] * sv_d64, mask=m3[:, None], other=0.0).to(tl.float32)
u = a0[:, None] * x0 + a1[:, None] * x1 + a2[:, None] * x2 + a3[:, None] * x3
y = u * tl.sigmoid(u)
sov_b64 = tl.cast(sov_b, tl.int64)
sov_t64 = tl.cast(sov_t, tl.int64)
sov_h64 = tl.cast(sov_h, tl.int64)
sov_d64 = tl.cast(sov_d, tl.int64)
tl.store(
v_out_ptr + pid_b * sov_b64 + t_offs[:, None] * sov_t64 + pid_h * sov_h64 + d_offs[None, :] * sov_d64,
y.to(v_out_ptr.dtype.element_ty),
mask=m_t[:, None],
)
@triton.jit
def _bwd_branch_step(
# Computes one branch's contribution to dX[i], dk_n[i], and atomic_add(d_p_rot[x, w, h, :])
x_ptr,
g_ptr,
attn_ptr,
prot_ptr,
dprot_ptr,
kn_i,
dk_n_acc,
sx_b, sx_t, sx_h, sx_d,
sg_b, sg_t, sg_h, sg_d,
sa_b, sa_x, sa_w, sa_t, sa_h,
sp_x, sp_w, sp_h, sp_d,
sdp_x, sdp_w, sdp_h, sdp_d,
pid_b,
pid_h,
i_offs,
d_offs,
T,
scale,
branch_x: tl.constexpr,
BLOCK_T: tl.constexpr,
HEAD_DIM: tl.constexpr,
):
dx_acc = tl.zeros((BLOCK_T, HEAD_DIM), dtype=tl.float32)
x_base = pid_b * sx_b + pid_h * sx_h
g_base = pid_b * sg_b + pid_h * sg_h
a_xh_base = pid_b * sa_b + branch_x * sa_x + pid_h * sa_h
p_xh_base = branch_x * sp_x + pid_h * sp_h + d_offs * sp_d
dp_xh_base = branch_x * sdp_x + pid_h * sdp_h + d_offs * sdp_d
for w_shift in tl.static_range(4):
t_offs = i_offs + w_shift
m_t = t_offs < T
t_c = tl.where(m_t, t_offs, 0)
# Load softmax weights a[b, x, 0..3, t, h] (FP32)
a_t_base = a_xh_base + t_c * sa_t
a0 = tl.load(attn_ptr + a_t_base + 0 * sa_w, mask=m_t, other=0.0).to(tl.float32)
a1 = tl.load(attn_ptr + a_t_base + 1 * sa_w, mask=m_t, other=0.0).to(tl.float32)
a2 = tl.load(attn_ptr + a_t_base + 2 * sa_w, mask=m_t, other=0.0).to(tl.float32)
a3 = tl.load(attn_ptr + a_t_base + 3 * sa_w, mask=m_t, other=0.0).to(tl.float32)
# Window indices t - w' for w' in {0, 1, 2, 3}
t0 = t_offs
t1 = t_offs - 1
t2 = t_offs - 2
t3 = t_offs - 3
m0 = m_t & (t0 >= 0)
m1 = m_t & (t1 >= 0)
m2 = m_t & (t2 >= 0)
m3 = m_t & (t3 >= 0)
t0_c = tl.where(m0, t0, 0)
t1_c = tl.where(m1, t1, 0)
t2_c = tl.where(m2, t2, 0)
t3_c = tl.where(m3, t3, 0)
# Load X[b, t - w', h, :] (L1-resident across w_shift)
x0 = tl.load(x_ptr + x_base + t0_c[:, None] * sx_t + d_offs[None, :] * sx_d, mask=m0[:, None], other=0.0).to(tl.float32)
x1 = tl.load(x_ptr + x_base + t1_c[:, None] * sx_t + d_offs[None, :] * sx_d, mask=m1[:, None], other=0.0).to(tl.float32)
x2 = tl.load(x_ptr + x_base + t2_c[:, None] * sx_t + d_offs[None, :] * sx_d, mask=m2[:, None], other=0.0).to(tl.float32)
x3 = tl.load(x_ptr + x_base + t3_c[:, None] * sx_t + d_offs[None, :] * sx_d, mask=m3[:, None], other=0.0).to(tl.float32)
# Recompute pre-SiLU mix u[t] = sum_{w'=0..3} a[w', t] * X[t - w']
u = a0[:, None] * x0 + a1[:, None] * x1 + a2[:, None] * x2 + a3[:, None] * x3
# Upstream gradient g[t] and SiLU backward: du = g * sig(u) * (1 + u * (1 - sig(u)))
g = tl.load(g_ptr + g_base + t_c[:, None] * sg_t + d_offs[None, :] * sg_d, mask=m_t[:, None], other=0.0).to(tl.float32)
sig = tl.sigmoid(u)
du = g * sig * (1.0 + u * (1.0 - sig))
# Select a_wshift and da_wshift for current w_shift
da0 = tl.sum(du * x0, axis=1)
da1 = tl.sum(du * x1, axis=1)
da2 = tl.sum(du * x2, axis=1)
da3 = tl.sum(du * x3, axis=1)
d_dot = a0 * da0 + a1 * da1 + a2 * da2 + a3 * da3
if w_shift == 0:
a_w = a0
da_w = da0
elif w_shift == 1:
a_w = a1
da_w = da1
elif w_shift == 2:
a_w = a2
da_w = da2
else:
a_w = a3
da_w = da3
# Accumulate dX[b, i, h, :] += a[x, w_shift, i + w_shift] * du[i + w_shift]
dx_acc += a_w[:, None] * du
# Softmax backward: ds[x, w_shift, t] = a_w * (da_w - sum_{w'} a_{w'} da_{w'})
ds_w = tl.where(m_t, a_w * (da_w - d_dot), 0.0)
ds_scaled = ds_w * scale
# Accumulate dk_n[b, i, h, :] += (scale * ds[x, w_shift, i + w_shift]) * p_rot[x, w_shift, h, :]
p_w = tl.load(prot_ptr + p_xh_base + w_shift * sp_w).to(tl.float32)
dk_n_acc += ds_scaled[:, None] * p_w[None, :]
# Accumulate d_p_rot[x, w_shift, h, :] += sum_{i} (scale * ds[x, w_shift, i + w_shift]) * k_n[b, i, h, :]
dp_w = tl.sum(ds_scaled[:, None] * kn_i, axis=0)
tl.atomic_add(dprot_ptr + dp_xh_base + w_shift * sdp_w, dp_w)
return dx_acc, dk_n_acc
@triton.jit
def _triton_swgdn2_local_swa_bwd(
# Upstream gradients: [B, T, H, D]
gq_ptr,
gk_ptr,
gv_ptr,
# Saved forward inputs: [B, T, H, D], [3, 4, H, D], [B, 3, 4, T, H]
q_ptr,
k_ptr,
v_ptr,
kn_ptr,
prot_ptr,
attn_ptr,
# Output gradients: [B, T, H, D] and FP32 [3, 4, H, D]
dq_ptr,
dk_ptr,
dv_ptr,
dkn_ptr,
dprot_ptr,
# Strides for upstream gradients
sgq_b, sgq_t, sgq_h, sgq_d,
sgk_b, sgk_t, sgk_h, sgk_d,
sgv_b, sgv_t, sgv_h, sgv_d,
# Strides for q, k, v, k_n
sq_b, sq_t, sq_h, sq_d,
sk_b, sk_t, sk_h, sk_d,
sv_b, sv_t, sv_h, sv_d,
skn_b, skn_t, skn_h, skn_d,
# Strides for p_rot & d_p_rot: [3, 4, H, D]
sp_x, sp_w, sp_h, sp_d,
sdp_x, sdp_w, sdp_h, sdp_d,
# Strides for attn: [B, 3, 4, T, H]
sa_b, sa_x, sa_w, sa_t, sa_h,
# Strides for output gradients dq, dk, dv, dkn: [B, T, H, D]
sdq_b, sdq_t, sdq_h, sdq_d,
sdk_b, sdk_t, sdk_h, sdk_d,
sdv_b, sdv_t, sdv_h, sdv_d,
sdkn_b, sdkn_t, sdkn_h, sdkn_d,
# Dimensions & scale
T,
scale,
BLOCK_T: tl.constexpr,
HEAD_DIM: tl.constexpr,
):
pid_b = tl.program_id(0).to(tl.int64)
pid_h = tl.program_id(1).to(tl.int64)
pid_tile = tl.program_id(2).to(tl.int64)
i_start = pid_tile * BLOCK_T
i_offs = i_start + tl.arange(0, BLOCK_T).to(tl.int64) # [BLOCK_T]
d_offs = tl.arange(0, HEAD_DIM).to(tl.int64) # [HEAD_DIM]
m_i = i_offs < T
i_c = tl.where(m_i, i_offs, 0)
# Load k_n[b, i, h, :] ONCE for d_p_rot accumulation across all 3 branches
skn_b64 = tl.cast(skn_b, tl.int64)
skn_t64 = tl.cast(skn_t, tl.int64)
skn_h64 = tl.cast(skn_h, tl.int64)
skn_d64 = tl.cast(skn_d, tl.int64)
kn_i = tl.load(
kn_ptr + pid_b * skn_b64 + i_c[:, None] * skn_t64 + pid_h * skn_h64 + d_offs[None, :] * skn_d64,
mask=m_i[:, None],
other=0.0,
).to(tl.float32)
sa_b64 = tl.cast(sa_b, tl.int64)
sa_x64 = tl.cast(sa_x, tl.int64)
sa_w64 = tl.cast(sa_w, tl.int64)
sa_t64 = tl.cast(sa_t, tl.int64)
sa_h64 = tl.cast(sa_h, tl.int64)
sp_x64 = tl.cast(sp_x, tl.int64)
sp_w64 = tl.cast(sp_w, tl.int64)
sp_h64 = tl.cast(sp_h, tl.int64)
sp_d64 = tl.cast(sp_d, tl.int64)
sdp_x64 = tl.cast(sdp_x, tl.int64)
sdp_w64 = tl.cast(sdp_w, tl.int64)
sdp_h64 = tl.cast(sdp_h, tl.int64)
sdp_d64 = tl.cast(sdp_d, tl.int64)
dk_n_acc = tl.zeros((BLOCK_T, HEAD_DIM), dtype=tl.float32)
# Branch 0: Q
dq_acc, dk_n_acc = _bwd_branch_step(
q_ptr, gq_ptr, attn_ptr, prot_ptr, dprot_ptr, kn_i, dk_n_acc,
tl.cast(sq_b, tl.int64), tl.cast(sq_t, tl.int64), tl.cast(sq_h, tl.int64), tl.cast(sq_d, tl.int64),
tl.cast(sgq_b, tl.int64), tl.cast(sgq_t, tl.int64), tl.cast(sgq_h, tl.int64), tl.cast(sgq_d, tl.int64),
sa_b64, sa_x64, sa_w64, sa_t64, sa_h64,
sp_x64, sp_w64, sp_h64, sp_d64,
sdp_x64, sdp_w64, sdp_h64, sdp_d64,
pid_b, pid_h, i_offs, d_offs, T, scale,
0, BLOCK_T, HEAD_DIM,
)
tl.store(
dq_ptr
+ pid_b * tl.cast(sdq_b, tl.int64)
+ i_offs[:, None] * tl.cast(sdq_t, tl.int64)
+ pid_h * tl.cast(sdq_h, tl.int64)
+ d_offs[None, :] * tl.cast(sdq_d, tl.int64),
dq_acc.to(dq_ptr.dtype.element_ty),
mask=m_i[:, None],
)
# Branch 1: K
dk_acc, dk_n_acc = _bwd_branch_step(
k_ptr, gk_ptr, attn_ptr, prot_ptr, dprot_ptr, kn_i, dk_n_acc,
tl.cast(sk_b, tl.int64), tl.cast(sk_t, tl.int64), tl.cast(sk_h, tl.int64), tl.cast(sk_d, tl.int64),
tl.cast(sgk_b, tl.int64), tl.cast(sgk_t, tl.int64), tl.cast(sgk_h, tl.int64), tl.cast(sgk_d, tl.int64),
sa_b64, sa_x64, sa_w64, sa_t64, sa_h64,
sp_x64, sp_w64, sp_h64, sp_d64,
sdp_x64, sdp_w64, sdp_h64, sdp_d64,
pid_b, pid_h, i_offs, d_offs, T, scale,
1, BLOCK_T, HEAD_DIM,
)
tl.store(
dk_ptr
+ pid_b * tl.cast(sdk_b, tl.int64)
+ i_offs[:, None] * tl.cast(sdk_t, tl.int64)
+ pid_h * tl.cast(sdk_h, tl.int64)
+ d_offs[None, :] * tl.cast(sdk_d, tl.int64),
dk_acc.to(dk_ptr.dtype.element_ty),
mask=m_i[:, None],
)
# Branch 2: V
dv_acc, dk_n_acc = _bwd_branch_step(
v_ptr, gv_ptr, attn_ptr, prot_ptr, dprot_ptr, kn_i, dk_n_acc,
tl.cast(sv_b, tl.int64), tl.cast(sv_t, tl.int64), tl.cast(sv_h, tl.int64), tl.cast(sv_d, tl.int64),
tl.cast(sgv_b, tl.int64), tl.cast(sgv_t, tl.int64), tl.cast(sgv_h, tl.int64), tl.cast(sgv_d, tl.int64),
sa_b64, sa_x64, sa_w64, sa_t64, sa_h64,
sp_x64, sp_w64, sp_h64, sp_d64,
sdp_x64, sdp_w64, sdp_h64, sdp_d64,
pid_b, pid_h, i_offs, d_offs, T, scale,
2, BLOCK_T, HEAD_DIM,
)
tl.store(
dv_ptr
+ pid_b * tl.cast(sdv_b, tl.int64)
+ i_offs[:, None] * tl.cast(sdv_t, tl.int64)
+ pid_h * tl.cast(sdv_h, tl.int64)
+ d_offs[None, :] * tl.cast(sdv_d, tl.int64),
dv_acc.to(dv_ptr.dtype.element_ty),
mask=m_i[:, None],
)
# Store accumulated dk_n[b, i, h, :]
tl.store(
dkn_ptr
+ pid_b * tl.cast(sdkn_b, tl.int64)
+ i_offs[:, None] * tl.cast(sdkn_t, tl.int64)
+ pid_h * tl.cast(sdkn_h, tl.int64)
+ d_offs[None, :] * tl.cast(sdkn_d, tl.int64),
dk_n_acc.to(dkn_ptr.dtype.element_ty),
mask=m_i[:, None],
)
# =============================================================================
# 2. Pure-PyTorch Fallback & Triton Launch Helpers
# =============================================================================
if True:
def _validate_inputs(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
) -> Tuple[int, int, int, int]:
if q.ndim != 4 or k.ndim != 4 or v.ndim != 4 or k_n.ndim != 4:
raise ValueError(
f"q, k, v, k_n must be 4D [B, T, H, D]; got {q.shape}, {k.shape}, {v.shape}, {k_n.shape}"
)
if q.shape != k.shape or q.shape != v.shape or q.shape != k_n.shape:
raise ValueError(
f"q, k, v, k_n must have identical shapes; got {q.shape}, {k.shape}, {v.shape}, {k_n.shape}"
)
B, T, H, D = q.shape
if p_rot.shape != (3, WINDOW_SIZE, H, D):
raise ValueError(
f"p_rot must have shape (3, {WINDOW_SIZE}, {H}, {D}); got {tuple(p_rot.shape)}"
)
return B, T, H, D
def _swgdn2_can_use_triton(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
) -> bool:
if not (_HAS_TRITON and q.is_cuda and k.is_cuda and v.is_cuda and k_n.is_cuda and p_rot.is_cuda):
return False
D = q.shape[-1]
return _is_power_of_two(D) and D <= 256
def _launch_triton_fwd(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot)
out_dtype = q.dtype
q_mix = torch.empty((B, T, H, D), device=q.device, dtype=out_dtype)
k_mix = torch.empty((B, T, H, D), device=q.device, dtype=out_dtype)
v_mix = torch.empty((B, T, H, D), device=q.device, dtype=out_dtype)
attn = torch.empty((B, 3, WINDOW_SIZE, T, H), device=q.device, dtype=torch.float32)
if B == 0 or T == 0 or H == 0:
return q_mix, k_mix, v_mix, attn
scale = 1.0 / math.sqrt(float(D))
block_t = DEFAULT_BLOCK_T
grid = (B, H, triton.cdiv(T, block_t))
_triton_swgdn2_local_swa_fwd[grid](
q, k, v, k_n, p_rot,
q_mix, k_mix, v_mix, attn,
q.stride(0), q.stride(1), q.stride(2), q.stride(3),
k.stride(0), k.stride(1), k.stride(2), k.stride(3),
v.stride(0), v.stride(1), v.stride(2), v.stride(3),
k_n.stride(0), k_n.stride(1), k_n.stride(2), k_n.stride(3),
p_rot.stride(0), p_rot.stride(1), p_rot.stride(2), p_rot.stride(3),
q_mix.stride(0), q_mix.stride(1), q_mix.stride(2), q_mix.stride(3),
k_mix.stride(0), k_mix.stride(1), k_mix.stride(2), k_mix.stride(3),
v_mix.stride(0), v_mix.stride(1), v_mix.stride(2), v_mix.stride(3),
attn.stride(0), attn.stride(1), attn.stride(2), attn.stride(3), attn.stride(4),
T,
scale,
BLOCK_T=block_t,
HEAD_DIM=D,
num_warps=4,
)
return q_mix, k_mix, v_mix, attn
def _launch_triton_bwd(
d_q_mix: torch.Tensor,
d_k_mix: torch.Tensor,
d_v_mix: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
attn: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot)
d_q = torch.empty((B, T, H, D), device=q.device, dtype=q.dtype)
d_k = torch.empty((B, T, H, D), device=k.device, dtype=k.dtype)
d_v = torch.empty((B, T, H, D), device=v.device, dtype=v.dtype)
d_k_n = torch.empty((B, T, H, D), device=k_n.device, dtype=k_n.dtype)
d_p_rot_fp32 = torch.zeros((3, WINDOW_SIZE, H, D), device=p_rot.device, dtype=torch.float32)
if B == 0 or T == 0 or H == 0:
return d_q, d_k, d_v, d_k_n, d_p_rot_fp32.to(p_rot.dtype)
scale = 1.0 / math.sqrt(float(D))
block_t = DEFAULT_BLOCK_T
grid = (B, H, triton.cdiv(T, block_t))
_triton_swgdn2_local_swa_bwd[grid](
d_q_mix, d_k_mix, d_v_mix,
q, k, v, k_n, p_rot, attn,
d_q, d_k, d_v, d_k_n, d_p_rot_fp32,
d_q_mix.stride(0), d_q_mix.stride(1), d_q_mix.stride(2), d_q_mix.stride(3),
d_k_mix.stride(0), d_k_mix.stride(1), d_k_mix.stride(2), d_k_mix.stride(3),
d_v_mix.stride(0), d_v_mix.stride(1), d_v_mix.stride(2), d_v_mix.stride(3),
q.stride(0), q.stride(1), q.stride(2), q.stride(3),
k.stride(0), k.stride(1), k.stride(2), k.stride(3),
v.stride(0), v.stride(1), v.stride(2), v.stride(3),
k_n.stride(0), k_n.stride(1), k_n.stride(2), k_n.stride(3),
p_rot.stride(0), p_rot.stride(1), p_rot.stride(2), p_rot.stride(3),
d_p_rot_fp32.stride(0), d_p_rot_fp32.stride(1), d_p_rot_fp32.stride(2), d_p_rot_fp32.stride(3),
attn.stride(0), attn.stride(1), attn.stride(2), attn.stride(3), attn.stride(4),
d_q.stride(0), d_q.stride(1), d_q.stride(2), d_q.stride(3),
d_k.stride(0), d_k.stride(1), d_k.stride(2), d_k.stride(3),
d_v.stride(0), d_v.stride(1), d_v.stride(2), d_v.stride(3),
d_k_n.stride(0), d_k_n.stride(1), d_k_n.stride(2), d_k_n.stride(3),
T,
scale,
BLOCK_T=block_t,
HEAD_DIM=D,
num_warps=4,
)
return d_q, d_k, d_v, d_k_n, d_p_rot_fp32.to(p_rot.dtype)
def _pytorch_swgdn2_local_swa_fwd(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Exact PyTorch FP32-accumulated fallback matching SWGDN2LocalSWA Eq. 7-8."""
B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot)
out_dtype = q.dtype
scale = 1.0 / math.sqrt(float(D))
raw_scores = torch.einsum("bthd,xwhd->bxwth", k_n.float(), p_rot.float()) * scale
logits_w = [raw_scores[:, :, 0]]
for w in range(1, WINDOW_SIZE):
if T > w:
pad = torch.full(
(B, 3, w, H), NEG_INF_SCORE, device=q.device, dtype=torch.float32
)
logits_w.append(torch.cat([pad, raw_scores[:, :, w, : T - w]], dim=2))
else:
logits_w.append(
torch.full((B, 3, T, H), NEG_INF_SCORE, device=q.device, dtype=torch.float32)
)
attn = F.softmax(torch.stack(logits_w, dim=2), dim=2) # [B, 3, 4, T, H] FP32
def _mix(x_b: torch.Tensor, a_b: torch.Tensor) -> torch.Tensor:
xf = x_b.float()
u = a_b[:, 0].unsqueeze(-1) * xf
for w in range(1, WINDOW_SIZE):
if T > w:
x_shift = F.pad(xf[:, : T - w], (0, 0, 0, 0, w, 0))
u = u + a_b[:, w].unsqueeze(-1) * x_shift
return F.silu(u).to(out_dtype)
q_mix = _mix(q, attn[:, 0])
k_mix = _mix(k, attn[:, 1])
v_mix = _mix(v, attn[:, 2])
return q_mix, k_mix, v_mix, attn
def _pytorch_swgdn2_local_swa_bwd(
d_q_mix: torch.Tensor,
d_k_mix: torch.Tensor,
d_v_mix: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
attn: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Exact analytical PyTorch backward fallback (matches Triton backward 1-to-1)."""
B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot)
scale = 1.0 / math.sqrt(float(D))
kn_f = k_n.float()
prot_f = p_rot.float()
attn_f = attn.float()
xs = (q.float(), k.float(), v.float())
gs = (d_q_mix.float(), d_k_mix.float(), d_v_mix.float())
dxs = []
d_k_n_f = torch.zeros((B, T, H, D), device=q.device, dtype=torch.float32)
d_p_rot_f = torch.zeros((3, WINDOW_SIZE, H, D), device=p_rot.device, dtype=torch.float32)
for x_idx in range(3):
xf = xs[x_idx]
gf = gs[x_idx]
a_b = attn_f[:, x_idx] # [B, 4, T, H]
# Shifted views x_shift[w][b, t] = xf[b, t - w] (0 for t < w)
x_shifts = [xf]
for w in range(1, WINDOW_SIZE):
if T > w:
x_shifts.append(F.pad(xf[:, : T - w], (0, 0, 0, 0, w, 0)))
else:
x_shifts.append(torch.zeros_like(xf))
u = sum(a_b[:, w].unsqueeze(-1) * x_shifts[w] for w in range(WINDOW_SIZE))
sig = torch.sigmoid(u)
du = gf * sig * (1.0 + u * (1.0 - sig)) # [B, T, H, D]
# da[w] = sum_d du[t] * x[t - w]
da = torch.stack([(du * x_shifts[w]).sum(dim=-1) for w in range(WINDOW_SIZE)], dim=1)
d_dot = (a_b * da).sum(dim=1, keepdim=True)
ds = a_b * (da - d_dot) # [B, 4, T, H]
# dX[i] = sum_{w: i + w < T} a[w, i + w] * du[i + w]
dx_f = a_b[:, 0].unsqueeze(-1) * du
for w in range(1, WINDOW_SIZE):
if T > w:
dx_f[:, : T - w] = dx_f[:, : T - w] + a_b[:, w, w:].unsqueeze(-1) * du[:, w:]
dxs.append(dx_f)
# dk_n[i] += scale * sum_{w: i + w < T} ds[w, i + w] * p_rot[x, w]
# dp_rot[x, w] += scale * sum_{b, i: i + w < T} ds[w, i + w] * k_n[i]
for w in range(WINDOW_SIZE):
if T > w:
ds_w = ds[:, w, w:] * scale # [B, T - w, H]
d_k_n_f[:, : T - w] = d_k_n_f[:, : T - w] + (
ds_w.unsqueeze(-1) * prot_f[x_idx, w].view(1, 1, H, D)
)
d_p_rot_f[x_idx, w] = torch.einsum("bth,bthd->hd", ds_w, kn_f[:, : T - w])
return (
dxs[0].to(q.dtype),
dxs[1].to(k.dtype),
dxs[2].to(v.dtype),
d_k_n_f.to(k_n.dtype),
d_p_rot_f.to(p_rot.dtype),
)
# =========================================================================
# 3. torch.library.custom_op (PyTorch 2.4+ zero graph breaks) + Fallback
# =========================================================================
_HAS_CUSTOM_OP = hasattr(torch, "library") and hasattr(torch.library, "custom_op")
if _HAS_CUSTOM_OP:
@torch.library.custom_op("swgdn2::local_swa_fwd", mutates_args=())
def _swgdn2_local_swa_fwd_op(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
if _swgdn2_can_use_triton(q, k, v, k_n, p_rot):
return _launch_triton_fwd(q, k, v, k_n, p_rot)
return _pytorch_swgdn2_local_swa_fwd(q, k, v, k_n, p_rot)
@_swgdn2_local_swa_fwd_op.register_fake
def _swgdn2_local_swa_fwd_fake(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot)
q_mix = q.new_empty((B, T, H, D), dtype=q.dtype)
k_mix = k.new_empty((B, T, H, D), dtype=q.dtype)
v_mix = v.new_empty((B, T, H, D), dtype=q.dtype)
attn = q.new_empty((B, 3, WINDOW_SIZE, T, H), dtype=torch.float32)
return q_mix, k_mix, v_mix, attn
@torch.library.custom_op("swgdn2::local_swa_bwd", mutates_args=())
def _swgdn2_local_swa_bwd_op(
d_q_mix: torch.Tensor,
d_k_mix: torch.Tensor,
d_v_mix: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
attn: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
if _swgdn2_can_use_triton(q, k, v, k_n, p_rot):
return _launch_triton_bwd(
d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn
)
return _pytorch_swgdn2_local_swa_bwd(
d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn
)
@_swgdn2_local_swa_bwd_op.register_fake
def _swgdn2_local_swa_bwd_fake(
d_q_mix: torch.Tensor,
d_k_mix: torch.Tensor,
d_v_mix: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
attn: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
B, T, H, D = _validate_inputs(q, k, v, k_n, p_rot)
return (
q.new_empty((B, T, H, D), dtype=q.dtype),
k.new_empty((B, T, H, D), dtype=k.dtype),
v.new_empty((B, T, H, D), dtype=v.dtype),
k_n.new_empty((B, T, H, D), dtype=k_n.dtype),
p_rot.new_empty((3, WINDOW_SIZE, H, D), dtype=p_rot.dtype),
)
def _setup_context(ctx, inputs, output):
q, k, v, k_n, p_rot = inputs
_q_mix, _k_mix, _v_mix, attn = output
ctx.save_for_backward(q, k, v, k_n, p_rot, attn)
def _backward_custom_op(ctx, d_q_mix, d_k_mix, d_v_mix, _d_attn):
q, k, v, k_n, p_rot, attn = ctx.saved_tensors
if d_q_mix is None:
d_q_mix = torch.zeros_like(q)
if d_k_mix is None:
d_k_mix = torch.zeros_like(k)
if d_v_mix is None:
d_v_mix = torch.zeros_like(v)
return _swgdn2_local_swa_bwd_op(
d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn
)
_swgdn2_local_swa_fwd_op.register_autograd(
_backward_custom_op, setup_context=_setup_context
)
class _FusedSWGDN2LocalSWAFunction(torch.autograd.Function):
"""Standard autograd.Function fallback when torch.library.custom_op is unavailable."""
@staticmethod
def forward(ctx, q, k, v, k_n, p_rot):
if _swgdn2_can_use_triton(q, k, v, k_n, p_rot):
q_mix, k_mix, v_mix, attn = _launch_triton_fwd(q, k, v, k_n, p_rot)
else:
q_mix, k_mix, v_mix, attn = _pytorch_swgdn2_local_swa_fwd(q, k, v, k_n, p_rot)
ctx.save_for_backward(q, k, v, k_n, p_rot, attn)
return q_mix, k_mix, v_mix
@staticmethod
def backward(ctx, d_q_mix, d_k_mix, d_v_mix):
q, k, v, k_n, p_rot, attn = ctx.saved_tensors
if d_q_mix is None:
d_q_mix = torch.zeros_like(q)
if d_k_mix is None:
d_k_mix = torch.zeros_like(k)
if d_v_mix is None:
d_v_mix = torch.zeros_like(v)
if _swgdn2_can_use_triton(q, k, v, k_n, p_rot):
return _launch_triton_bwd(
d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn
)
return _pytorch_swgdn2_local_swa_bwd(
d_q_mix, d_k_mix, d_v_mix, q, k, v, k_n, p_rot, attn
)
def fused_swgdn2_local_swa(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_n: torch.Tensor,
p_rot: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""1-pass fused SWGDN2LocalSWA (arXiv:2611.33257 Eq. 7-8).
Args:
q: `[B, T, H, D]` projected queries (may be non-contiguous view of `g_qkv`)
k: `[B, T, H, D]` projected keys
v: `[B, T, H, D]` projected values
k_n: `[B, T, H, D]` RMSNorm-normalized keys `rms_norm(k, k_norm)`
p_rot: `[3, 4, H, D]` pre-rotated RMSNorm pseudo-queries
Returns:
`(q_mix, k_mix, v_mix)` each `[B, T, H, D]` in `q.dtype`.
"""
if _HAS_CUSTOM_OP:
q_mix, k_mix, v_mix, _ = _swgdn2_local_swa_fwd_op(q, k, v, k_n, p_rot)
return q_mix, k_mix, v_mix
return _FusedSWGDN2LocalSWAFunction.apply(q, k, v, k_n, p_rot)
# =============================================================================
# --- Kernel Suite 5: Fused MoD Gate Score & Scaled Scatter-Add ---
if _HAS_TRITON:
@triton.jit
def _triton_mod_gate_score_fwd(
h_ptr,
w_ptr,
b_ptr,
c_gate_ptr,
out_ptr,
sig_ptr,
N,
D,
stride_hn,
stride_hd,
HAS_BIAS: tl.constexpr,
HAS_CGATE: tl.constexpr,
SAVE_SIG: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""Fused linear(D -> 1) + sigmoid + optional c_gate multiply in 1 pass.
Grid: (cdiv(N, BLOCK_N),)
For locked-in D=1024, BLOCK_D=1024 -> inner D-loop runs exactly 1 iteration.
"""
pid_n = tl.program_id(0).to(tl.int64)
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N).to(tl.int64)
mask_n = offs_n < N
acc = tl.zeros((BLOCK_N,), dtype=tl.float32)
for d_start in range(0, D, BLOCK_D):
offs_d = tl.arange(0, BLOCK_D).to(tl.int64) + d_start
mask_d = offs_d < D
w_val = tl.load(w_ptr + offs_d, mask=mask_d, other=0.0).to(tl.float32)
h_ptrs = h_ptr + offs_n[:, None] * stride_hn + offs_d[None, :] * stride_hd
h_val = tl.load(
h_ptrs, mask=mask_n[:, None] & mask_d[None, :], other=0.0
).to(tl.float32)
acc += tl.sum(h_val * w_val[None, :], axis=1)
if HAS_BIAS:
b_val = tl.load(b_ptr).to(tl.float32)
acc = acc + b_val
sig = tl.sigmoid(acc)
if SAVE_SIG:
tl.store(sig_ptr + offs_n, sig, mask=mask_n)
if HAS_CGATE:
cg = tl.load(c_gate_ptr + offs_n, mask=mask_n, other=1.0).to(tl.float32)
eff = sig * cg
else:
eff = sig
tl.store(out_ptr + offs_n, eff.to(out_ptr.dtype.element_ty), mask=mask_n)
@triton.jit
def _triton_mod_gate_score_bwd_persistent(
d_eff_ptr,
h_ptr,
w_ptr,
sig_ptr,
c_gate_ptr,
d_h_ptr,
d_w_fp32_ptr,
d_b_fp32_ptr,
N,
D,
num_tiles,
stride_hn,
stride_hd,
stride_dhn,
stride_dhd,
HAS_CGATE: tl.constexpr,
NEED_DH: tl.constexpr,
NEED_DW: tl.constexpr,
NEED_DB: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""Persistent-grid backward pass for `fused_mod_gate_score`.
Computes `d_h_ffn [N, D]`, `d_w [1, D]` (accumulated in FP32), and
`d_b [1]` (accumulated in FP32) in ONE Triton kernel launch.
Treats `c_gate` as a detached constant (matching `forward_backbone`).
Grid: (num_progs, cdiv(D, BLOCK_D))
For locked-in D=1024, BLOCK_D=1024 -> Grid is (num_progs, 1).
"""
pid_p = tl.program_id(0).to(tl.int64)
num_progs = tl.num_programs(0).to(tl.int64)
pid_d = tl.program_id(1).to(tl.int64)
offs_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64)
mask_d = offs_d < D
# Load w once into registers for the entire persistent tile loop
if NEED_DH:
w_reg = tl.load(w_ptr + offs_d, mask=mask_d, other=0.0).to(tl.float32)
else:
w_reg = tl.zeros((BLOCK_D,), dtype=tl.float32)
dw_acc = tl.zeros((BLOCK_D,), dtype=tl.float32)
db_acc = tl.zeros((1,), dtype=tl.float32)
tile_idx = pid_p
while tile_idx < num_tiles:
offs_n = tile_idx * BLOCK_N + tl.arange(0, BLOCK_N).to(tl.int64)
mask_n = offs_n < N
d_eff = tl.load(d_eff_ptr + offs_n, mask=mask_n, other=0.0).to(tl.float32)
sig = tl.load(sig_ptr + offs_n, mask=mask_n, other=0.0).to(tl.float32)
if HAS_CGATE:
cg = tl.load(c_gate_ptr + offs_n, mask=mask_n, other=0.0).to(tl.float32)
delta = d_eff * cg * sig * (1.0 - sig)
else:
delta = d_eff * sig * (1.0 - sig)
delta = tl.where(mask_n, delta, 0.0)
if NEED_DB:
db_acc += tl.sum(delta, axis=0)
if NEED_DH:
dh_tile = delta[:, None] * w_reg[None, :]
dh_ptrs = (
d_h_ptr
+ offs_n[:, None] * stride_dhn
+ offs_d[None, :] * stride_dhd
)
tl.store(
dh_ptrs,
dh_tile.to(d_h_ptr.dtype.element_ty),
mask=mask_n[:, None] & mask_d[None, :],
)
if NEED_DW:
h_ptrs = (
h_ptr + offs_n[:, None] * stride_hn + offs_d[None, :] * stride_hd
)
h_tile = tl.load(
h_ptrs, mask=mask_n[:, None] & mask_d[None, :], other=0.0
).to(tl.float32)
dw_acc += tl.sum(delta[:, None] * h_tile, axis=0)
tile_idx += num_progs
if NEED_DW:
tl.atomic_add(d_w_fp32_ptr + offs_d, dw_acc, mask=mask_d)
if NEED_DB:
if pid_d == 0:
tl.atomic_add(d_b_fp32_ptr + tl.arange(0, 1), db_acc)
@triton.jit
def _triton_mod_scaled_scatter_add_fwd(
out_ptr,
top_idx_ptr,
top_g_ptr,
bridge_scale_ptr,
m_sel_ptr,
N,
K,
D,
stride_on,
stride_od,
stride_mk,
stride_md,
BLOCK_D: tl.constexpr,
):
"""Fused scaled scatter-add without materializing `mem_delta [K, D]`.
For each k in 0..K-1:
out[top_idx[k], d] += top_g[k] * bridge_scale * m_sel[k, d]
Safe without atomics because `top_idx` from `torch.topk` / `nonzero`
contains strictly unique token indices.
Grid: (K, cdiv(D, BLOCK_D))
For locked-in K=8192, D=1024, BLOCK_D=1024 -> Grid is (8192, 1).
"""
pid_k = tl.program_id(0).to(tl.int64)
if pid_k >= K:
return
pid_d = tl.program_id(1).to(tl.int64)
tok_idx = tl.load(top_idx_ptr + pid_k).to(tl.int64)
if (tok_idx < 0) | (tok_idx >= N):
return
g_k = tl.load(top_g_ptr + pid_k).to(tl.float32)
bs = tl.load(bridge_scale_ptr).to(tl.float32)
scale = g_k * bs
offs_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64)
mask_d = offs_d < D
m_ptrs = m_sel_ptr + pid_k * stride_mk + offs_d * stride_md
m_val = tl.load(m_ptrs, mask=mask_d, other=0.0).to(tl.float32)
o_ptrs = out_ptr + tok_idx * stride_on + offs_d * stride_od
cur = tl.load(o_ptrs, mask=mask_d, other=0.0).to(tl.float32)
updated = cur + scale * m_val
tl.store(o_ptrs, updated.to(out_ptr.dtype.element_ty), mask=mask_d)
@triton.jit
def _triton_mod_scaled_scatter_add_bwd_persistent(
d_out_ptr,
top_idx_ptr,
top_g_ptr,
bridge_scale_ptr,
m_sel_ptr,
d_m_sel_ptr,
d_top_g_ptr,
d_bs_fp32_ptr,
N,
K,
D,
stride_gon,
stride_god,
stride_mk,
stride_md,
stride_dmk,
stride_dmd,
NEED_DM: tl.constexpr,
NEED_DG: tl.constexpr,
NEED_DBS: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""Persistent-grid fused backward pass for `fused_mod_scaled_scatter_add`.
Given `d_out [N, D]`:
- d_m_sel[k, d] = (top_g[k] * bridge_scale) * d_out[top_idx[k], d]
- d_top_g[k] = bridge_scale * sum_d(d_out[top_idx[k], d] * m_sel[k, d])
- d_bridge_scale = sum_k(top_g[k] * sum_d(d_out[top_idx[k], d] * m_sel[k, d]))
(d_ffn_out = d_out is returned directly by the autograd wrapper.)
Grid: (num_progs,)
For locked-in D=1024, BLOCK_D=1024 -> inner D-loop runs exactly 1 iteration,
and `d_bridge_scale` requires only `num_progs` (~128) FP32 atomic adds total.
"""
pid_p = tl.program_id(0).to(tl.int64)
num_progs = tl.num_programs(0).to(tl.int64)
bs = tl.load(bridge_scale_ptr).to(tl.float32)
dbs_acc = tl.zeros((1,), dtype=tl.float32)
k_idx = pid_p
while k_idx < K:
tok_idx = tl.load(top_idx_ptr + k_idx).to(tl.int64)
valid_tok = (tok_idx >= 0) & (tok_idx < N)
g_k = tl.load(top_g_ptr + k_idx).to(tl.float32)
scale = g_k * bs
dot_k = tl.zeros((1,), dtype=tl.float32)
for d_start in range(0, D, BLOCK_D):
offs_d = tl.arange(0, BLOCK_D).to(tl.int64) + d_start
mask_d = (offs_d < D) & valid_tok
go_ptrs = d_out_ptr + tok_idx * stride_gon + offs_d * stride_god
go_val = tl.load(go_ptrs, mask=mask_d, other=0.0).to(tl.float32)
if NEED_DM:
dm_ptrs = d_m_sel_ptr + k_idx * stride_dmk + offs_d * stride_dmd
dm_val = scale * go_val
tl.store(
dm_ptrs,
dm_val.to(d_m_sel_ptr.dtype.element_ty),
mask=offs_d < D,
)
if NEED_DG | NEED_DBS:
m_ptrs = m_sel_ptr + k_idx * stride_mk + offs_d * stride_md
m_val = tl.load(m_ptrs, mask=mask_d, other=0.0).to(tl.float32)
dot_k += tl.sum(go_val * m_val, axis=0)
if NEED_DG:
dg_val = bs * dot_k
tl.store(
d_top_g_ptr + k_idx + tl.arange(0, 1),
dg_val.to(d_top_g_ptr.dtype.element_ty),
)
if NEED_DBS:
dbs_acc += g_k * dot_k
k_idx += num_progs
if NEED_DBS:
tl.atomic_add(d_bs_fp32_ptr + tl.arange(0, 1), dbs_acc)
# =============================================================================
# 2. LAUNCH HELPERS & PYTORCH FALLBACKS
# =============================================================================
def _next_pow2_capped(val: int, cap: int = 1024) -> int:
if val <= 1:
return 1
p = 1 << (val - 1).bit_length()
return min(p, cap)
def _get_num_sms(device: "torch.device") -> int:
try:
return int(torch.cuda.get_device_properties(device).multi_processor_count)
except Exception:
return 128
def _mod_can_use_triton(tensor: "torch.Tensor") -> bool:
return bool(_HAS_TRITON and _HAS_TORCH and tensor.is_cuda)
# --- Kernel 1: fused_mod_gate_score impls ---
def _pytorch_mod_gate_score_fwd(
h_2d: "torch.Tensor",
w_1d: "torch.Tensor",
bias: Optional["torch.Tensor"],
c_gate_1d: Optional["torch.Tensor"],
out_dtype: "torch.dtype",
) -> Tuple["torch.Tensor", "torch.Tensor"]:
logits = torch.mv(h_2d.float(), w_1d.float())
if bias is not None:
logits = logits + bias.reshape(-1)[0].float()
sig = torch.sigmoid(logits)
eff = sig * c_gate_1d.float() if c_gate_1d is not None else sig
return eff.to(out_dtype), sig
def _pytorch_mod_gate_score_bwd(
d_eff_1d: "torch.Tensor",
h_2d: "torch.Tensor",
w_1d: "torch.Tensor",
sig_1d: "torch.Tensor",
c_gate_1d: Optional["torch.Tensor"],
need_dh: bool,
need_dw: bool,
need_db: bool,
h_dtype: "torch.dtype",
w_shape: Tuple[int, ...],
w_dtype: "torch.dtype",
b_shape: Optional[Tuple[int, ...]],
b_dtype: Optional["torch.dtype"],
) -> Tuple[Optional["torch.Tensor"], Optional["torch.Tensor"], Optional["torch.Tensor"]]:
delta = d_eff_1d.float() * sig_1d.float() * (1.0 - sig_1d.float())
if c_gate_1d is not None:
delta = delta * c_gate_1d.float()
d_h = None
if need_dh:
d_h = (delta.unsqueeze(1) * w_1d.float().unsqueeze(0)).to(h_dtype)
d_w = None
if need_dw:
# Explicitly reshape to w_shape (guaranteed [1, D] for nn.Linear(D, 1)!)
d_w = torch.matmul(delta, h_2d.float()).reshape(w_shape).to(w_dtype)
d_b = None
if need_db and b_shape is not None and b_dtype is not None:
d_b = delta.sum().reshape(b_shape).to(b_dtype)
return d_h, d_w, d_b
def _mod_gate_score_fwd_impl(
h_2d: "torch.Tensor",
w_1d: "torch.Tensor",
bias: Optional["torch.Tensor"],
c_gate_1d: Optional["torch.Tensor"],
out_dtype: "torch.dtype",
save_sig: bool,
) -> Tuple["torch.Tensor", Optional["torch.Tensor"]]:
N, D = h_2d.shape
if N == 0:
empty_out = torch.empty((0,), device=h_2d.device, dtype=out_dtype)
empty_sig = torch.empty((0,), device=h_2d.device, dtype=torch.float32) if save_sig else None
return empty_out, empty_sig
if not _mod_can_use_triton(h_2d):
eff, sig = _pytorch_mod_gate_score_fwd(h_2d, w_1d, bias, c_gate_1d, out_dtype)
return eff, (sig if save_sig else None)
w_c = w_1d.contiguous()
b_c = bias.reshape(-1).contiguous() if bias is not None else w_c
cg_c = c_gate_1d.contiguous() if c_gate_1d is not None else w_c
out = torch.empty((N,), device=h_2d.device, dtype=out_dtype)
sig = torch.empty((N,), device=h_2d.device, dtype=torch.float32) if save_sig else out
BLOCK_D = _next_pow2_capped(D, 1024)
BLOCK_N = 4
grid = (triton.cdiv(N, BLOCK_N),)
_triton_mod_gate_score_fwd[grid](
h_2d,
w_c,
b_c,
cg_c,
out,
sig,
N,
D,
h_2d.stride(0),
h_2d.stride(1),
HAS_BIAS=(bias is not None),
HAS_CGATE=(c_gate_1d is not None),
SAVE_SIG=save_sig,
BLOCK_N=BLOCK_N,
BLOCK_D=BLOCK_D,
num_warps=4,
)
return out, (sig if save_sig else None)
def _mod_gate_score_bwd_impl(
d_eff_1d: "torch.Tensor",
h_2d: "torch.Tensor",
w_1d: "torch.Tensor",
sig_1d: "torch.Tensor",
c_gate_1d: Optional["torch.Tensor"],
need_dh: bool,
need_dw: bool,
need_db: bool,
h_dtype: "torch.dtype",
w_shape: Tuple[int, ...],
w_dtype: "torch.dtype",
b_shape: Optional[Tuple[int, ...]],
b_dtype: Optional["torch.dtype"],
) -> Tuple[Optional["torch.Tensor"], Optional["torch.Tensor"], Optional["torch.Tensor"]]:
N, D = h_2d.shape
if N == 0:
d_h = torch.empty((0, D), device=h_2d.device, dtype=h_dtype) if need_dh else None
d_w = torch.zeros(w_shape, device=h_2d.device, dtype=w_dtype) if need_dw else None
d_b = (
torch.zeros(b_shape, device=h_2d.device, dtype=b_dtype)
if (need_db and b_shape is not None and b_dtype is not None)
else None
)
return d_h, d_w, d_b
if not _mod_can_use_triton(h_2d):
return _pytorch_mod_gate_score_bwd(
d_eff_1d,
h_2d,
w_1d,
sig_1d,
c_gate_1d,
need_dh,
need_dw,
need_db,
h_dtype,
w_shape,
w_dtype,
b_shape,
b_dtype,
)
d_eff_c = d_eff_1d.contiguous()
w_c = w_1d.contiguous()
sig_c = sig_1d.contiguous()
cg_c = c_gate_1d.contiguous() if c_gate_1d is not None else sig_c
d_h = torch.empty((N, D), device=h_2d.device, dtype=h_dtype) if need_dh else h_2d
d_w_fp32 = torch.zeros((D,), device=h_2d.device, dtype=torch.float32) if need_dw else sig_c
d_b_fp32 = torch.zeros((1,), device=h_2d.device, dtype=torch.float32) if need_db else sig_c
BLOCK_D = _next_pow2_capped(D, 1024)
BLOCK_N = 4
num_tiles = triton.cdiv(N, BLOCK_N)
num_progs = min(max(1, _get_num_sms(h_2d.device)), num_tiles)
grid = (num_progs, triton.cdiv(D, BLOCK_D))
_triton_mod_gate_score_bwd_persistent[grid](
d_eff_c,
h_2d,
w_c,
sig_c,
cg_c,
d_h,
d_w_fp32,
d_b_fp32,
N,
D,
num_tiles,
h_2d.stride(0),
h_2d.stride(1),
d_h.stride(0),
d_h.stride(1),
HAS_CGATE=(c_gate_1d is not None),
NEED_DH=need_dh,
NEED_DW=need_dw,
NEED_DB=need_db,
BLOCK_N=BLOCK_N,
BLOCK_D=BLOCK_D,
num_warps=4,
)
out_dh = d_h if need_dh else None
out_dw = d_w_fp32.reshape(w_shape).to(w_dtype) if need_dw else None
out_db = (
d_b_fp32.reshape(b_shape).to(b_dtype)
if (need_db and b_shape is not None and b_dtype is not None)
else None
)
return out_dh, out_dw, out_db
# --- Kernel 2: fused_mod_scaled_scatter_add impls ---
def _pytorch_mod_scaled_scatter_add_fwd(
out_2d: "torch.Tensor",
top_idx_1d: "torch.Tensor",
top_g_1d: "torch.Tensor",
bridge_scale_1d: "torch.Tensor",
m_sel_2d: "torch.Tensor",
) -> "torch.Tensor":
scale = (top_g_1d.float() * bridge_scale_1d.reshape(-1)[0].float()).unsqueeze(-1)
delta = (scale * m_sel_2d.float()).to(out_2d.dtype)
out_2d.index_add_(0, top_idx_1d.long(), delta)
return out_2d
def _pytorch_mod_scaled_scatter_add_bwd(
d_out_2d: "torch.Tensor",
top_idx_1d: "torch.Tensor",
top_g_1d: "torch.Tensor",
bridge_scale_1d: "torch.Tensor",
m_sel_2d: "torch.Tensor",
need_dm: bool,
need_dg: bool,
need_dbs: bool,
m_dtype: "torch.dtype",
g_dtype: "torch.dtype",
bs_shape: Tuple[int, ...],
bs_dtype: "torch.dtype",
) -> Tuple[Optional["torch.Tensor"], Optional["torch.Tensor"], Optional["torch.Tensor"]]:
go_sel = d_out_2d.index_select(0, top_idx_1d.long()).float()
g_f = top_g_1d.float()
bs_f = bridge_scale_1d.reshape(-1)[0].float()
d_m_sel = None
if need_dm:
d_m_sel = ((g_f * bs_f).unsqueeze(-1) * go_sel).to(m_dtype)
d_top_g = None
d_bs = None
if need_dg or need_dbs:
dot_k = (go_sel * m_sel_2d.float()).sum(dim=-1)
if need_dg:
d_top_g = (bs_f * dot_k).to(g_dtype)
if need_dbs:
d_bs = (g_f * dot_k).sum().reshape(bs_shape).to(bs_dtype)
return d_m_sel, d_top_g, d_bs
def _mod_scaled_scatter_add_fwd_impl(
out_2d: "torch.Tensor",
top_idx_1d: "torch.Tensor",
top_g_1d: "torch.Tensor",
bridge_scale_1d: "torch.Tensor",
m_sel_2d: "torch.Tensor",
) -> "torch.Tensor":
N, D = out_2d.shape
K = top_idx_1d.numel()
if K == 0 or N == 0:
return out_2d
if not _mod_can_use_triton(out_2d):
return _pytorch_mod_scaled_scatter_add_fwd(
out_2d, top_idx_1d, top_g_1d, bridge_scale_1d, m_sel_2d
)
idx_c = top_idx_1d.contiguous()
g_c = top_g_1d.contiguous()
bs_c = bridge_scale_1d.reshape(-1).contiguous()
m_c = m_sel_2d.contiguous()
BLOCK_D = _next_pow2_capped(D, 1024)
grid = (K, triton.cdiv(D, BLOCK_D))
_triton_mod_scaled_scatter_add_fwd[grid](
out_2d,
idx_c,
g_c,
bs_c,
m_c,
N,
K,
D,
out_2d.stride(0),
out_2d.stride(1),
m_c.stride(0),
m_c.stride(1),
BLOCK_D=BLOCK_D,
num_warps=4,
)
return out_2d
def _mod_scaled_scatter_add_bwd_impl(
d_out_2d: "torch.Tensor",
top_idx_1d: "torch.Tensor",
top_g_1d: "torch.Tensor",
bridge_scale_1d: "torch.Tensor",
m_sel_2d: "torch.Tensor",
need_dm: bool,
need_dg: bool,
need_dbs: bool,
m_dtype: "torch.dtype",
g_dtype: "torch.dtype",
bs_shape: Tuple[int, ...],
bs_dtype: "torch.dtype",
) -> Tuple[Optional["torch.Tensor"], Optional["torch.Tensor"], Optional["torch.Tensor"]]:
N, D = d_out_2d.shape
K = top_idx_1d.numel()
if K == 0 or N == 0:
d_m = torch.empty((0, D), device=d_out_2d.device, dtype=m_dtype) if need_dm else None
d_g = torch.empty((0,), device=d_out_2d.device, dtype=g_dtype) if need_dg else None
d_bs = (
torch.zeros(bs_shape, device=d_out_2d.device, dtype=bs_dtype) if need_dbs else None
)
return d_m, d_g, d_bs
if not _mod_can_use_triton(d_out_2d):
return _pytorch_mod_scaled_scatter_add_bwd(
d_out_2d,
top_idx_1d,
top_g_1d,
bridge_scale_1d,
m_sel_2d,
need_dm,
need_dg,
need_dbs,
m_dtype,
g_dtype,
bs_shape,
bs_dtype,
)
idx_c = top_idx_1d.contiguous()
g_c = top_g_1d.contiguous()
bs_c = bridge_scale_1d.reshape(-1).contiguous()
m_c = m_sel_2d.contiguous()
d_m_sel = torch.empty((K, D), device=d_out_2d.device, dtype=m_dtype) if need_dm else m_c
d_top_g = torch.empty((K,), device=d_out_2d.device, dtype=g_dtype) if need_dg else g_c
d_bs_fp32 = (
torch.zeros((1,), device=d_out_2d.device, dtype=torch.float32) if need_dbs else bs_c
)
BLOCK_D = _next_pow2_capped(D, 1024)
num_progs = min(max(1, _get_num_sms(d_out_2d.device)), K)
grid = (num_progs,)
_triton_mod_scaled_scatter_add_bwd_persistent[grid](
d_out_2d,
idx_c,
g_c,
bs_c,
m_c,
d_m_sel,
d_top_g,
d_bs_fp32,
N,
K,
D,
d_out_2d.stride(0),
d_out_2d.stride(1),
m_c.stride(0),
m_c.stride(1),
d_m_sel.stride(0),
d_m_sel.stride(1),
NEED_DM=need_dm,
NEED_DG=need_dg,
NEED_DBS=need_dbs,
BLOCK_D=BLOCK_D,
num_warps=4,
)
out_dm = d_m_sel if need_dm else None
out_dg = d_top_g if need_dg else None
out_dbs = d_bs_fp32.reshape(bs_shape).to(bs_dtype) if need_dbs else None
return out_dm, out_dg, out_dbs
# =============================================================================
# 3. PYTORCH AUTOGRAD WRAPPERS & PUBLIC ENTRY POINTS
# =============================================================================
if True:
class FusedModGateScoreFunction(torch.autograd.Function):
@staticmethod
def forward(
ctx,
h_ffn: "torch.Tensor",
weight: "torch.Tensor",
bias: Optional["torch.Tensor"],
c_gate: Optional["torch.Tensor"],
out_dtype: "torch.dtype",
) -> "torch.Tensor":
orig_h_shape = tuple(h_ffn.shape)
D = orig_h_shape[-1]
h_2d = h_ffn.reshape(-1, D)
w_1d = weight.reshape(D)
cg_1d = c_gate.reshape(-1) if c_gate is not None else None
need_bwd = (
ctx.needs_input_grad[0]
or ctx.needs_input_grad[1]
or (bias is not None and ctx.needs_input_grad[2])
)
eff_score, sig = _mod_gate_score_fwd_impl(
h_2d, w_1d, bias, cg_1d, out_dtype=out_dtype, save_sig=need_bwd
)
ctx.orig_h_shape = orig_h_shape
ctx.h_dtype = h_ffn.dtype
ctx.w_shape = tuple(weight.shape)
ctx.w_dtype = weight.dtype
ctx.b_shape = tuple(bias.shape) if bias is not None else None
ctx.b_dtype = bias.dtype if bias is not None else None
ctx.has_cgate = cg_1d is not None
if need_bwd:
if cg_1d is not None:
ctx.save_for_backward(h_2d, w_1d, sig, cg_1d)
else:
ctx.save_for_backward(h_2d, w_1d, sig)
return eff_score
@staticmethod
def backward(ctx, d_eff_score: "torch.Tensor"):
saved = ctx.saved_tensors
if ctx.has_cgate:
h_2d, w_1d, sig, cg_1d = saved
else:
h_2d, w_1d, sig = saved
cg_1d = None
need_dh = ctx.needs_input_grad[0]
need_dw = ctx.needs_input_grad[1]
need_db = (ctx.b_shape is not None) and ctx.needs_input_grad[2]
d_h_2d, d_w, d_b = _mod_gate_score_bwd_impl(
d_eff_score.reshape(-1),
h_2d,
w_1d,
sig,
cg_1d,
need_dh=need_dh,
need_dw=need_dw,
need_db=need_db,
h_dtype=ctx.h_dtype,
w_shape=ctx.w_shape,
w_dtype=ctx.w_dtype,
b_shape=ctx.b_shape,
b_dtype=ctx.b_dtype,
)
d_h = d_h_2d.view(ctx.orig_h_shape) if d_h_2d is not None else None
# c_gate is treated as a detached constant (matching forward_backbone)
return d_h, d_w, d_b, None, None
class FusedModScaledScatterAddFunction(torch.autograd.Function):
@staticmethod
def forward(
ctx,
ffn_out: "torch.Tensor",
top_idx: "torch.Tensor",
top_g: "torch.Tensor",
bridge_scale: "torch.Tensor",
m_sel: "torch.Tensor",
inplace: bool,
) -> "torch.Tensor":
orig_shape = tuple(ffn_out.shape)
D = orig_shape[-1]
can_inplace = (
inplace
and ffn_out.is_contiguous()
and not (ffn_out.is_leaf and ffn_out.requires_grad)
)
if can_inplace:
out = ffn_out
ctx.mark_dirty(ffn_out)
else:
out = ffn_out.clone().contiguous()
out_2d = out.view(-1, D)
idx_1d = top_idx.reshape(-1)
g_1d = top_g.reshape(-1)
bs_1d = bridge_scale.reshape(-1)
m_2d = m_sel.reshape(-1, D)
_mod_scaled_scatter_add_fwd_impl(out_2d, idx_1d, g_1d, bs_1d, m_2d)
ctx.ffn_dtype = ffn_out.dtype
ctx.m_dtype = m_sel.dtype
ctx.g_shape = tuple(top_g.shape)
ctx.g_dtype = top_g.dtype
ctx.bs_shape = tuple(bridge_scale.shape)
ctx.bs_dtype = bridge_scale.dtype
ctx.D = D
ctx.save_for_backward(idx_1d, g_1d, bs_1d, m_2d)
return out
@staticmethod
def backward(ctx, d_out: "torch.Tensor"):
idx_1d, g_1d, bs_1d, m_2d = ctx.saved_tensors
need_dffn = ctx.needs_input_grad[0]
need_dg = ctx.needs_input_grad[2]
need_dbs = ctx.needs_input_grad[3]
need_dm = ctx.needs_input_grad[4]
d_ffn_out = None
if need_dffn:
d_ffn_out = d_out if d_out.dtype == ctx.ffn_dtype else d_out.to(ctx.ffn_dtype)
d_m_sel = None
d_top_g = None
d_bs = None
if need_dm or need_dg or need_dbs:
d_out_2d = d_out.reshape(-1, ctx.D)
d_m_sel, d_g_1d, d_bs = _mod_scaled_scatter_add_bwd_impl(
d_out_2d,
idx_1d,
g_1d,
bs_1d,
m_2d,
need_dm=need_dm,
need_dg=need_dg,
need_dbs=need_dbs,
m_dtype=ctx.m_dtype,
g_dtype=ctx.g_dtype,
bs_shape=ctx.bs_shape,
bs_dtype=ctx.bs_dtype,
)
if d_g_1d is not None:
d_top_g = d_g_1d.view(ctx.g_shape)
return d_ffn_out, None, d_top_g, d_bs, d_m_sel, None
def fused_mod_gate_score(
h_ffn: "torch.Tensor",
weight: "torch.Tensor",
bias: Optional["torch.Tensor"] = None,
c_gate: Optional["torch.Tensor"] = None,
out_dtype: Optional["torch.dtype"] = None,
) -> "torch.Tensor":
"""Fused MoD gate scoring: `eff_score[n] = sigmoid(dot(h_ffn[n], w) + b) * c_gate[n]`.
Drop-in replacement in `train_l2_gddr7_wikipedia.py` (lines 3858-3865):
eff_score = fused_mod_gate_score(
h_ffn_mg,
self.mem_need_gate.weight,
self.mem_need_gate.bias,
contraction_gate,
)
Args:
h_ffn: Input hidden states `[..., D]` (e.g. `[B, T, 1024]` or `[N, 1024]`).
weight: Gate projection weight `[1, D]` (guaranteed `[1, D]` gradient shape).
bias: Optional gate bias `[1]`.
c_gate: Optional detached contraction gate `[...]` (flattened to `[N]`) or `None`.
out_dtype: Output dtype (defaults to `weight.dtype`, matching eager `nn.Linear`).
Returns:
1D `eff_score` tensor of shape `[N]`.
"""
if not _HAS_TORCH:
raise RuntimeError("PyTorch is required to call fused_mod_gate_score.")
target_dtype = out_dtype if out_dtype is not None else weight.dtype
if not torch.is_grad_enabled():
D = h_ffn.shape[-1]
eff, _ = _mod_gate_score_fwd_impl(
h_ffn.reshape(-1, D),
weight.reshape(D),
bias,
c_gate.reshape(-1) if c_gate is not None else None,
out_dtype=target_dtype,
save_sig=False,
)
return eff
return FusedModGateScoreFunction.apply(h_ffn, weight, bias, c_gate, target_dtype)
def fused_mod_scaled_scatter_add(
ffn_out: "torch.Tensor",
top_idx: "torch.Tensor",
top_g: "torch.Tensor",
bridge_scale: "torch.Tensor",
m_sel: "torch.Tensor",
inplace: bool = True,
) -> "torch.Tensor":
"""Fused scaled scatter-add: `ffn_out[top_idx[k]] += top_g[k] * bridge_scale * m_sel[k]`.
Drop-in replacement in `train_l2_gddr7_wikipedia.py` (lines 3884-3892):
ffn_out = fused_mod_scaled_scatter_add(
ffn_out, top_idx, top_g, bridge.bridge_scale, m_sel, inplace=True
)
Note on telemetry (`collect_telemetry=True`, line 3896):
`b_rms` can be computed without materializing `mem_delta` via:
b_rms = (
(top_g.float() * bridge.bridge_scale.float()).pow(2)
* m_sel.float().pow(2).mean(dim=-1)
).mean().sqrt().item()
Args:
ffn_out: Target tensor `[..., D]` (e.g. `[B, T, 1024]` or `[N, 1024]`).
top_idx: Strictly unique selected token indices `[K]` (int32 or int64).
top_g: Selected token gate scores `[K]`.
bridge_scale: Scalar `()` or `[1]` bridge scale tensor.
m_sel: Selected memory outputs `[K, D]`.
inplace: If `True` (default), updates `ffn_out` in-place when contiguous and
non-leaf, avoiding the 64 MiB `ffn_out.clone()` allocation.
Returns:
Updated tensor with the same shape and dtype as `ffn_out`.
"""
if not _HAS_TORCH:
raise RuntimeError("PyTorch is required to call fused_mod_scaled_scatter_add.")
if not torch.is_grad_enabled():
D = ffn_out.shape[-1]
out = ffn_out if (inplace and ffn_out.is_contiguous()) else ffn_out.clone().contiguous()
_mod_scaled_scatter_add_fwd_impl(
out.view(-1, D),
top_idx.reshape(-1),
top_g.reshape(-1),
bridge_scale.reshape(-1),
m_sel.reshape(-1, D),
)
return out
return FusedModScaledScatterAddFunction.apply(
ffn_out, top_idx, top_g, bridge_scale, m_sel, inplace
)
# =============================================================================
# --- Kernel Suite 6: Fused SwiGLU-FP8, RMSNorm-FP8 & CachedFP8Linear ---
def _is_triton_cuda_tensor(t: torch.Tensor) -> bool:
return HAS_TRITON and t.is_cuda
def _can_use_fp8(t: torch.Tensor) -> bool:
return FP8_DTYPE is not None and t.is_cuda
# ==============================================================================
# TRITON KERNELS
# ==============================================================================
if HAS_TRITON:
@triton.jit
def _quantize_rowwise_fp8_kernel(
x_ptr,
y_fp8_ptr,
y_scale_ptr,
stride_x_row,
stride_y_row,
N: tl.constexpr,
BLOCK_N: tl.constexpr,
):
"""Rowwise dynamic FP8 E4M3FN quantization (handles arbitrary N via masking)."""
row = tl.program_id(0).to(tl.int64)
x_row_ptr = x_ptr + row * stride_x_row
y_row_ptr = y_fp8_ptr + row * stride_y_row
# Vector max across tiles avoids repeated cross-lane warp reductions inside the loop
row_amax_vec = tl.zeros((BLOCK_N,), dtype=tl.float32)
for col_start in range(0, N, BLOCK_N):
offs = col_start + tl.arange(0, BLOCK_N)
mask = offs < N
x = tl.load(x_row_ptr + offs, mask=mask, other=0.0).to(tl.float32)
row_amax_vec = tl.maximum(row_amax_vec, tl.abs(x))
row_amax = tl.max(row_amax_vec, axis=0)
scale = tl.maximum(row_amax * (1.0 / 448.0), 1e-12)
inv_scale = 1.0 / scale
tl.store(y_scale_ptr + row, scale)
for col_start in range(0, N, BLOCK_N):
offs = col_start + tl.arange(0, BLOCK_N)
mask = offs < N
x = tl.load(x_row_ptr + offs, mask=mask, other=0.0).to(tl.float32)
q = tl.minimum(tl.maximum(x * inv_scale, -448.0), 448.0)
tl.store(y_row_ptr + offs, q.to(y_fp8_ptr.dtype.element_ty), mask=mask)
@triton.jit
def _silu_mul_fp8_fwd_kernel(
gate_ptr,
up_ptr,
y_fp8_ptr,
y_scale_ptr,
y_bf16_ptr,
stride_gate_row,
stride_up_row,
stride_y_fp8_row,
stride_y_bf16_row,
N: tl.constexpr,
BLOCK_N: tl.constexpr,
WRITE_BF16: tl.constexpr,
):
"""Fused SwiGLU + per-row FP8 E4M3FN quantization.
Computes y = silu(gate) * up in FP32, per-row scale = max(amax(|y|) / 448.0, 1e-12),
and writes y_fp8 [M, N] (float8_e4m3fn) + y_scale [M] (fp32), plus optional BF16 y.
Handles N = 2688 (21 * 128) cleanly with power-of-2 BLOCK_N and mask = offs < N.
"""
row = tl.program_id(0).to(tl.int64)
gate_row_ptr = gate_ptr + row * stride_gate_row
up_row_ptr = up_ptr + row * stride_up_row
y_fp8_row_ptr = y_fp8_ptr + row * stride_y_fp8_row
y_bf16_row_ptr = y_bf16_ptr + row * stride_y_bf16_row
# Pass 1: compute row amax in FP32 (and optionally write BF16 output).
# 5376 * 2B = 10.75 KiB per row stays resident in L1 cache for Pass 2.
row_amax_vec = tl.zeros((BLOCK_N,), dtype=tl.float32)
for col_start in range(0, N, BLOCK_N):
offs = col_start + tl.arange(0, BLOCK_N)
mask = offs < N
g = tl.load(gate_row_ptr + offs, mask=mask, other=0.0).to(tl.float32)
u = tl.load(up_row_ptr + offs, mask=mask, other=0.0).to(tl.float32)
sig = tl.sigmoid(g)
y = (g * sig) * u
if WRITE_BF16:
tl.store(
y_bf16_row_ptr + offs,
y.to(y_bf16_ptr.dtype.element_ty),
mask=mask,
)
row_amax_vec = tl.maximum(row_amax_vec, tl.abs(y))
row_amax = tl.max(row_amax_vec, axis=0)
scale = tl.maximum(row_amax * (1.0 / 448.0), 1e-12)
inv_scale = 1.0 / scale
tl.store(y_scale_ptr + row, scale)
# Pass 2: quantize exact FP32 y to FP8 E4M3FN using per-row scale
for col_start in range(0, N, BLOCK_N):
offs = col_start + tl.arange(0, BLOCK_N)
mask = offs < N
g = tl.load(gate_row_ptr + offs, mask=mask, other=0.0).to(tl.float32)
u = tl.load(up_row_ptr + offs, mask=mask, other=0.0).to(tl.float32)
sig = tl.sigmoid(g)
y = (g * sig) * u
q = tl.minimum(tl.maximum(y * inv_scale, -448.0), 448.0)
tl.store(
y_fp8_row_ptr + offs,
q.to(y_fp8_ptr.dtype.element_ty),
mask=mask,
)
@triton.jit
def _silu_mul_bwd_kernel(
dy_ptr,
gate_ptr,
up_ptr,
d_gate_ptr,
d_up_ptr,
stride_dy_row,
stride_gate_row,
stride_up_row,
stride_dgate_row,
stride_dup_row,
N: tl.constexpr,
BLOCK_N: tl.constexpr,
):
"""Single-pass fused SwiGLU backward kernel.
d_up = dy * silu(gate)
d_gate = dy * up * sig * (1 + gate * (1 - sig))
"""
row = tl.program_id(0).to(tl.int64)
col_block = tl.program_id(1)
offs = col_block * BLOCK_N + tl.arange(0, BLOCK_N)
mask = offs < N
dy = tl.load(dy_ptr + row * stride_dy_row + offs, mask=mask, other=0.0).to(tl.float32)
g = tl.load(gate_ptr + row * stride_gate_row + offs, mask=mask, other=0.0).to(tl.float32)
u = tl.load(up_ptr + row * stride_up_row + offs, mask=mask, other=0.0).to(tl.float32)
sig = tl.sigmoid(g)
silu_g = g * sig
d_up = dy * silu_g
d_gate = dy * u * sig * (1.0 + g * (1.0 - sig))
tl.store(
d_gate_ptr + row * stride_dgate_row + offs,
d_gate.to(d_gate_ptr.dtype.element_ty),
mask=mask,
)
tl.store(
d_up_ptr + row * stride_dup_row + offs,
d_up.to(d_up_ptr.dtype.element_ty),
mask=mask,
)
@triton.jit
def _rmsnorm_fp8_fwd_kernel(
x_ptr,
gamma_ptr,
y_fp8_ptr,
y_scale_ptr,
rstd_ptr,
y_bf16_ptr,
stride_x_row,
stride_y_fp8_row,
stride_y_bf16_row,
eps,
D: tl.constexpr,
BLOCK_D: tl.constexpr,
HAS_GAMMA: tl.constexpr,
WRITE_BF16: tl.constexpr,
):
"""Single-pass RMSNorm + per-row FP8 E4M3FN quantization for D = 1024 (power of 2)."""
row = tl.program_id(0).to(tl.int64)
offs = tl.arange(0, BLOCK_D)
mask = offs < D
x = tl.load(x_ptr + row * stride_x_row + offs, mask=mask, other=0.0).to(tl.float32)
mean_sq = tl.sum(x * x, axis=0) * (1.0 / D)
rstd = tl.rsqrt(mean_sq + eps)
tl.store(rstd_ptr + row, rstd)
y = x * rstd
if HAS_GAMMA:
gamma = tl.load(gamma_ptr + offs, mask=mask, other=0.0).to(tl.float32)
y = y * gamma
if WRITE_BF16:
tl.store(
y_bf16_ptr + row * stride_y_bf16_row + offs,
y.to(y_bf16_ptr.dtype.element_ty),
mask=mask,
)
amax = tl.max(tl.abs(y), axis=0)
scale = tl.maximum(amax * (1.0 / 448.0), 1e-12)
inv_scale = 1.0 / scale
q = tl.minimum(tl.maximum(y * inv_scale, -448.0), 448.0)
tl.store(
y_fp8_ptr + row * stride_y_fp8_row + offs,
q.to(y_fp8_ptr.dtype.element_ty),
mask=mask,
)
tl.store(y_scale_ptr + row, scale)
@triton.jit
def _rmsnorm_bwd_dx_partial_dgamma_kernel(
dy_ptr,
x_ptr,
rstd_ptr,
gamma_ptr,
dx_ptr,
partial_dgamma_ptr,
stride_dy_row,
stride_x_row,
stride_dx_row,
stride_pg_row,
M,
rows_per_group,
D: tl.constexpr,
BLOCK_D: tl.constexpr,
HAS_GAMMA: tl.constexpr,
):
"""Single-pass RMSNorm backward computing exact dx and FP32 partial dgamma.
Each program handles a contiguous stripe of rows, keeping `gamma` and
`dgamma_acc` in FP32 registers (zero atomic_add contention).
"""
pid = tl.program_id(0).to(tl.int64)
offs = tl.arange(0, BLOCK_D)
mask = offs < D
if HAS_GAMMA:
gamma = tl.load(gamma_ptr + offs, mask=mask, other=0.0).to(tl.float32)
dgamma_acc = tl.zeros((BLOCK_D,), dtype=tl.float32)
row_start = pid * rows_per_group
row_end = tl.minimum(row_start + rows_per_group, M)
for row in range(row_start, row_end):
x = tl.load(x_ptr + row * stride_x_row + offs, mask=mask, other=0.0).to(tl.float32)
dy = tl.load(dy_ptr + row * stride_dy_row + offs, mask=mask, other=0.0).to(tl.float32)
rstd = tl.load(rstd_ptr + row).to(tl.float32)
x_hat = x * rstd
if HAS_GAMMA:
g = dy * gamma
dgamma_acc += dy * x_hat
else:
g = dy
c = tl.sum(g * x_hat, axis=0) * (1.0 / D)
dx = rstd * (g - c * x_hat)
tl.store(
dx_ptr + row * stride_dx_row + offs,
dx.to(dx_ptr.dtype.element_ty),
mask=mask,
)
if HAS_GAMMA:
tl.store(
partial_dgamma_ptr + pid * stride_pg_row + offs,
dgamma_acc,
mask=mask,
)
@triton.jit
def _rmsnorm_dgamma_reduce_kernel(
partial_dgamma_ptr,
dgamma_ptr,
stride_pg_row,
num_groups,
D: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""Final FP32 reduction of partial_dgamma [num_groups, D] -> dgamma [D]."""
offs = tl.arange(0, BLOCK_D)
mask = offs < D
acc = tl.zeros((BLOCK_D,), dtype=tl.float32)
for g in range(0, num_groups):
acc += tl.load(partial_dgamma_ptr + g * stride_pg_row + offs, mask=mask, other=0.0)
tl.store(dgamma_ptr + offs, acc.to(dgamma_ptr.dtype.element_ty), mask=mask)
# ==============================================================================
# QUANTIZATION HELPERS
# ==============================================================================
def quantize_rowwise_fp8(
x: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Rowwise dynamic FP8 E4M3FN quantization of a 2D tensor [M, N].
Returns:
(x_fp8 [M, N] float8_e4m3fn, x_scale [M, 1] float32)
"""
assert x.ndim == 2, f"Expected 2D tensor, got shape {tuple(x.shape)}"
M, N = x.shape
x_contig = x.contiguous()
if _is_triton_cuda_tensor(x_contig) and FP8_DTYPE is not None:
y_fp8 = torch.empty((M, N), device=x.device, dtype=FP8_DTYPE)
y_scale = torch.empty((M, 1), device=x.device, dtype=torch.float32)
if M > 0 and N > 0:
block_n = 256 if N >= 256 else max(16, 1 << (N - 1).bit_length())
_quantize_rowwise_fp8_kernel[(M,)](
x_contig,
y_fp8,
y_scale,
x_contig.stride(0),
y_fp8.stride(0),
N=N,
BLOCK_N=block_n,
num_warps=4,
)
return y_fp8, y_scale
# PyTorch fallback (CPU or no Triton)
x32 = x_contig.float()
amax = x32.abs().amax(dim=-1, keepdim=True)
scale = torch.clamp(amax / FP8_E4M3_MAX, min=FP8_SCALE_EPS)
q = torch.clamp(x32 / scale, -FP8_E4M3_MAX, FP8_E4M3_MAX)
out_dtype = FP8_DTYPE if FP8_DTYPE is not None else torch.float32
return q.to(out_dtype), scale
def quantize_tensorwise_fp8(
x: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Tensorwise dynamic FP8 E4M3FN quantization.
Returns:
(x_fp8 float8_e4m3fn, x_scale [1] float32)
"""
x32 = x.float()
amax = x32.abs().amax()
scale = torch.clamp(amax / FP8_E4M3_MAX, min=FP8_SCALE_EPS).reshape(1).to(torch.float32)
q = torch.clamp(x32 / scale, -FP8_E4M3_MAX, FP8_E4M3_MAX)
out_dtype = FP8_DTYPE if FP8_DTYPE is not None else torch.float32
return q.to(out_dtype), scale
# ==============================================================================
# COMPONENT 1: FUSED SWIGLU + FP8 QUANTIZATION (FWD & BWD)
# ==============================================================================
def fused_silu_mul_fp8_quant(
gate_up: torch.Tensor,
up: Optional[torch.Tensor] = None,
return_bf16: bool = False,
block_n: int = 256,
) -> Union[
Tuple[torch.Tensor, torch.Tensor],
Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
]:
"""Fused SwiGLU (`silu(gate) * up`) + per-row FP8 E4M3FN quantization.
Args:
gate_up: Either fused `[..., 2 * N]` tensor (e.g. `[M, 5376]`) when `up is None`,
or `gate [..., N]` tensor (e.g. `[M, 2688]`) when `up` is provided.
up: Optional separate `up [..., N]` tensor.
return_bf16: If True, also return BF16 `y` (useful for non-FP8 fallback).
block_n: Power-of-2 tile width (default 256; 128 also supported).
Returns:
`(y_fp8 [..., N], y_scale [..., 1])` or `(y_fp8, y_scale, y_bf16)`.
"""
if up is None:
assert gate_up.shape[-1] % 2 == 0, (
f"gate_up last dim must be even, got {gate_up.shape[-1]}"
)
orig_shape = gate_up.shape[:-1]
N = gate_up.shape[-1] // 2
gu_2d = gate_up.reshape(-1, 2 * N).contiguous()
M = gu_2d.shape[0]
gate_2d = gu_2d[:, :N]
up_2d = gu_2d[:, N:]
else:
assert gate_up.shape == up.shape, (
f"gate {tuple(gate_up.shape)} and up {tuple(up.shape)} must match"
)
orig_shape = gate_up.shape[:-1]
N = gate_up.shape[-1]
gate_2d = gate_up.reshape(-1, N).contiguous()
up_2d = up.reshape(-1, N).contiguous()
M = gate_2d.shape[0]
assert block_n > 0 and (block_n & (block_n - 1)) == 0, "block_n must be power of 2"
if _is_triton_cuda_tensor(gate_2d) and FP8_DTYPE is not None:
y_fp8 = torch.empty((M, N), device=gate_2d.device, dtype=FP8_DTYPE)
y_scale = torch.empty((M, 1), device=gate_2d.device, dtype=torch.float32)
y_bf16 = (
torch.empty((M, N), device=gate_2d.device, dtype=torch.bfloat16)
if return_bf16
else torch.empty((1,), device=gate_2d.device, dtype=torch.bfloat16)
)
if M > 0 and N > 0:
_silu_mul_fp8_fwd_kernel[(M,)](
gate_2d,
up_2d,
y_fp8,
y_scale,
y_bf16,
gate_2d.stride(0),
up_2d.stride(0),
y_fp8.stride(0),
y_bf16.stride(0) if return_bf16 else 0,
N=N,
BLOCK_N=block_n,
WRITE_BF16=return_bf16,
num_warps=4,
)
y_fp8 = y_fp8.reshape(*orig_shape, N)
y_scale = y_scale.reshape(*orig_shape, 1)
if return_bf16:
return y_fp8, y_scale, y_bf16.reshape(*orig_shape, N)
return y_fp8, y_scale
# Reference PyTorch fallback
g32 = gate_2d.float()
u32 = up_2d.float()
y32 = F.silu(g32) * u32
amax = y32.abs().amax(dim=-1, keepdim=True)
scale = torch.clamp(amax / FP8_E4M3_MAX, min=FP8_SCALE_EPS)
q = torch.clamp(y32 / scale, -FP8_E4M3_MAX, FP8_E4M3_MAX)
out_dtype = FP8_DTYPE if FP8_DTYPE is not None else torch.float32
y_fp8 = q.to(out_dtype).reshape(*orig_shape, N)
y_scale = scale.reshape(*orig_shape, 1)
if return_bf16:
return y_fp8, y_scale, y32.to(torch.bfloat16).reshape(*orig_shape, N)
return y_fp8, y_scale
def fused_silu_mul_bwd(
dy: torch.Tensor,
gate_up: torch.Tensor,
up: Optional[torch.Tensor] = None,
block_n: int = 256,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""Single-pass fused SwiGLU backward kernel.
Args:
dy: Upstream gradient `[..., N]`.
gate_up: Either fused `[..., 2 * N]` when `up is None`, or `gate [..., N]`.
up: Optional separate `up [..., N]`.
block_n: Power-of-2 tile width (default 256).
Returns:
`d_gate_up [..., 2 * N]` if `up is None`, else `(d_gate [..., N], d_up [..., N])`.
"""
assert block_n > 0 and (block_n & (block_n - 1)) == 0, "block_n must be power of 2"
if up is None:
orig_shape = dy.shape[:-1]
N = dy.shape[-1]
assert gate_up.shape[-1] == 2 * N, (
f"Expected gate_up last dim {2 * N}, got {gate_up.shape[-1]}"
)
dy_2d = dy.reshape(-1, N).contiguous()
gu_2d = gate_up.reshape(-1, 2 * N).contiguous()
M = dy_2d.shape[0]
gate_2d = gu_2d[:, :N]
up_2d = gu_2d[:, N:]
d_gate_up = torch.empty((M, 2 * N), device=gate_up.device, dtype=gate_up.dtype)
d_gate_2d = d_gate_up[:, :N]
d_up_2d = d_gate_up[:, N:]
fused_out = True
else:
orig_shape = dy.shape[:-1]
N = dy.shape[-1]
dy_2d = dy.reshape(-1, N).contiguous()
gate_2d = gate_up.reshape(-1, N).contiguous()
up_2d = up.reshape(-1, N).contiguous()
M = dy_2d.shape[0]
d_gate_2d = torch.empty((M, N), device=gate_up.device, dtype=gate_up.dtype)
d_up_2d = torch.empty((M, N), device=up.device, dtype=up.dtype)
fused_out = False
if _is_triton_cuda_tensor(dy_2d):
if M > 0 and N > 0:
grid = (M, triton.cdiv(N, block_n))
_silu_mul_bwd_kernel[grid](
dy_2d,
gate_2d,
up_2d,
d_gate_2d,
d_up_2d,
dy_2d.stride(0),
gate_2d.stride(0),
up_2d.stride(0),
d_gate_2d.stride(0),
d_up_2d.stride(0),
N=N,
BLOCK_N=block_n,
num_warps=4,
)
else:
dy32 = dy_2d.float()
g32 = gate_2d.float()
u32 = up_2d.float()
sig = torch.sigmoid(g32)
d_up_2d.copy_((dy32 * (g32 * sig)).to(d_up_2d.dtype))
d_gate_2d.copy_((dy32 * u32 * sig * (1.0 + g32 * (1.0 - sig))).to(d_gate_2d.dtype))
if fused_out:
return d_gate_up.reshape(*orig_shape, 2 * N)
return d_gate_2d.reshape(*orig_shape, N), d_up_2d.reshape(*orig_shape, N)
# ==============================================================================
# COMPONENT 2: FUSED RMSNORM + FP8 QUANTIZATION (FWD & BWD) FOR D = 1024
# ==============================================================================
def fused_rmsnorm_fp8_quant(
x: torch.Tensor,
gamma: Optional[torch.Tensor] = None,
eps: float = DEFAULT_EPS,
return_bf16: bool = False,
) -> Union[
Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor],
]:
"""Single-pass fused RMSNorm + per-row FP8 E4M3FN quantization.
Optimized for D = 1024 (power of 2); works for any D <= 8192 via power-of-2 BLOCK_D.
Args:
x: Input tensor `[..., D]` (BF16/FP16/FP32).
gamma: Optional affine weight `[D]` (FP32/BF16).
eps: Epsilon for numerical stability (default 1e-6).
return_bf16: If True, also return BF16 normalized output `y_bf16`.
Returns:
`(y_fp8 [..., D], y_scale [..., 1], rstd [..., 1])`, or with `y_bf16` appended.
"""
orig_shape = x.shape[:-1]
D = x.shape[-1]
x_2d = x.reshape(-1, D).contiguous()
M = x_2d.shape[0]
has_gamma = gamma is not None
gamma_contig = (
gamma.contiguous()
if has_gamma
else torch.empty((1,), device=x.device, dtype=torch.float32)
)
if _is_triton_cuda_tensor(x_2d) and FP8_DTYPE is not None:
block_d = triton.next_power_of_2(D)
y_fp8 = torch.empty((M, D), device=x.device, dtype=FP8_DTYPE)
y_scale = torch.empty((M, 1), device=x.device, dtype=torch.float32)
rstd = torch.empty((M, 1), device=x.device, dtype=torch.float32)
y_bf16 = (
torch.empty((M, D), device=x.device, dtype=torch.bfloat16)
if return_bf16
else torch.empty((1,), device=x.device, dtype=torch.bfloat16)
)
if M > 0 and D > 0:
num_warps = 4 if block_d <= 1024 else 8
_rmsnorm_fp8_fwd_kernel[(M,)](
x_2d,
gamma_contig,
y_fp8,
y_scale,
rstd,
y_bf16,
x_2d.stride(0),
y_fp8.stride(0),
y_bf16.stride(0) if return_bf16 else 0,
eps,
D=D,
BLOCK_D=block_d,
HAS_GAMMA=has_gamma,
WRITE_BF16=return_bf16,
num_warps=num_warps,
)
y_fp8 = y_fp8.reshape(*orig_shape, D)
y_scale = y_scale.reshape(*orig_shape, 1)
rstd = rstd.reshape(*orig_shape, 1)
if return_bf16:
return y_fp8, y_scale, rstd, y_bf16.reshape(*orig_shape, D)
return y_fp8, y_scale, rstd
# Reference PyTorch fallback
x32 = x_2d.float()
rstd = torch.rsqrt(x32.pow(2).mean(dim=-1, keepdim=True) + eps)
y32 = x32 * rstd
if has_gamma:
y32 = y32 * gamma_contig.float()
amax = y32.abs().amax(dim=-1, keepdim=True)
scale = torch.clamp(amax / FP8_E4M3_MAX, min=FP8_SCALE_EPS)
q = torch.clamp(y32 / scale, -FP8_E4M3_MAX, FP8_E4M3_MAX)
out_dtype = FP8_DTYPE if FP8_DTYPE is not None else torch.float32
y_fp8 = q.to(out_dtype).reshape(*orig_shape, D)
y_scale = scale.reshape(*orig_shape, 1)
rstd = rstd.reshape(*orig_shape, 1)
if return_bf16:
return y_fp8, y_scale, rstd, y32.to(torch.bfloat16).reshape(*orig_shape, D)
return y_fp8, y_scale, rstd
def fused_rmsnorm_bwd(
dy: torch.Tensor,
x: torch.Tensor,
rstd: torch.Tensor,
gamma: Optional[torch.Tensor] = None,
max_groups: int = 128,
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
"""Exact single-pass Triton RMSNorm backward with FP32 partial reductions for dgamma.
Args:
dy: Upstream gradient `[..., D]`.
x: Forward input `[..., D]`.
rstd: Saved reciprocal RMS `[..., 1]` (or `[M]`) in FP32.
gamma: Optional forward weight `[D]`.
max_groups: Number of SM row groups for partial FP32 dgamma reduction.
Returns:
`(dx [..., D], dgamma [D] or None)`.
"""
orig_shape = x.shape[:-1]
D = x.shape[-1]
x_2d = x.reshape(-1, D).contiguous()
dy_2d = dy.reshape(-1, D).contiguous()
rstd_1d = rstd.reshape(-1).contiguous().float()
M = x_2d.shape[0]
has_gamma = gamma is not None
if _is_triton_cuda_tensor(x_2d):
dx_2d = torch.empty_like(x_2d)
if M == 0 or D == 0:
dgamma = torch.zeros_like(gamma) if has_gamma else None
return dx_2d.reshape(*orig_shape, D), dgamma
block_d = triton.next_power_of_2(D)
num_warps = 4 if block_d <= 1024 else 8
num_groups = min(M, max_groups)
rows_per_group = (M + num_groups - 1) // num_groups
num_groups = (M + rows_per_group - 1) // rows_per_group
gamma_contig = (
gamma.contiguous()
if has_gamma
else torch.empty((1,), device=x.device, dtype=torch.float32)
)
partial_dgamma = (
torch.empty((num_groups, D), device=x.device, dtype=torch.float32)
if has_gamma
else torch.empty((1, 1), device=x.device, dtype=torch.float32)
)
_rmsnorm_bwd_dx_partial_dgamma_kernel[(num_groups,)](
dy_2d,
x_2d,
rstd_1d,
gamma_contig,
dx_2d,
partial_dgamma,
dy_2d.stride(0),
x_2d.stride(0),
dx_2d.stride(0),
partial_dgamma.stride(0),
M,
rows_per_group,
D=D,
BLOCK_D=block_d,
HAS_GAMMA=has_gamma,
num_warps=num_warps,
)
dgamma: Optional[torch.Tensor] = None
if has_gamma:
dgamma = torch.empty((D,), device=x.device, dtype=gamma.dtype)
_rmsnorm_dgamma_reduce_kernel[(1,)](
partial_dgamma,
dgamma,
partial_dgamma.stride(0),
num_groups,
D=D,
BLOCK_D=block_d,
num_warps=num_warps,
)
return dx_2d.reshape(*orig_shape, D), dgamma
# Reference PyTorch fallback
x32 = x_2d.float()
dy32 = dy_2d.float()
rstd32 = rstd_1d.unsqueeze(-1)
x_hat = x32 * rstd32
if has_gamma:
g = dy32 * gamma.float()
dgamma = (dy32 * x_hat).sum(dim=0).to(gamma.dtype)
else:
g = dy32
dgamma = None
c = (g * x_hat).mean(dim=-1, keepdim=True)
dx_2d = (rstd32 * (g - c * x_hat)).to(x.dtype)
return dx_2d.reshape(*orig_shape, D), dgamma
# ==============================================================================
# COMPONENT 3: CachedFP8Linear (nn.Module + torch.autograd.Function)
# ==============================================================================
def _scaled_mm_rowwise_or_tensorwise(
a_fp8: torch.Tensor,
b_fp8_colmajor: torch.Tensor,
scale_a: torch.Tensor,
scale_b: torch.Tensor,
out_dtype: torch.dtype,
bias: Optional[torch.Tensor] = None,
use_fast_accum: bool = False,
) -> torch.Tensor:
"""Invoke `torch._scaled_mm` with rowwise/tensorwise scales.
`a_fp8`: [M, K] row-major float8_e4m3fn
`b_fp8_colmajor`: [K, N] column-major float8_e4m3fn (`stride(0) == 1`)
`scale_a`: [M, 1] (rowwise) or [1] (tensorwise) float32
`scale_b`: [1, N] (columnwise of B) or [1] (tensorwise) float32
"""
kwargs = {
"scale_a": scale_a,
"scale_b": scale_b,
"out_dtype": out_dtype,
"use_fast_accum": use_fast_accum,
}
if bias is not None:
kwargs["bias"] = bias.to(out_dtype)
res = torch._scaled_mm(a_fp8, b_fp8_colmajor, **kwargs)
# PyTorch < 2.5 returned (out, amax); >= 2.5 returns out directly.
if isinstance(res, tuple):
return res[0]
return res
def _shapes_ok_for_scaled_mm(M: int, K: int, N: int) -> bool:
return M > 0 and K > 0 and N > 0 and (M % 16 == 0) and (K % 16 == 0) and (N % 16 == 0)
class _CachedFP8LinearFunction(torch.autograd.Function):
"""Autograd function using cached FP8 weights `(w_fp8, w_scale, w_t_fp8, w_t_scale)`.
Forward:
Y = scaled_mm(X_fp8, W_fp8^T, x_scale, w_scale^T) + bias
Backward:
dX = scaled_mm(dY_fp8, W_t_fp8^T, dy_scale, w_t_scale^T)
dW = dY^T @ X (computed in BF16/input dtype using saved X)
db = dY.sum(dim=0)
Automatically falls back to BF16 `F.linear` if shapes are not 16-aligned or if
`torch._scaled_mm` raises a RuntimeError on `sm_120` scaling constraints.
"""
@staticmethod
def forward(
ctx,
x: torch.Tensor,
weight: torch.Tensor,
bias: Optional[torch.Tensor],
w_fp8: Optional[torch.Tensor],
w_scale: Optional[torch.Tensor],
w_t_fp8: Optional[torch.Tensor],
w_t_scale: Optional[torch.Tensor],
scaling_mode: str,
use_fast_accum: bool,
) -> torch.Tensor:
orig_shape = x.shape[:-1]
K = x.shape[-1]
N = weight.shape[0]
x_2d = x.reshape(-1, K)
M = x_2d.shape[0]
out_dtype = x.dtype if x.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16
used_fp8 = False
if (
w_fp8 is not None
and w_scale is not None
and _can_use_fp8(x_2d)
and _shapes_ok_for_scaled_mm(M, K, N)
and hasattr(torch, "_scaled_mm")
):
try:
if scaling_mode == "rowwise":
x_fp8, x_scale = quantize_rowwise_fp8(x_2d)
w_scale_b = w_scale.t() # [1, N]
fast_acc = False # rowwise scaled_mm requires use_fast_accum=False
else:
x_fp8, x_scale = quantize_tensorwise_fp8(x_2d)
w_scale_b = w_scale # [1]
fast_acc = use_fast_accum
# w_fp8 is [N, K] contiguous -> w_fp8.t() is [K, N] column-major
y_2d = _scaled_mm_rowwise_or_tensorwise(
x_fp8,
w_fp8.t(),
x_scale,
w_scale_b,
out_dtype=out_dtype,
bias=bias,
use_fast_accum=fast_acc,
)
used_fp8 = True
except (RuntimeError, NotImplementedError):
used_fp8 = False
if not used_fp8:
x_bf16 = x_2d.to(out_dtype)
w_bf16 = weight.to(out_dtype)
b_bf16 = bias.to(out_dtype) if bias is not None else None
y_2d = F.linear(x_bf16, w_bf16, b_bf16)
ctx.save_for_backward(x_2d, weight, w_t_fp8, w_t_scale)
ctx.has_bias = bias is not None
ctx.orig_dtype = x.dtype
ctx.scaling_mode = scaling_mode
ctx.use_fast_accum = use_fast_accum
ctx.used_fp8 = used_fp8
return y_2d.to(x.dtype).reshape(*orig_shape, N)
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
x_2d, weight, w_t_fp8, w_t_scale = ctx.saved_tensors
orig_shape = grad_output.shape[:-1]
N = grad_output.shape[-1]
K = weight.shape[1]
dy_2d = grad_output.reshape(-1, N)
M = dy_2d.shape[0]
comp_dtype = dy_2d.dtype if dy_2d.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16
dx = None
if ctx.needs_input_grad[0]:
dx_done = False
if (
ctx.used_fp8
and w_t_fp8 is not None
and w_t_scale is not None
and _can_use_fp8(dy_2d)
and _shapes_ok_for_scaled_mm(M, N, K)
and hasattr(torch, "_scaled_mm")
):
try:
if ctx.scaling_mode == "rowwise":
dy_fp8, dy_scale = quantize_rowwise_fp8(dy_2d)
wt_scale_b = w_t_scale.t() # [1, K]
fast_acc = False
else:
dy_fp8, dy_scale = quantize_tensorwise_fp8(dy_2d)
wt_scale_b = w_t_scale # [1]
fast_acc = ctx.use_fast_accum
# w_t_fp8 is [K, N] contiguous -> w_t_fp8.t() is [N, K] column-major
dx_2d = _scaled_mm_rowwise_or_tensorwise(
dy_fp8,
w_t_fp8.t(),
dy_scale,
wt_scale_b,
out_dtype=comp_dtype,
bias=None,
use_fast_accum=fast_acc,
)
dx_done = True
except (RuntimeError, NotImplementedError):
dx_done = False
if not dx_done:
dx_2d = torch.matmul(dy_2d.to(comp_dtype), weight.to(comp_dtype))
dx = dx_2d.to(ctx.orig_dtype).reshape(*orig_shape, K)
dw = None
if ctx.needs_input_grad[1]:
dw = torch.matmul(dy_2d.to(comp_dtype).t(), x_2d.to(comp_dtype)).to(weight.dtype)
db = None
if ctx.has_bias and ctx.needs_input_grad[2]:
db = dy_2d.sum(dim=0, dtype=torch.float32).to(weight.dtype)
return dx, dw, db, None, None, None, None, None, None
class _FusedRMSNormCachedFP8LinearFn(torch.autograd.Function):
"""End-to-end autograd fusion: `fused_rmsnorm_fp8_quant` -> `CachedFP8Linear`.
Avoids materializing a BF16 activation between RMSNorm and `qkv_fg_fused` / `w_gate_up`
in the forward pass while preserving exact Triton RMSNorm backward + cached FP8 dX.
"""
@staticmethod
def forward(
ctx,
x: torch.Tensor,
gamma: Optional[torch.Tensor],
eps: float,
weight: torch.Tensor,
bias: Optional[torch.Tensor],
w_fp8: Optional[torch.Tensor],
w_scale: Optional[torch.Tensor],
w_t_fp8: Optional[torch.Tensor],
w_t_scale: Optional[torch.Tensor],
scaling_mode: str,
) -> torch.Tensor:
orig_shape = x.shape[:-1]
K = x.shape[-1]
N = weight.shape[0]
M = x.numel() // K
out_dtype = x.dtype if x.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16
need_bf16 = not (
w_fp8 is not None
and w_scale is not None
and _can_use_fp8(x)
and _shapes_ok_for_scaled_mm(M, K, N)
and scaling_mode == "rowwise"
and hasattr(torch, "_scaled_mm")
)
res = fused_rmsnorm_fp8_quant(x, gamma, eps=eps, return_bf16=need_bf16)
if need_bf16:
y_fp8, y_scale, rstd, y_bf16 = res
else:
y_fp8, y_scale, rstd = res
y_bf16 = None
used_fp8 = False
if not need_bf16:
try:
out_2d = _scaled_mm_rowwise_or_tensorwise(
y_fp8.reshape(M, K),
w_fp8.t(),
y_scale.reshape(M, 1),
w_scale.t(),
out_dtype=out_dtype,
bias=bias,
use_fast_accum=False,
)
used_fp8 = True
except (RuntimeError, NotImplementedError):
used_fp8 = False
if not used_fp8:
if y_bf16 is None:
y_bf16 = y_fp8.to(out_dtype) * y_scale.to(out_dtype)
out_2d = F.linear(
y_bf16.reshape(M, K).to(out_dtype),
weight.to(out_dtype),
bias.to(out_dtype) if bias is not None else None,
)
ctx.save_for_backward(x, gamma, rstd, weight, w_t_fp8, w_t_scale)
ctx.has_bias = bias is not None
ctx.orig_dtype = x.dtype
ctx.used_fp8 = used_fp8
return out_2d.to(x.dtype).reshape(*orig_shape, N)
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
x, gamma, rstd, weight, w_t_fp8, w_t_scale = ctx.saved_tensors
orig_shape = grad_output.shape[:-1]
N = grad_output.shape[-1]
K = weight.shape[1]
dy_2d = grad_output.reshape(-1, N)
M = dy_2d.shape[0]
comp_dtype = dy_2d.dtype if dy_2d.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16
# 1. d_norm = dy @ W
d_norm_done = False
if (
ctx.used_fp8
and w_t_fp8 is not None
and w_t_scale is not None
and _can_use_fp8(dy_2d)
and _shapes_ok_for_scaled_mm(M, N, K)
and hasattr(torch, "_scaled_mm")
):
try:
dy_fp8, dy_scale = quantize_rowwise_fp8(dy_2d)
d_norm_2d = _scaled_mm_rowwise_or_tensorwise(
dy_fp8,
w_t_fp8.t(),
dy_scale,
w_t_scale.t(),
out_dtype=comp_dtype,
bias=None,
use_fast_accum=False,
)
d_norm_done = True
except (RuntimeError, NotImplementedError):
d_norm_done = False
if not d_norm_done:
d_norm_2d = torch.matmul(dy_2d.to(comp_dtype), weight.to(comp_dtype))
# 2. Exact single-pass Triton RMSNorm backward
dx, dgamma = fused_rmsnorm_bwd(d_norm_2d.reshape(*orig_shape, K), x, rstd, gamma)
# 3. dW = dy^T @ y_norm (recompute lightweight y_norm from x, rstd, gamma)
dw = None
if ctx.needs_input_grad[3]:
y_norm = x.reshape(M, K).float() * rstd.reshape(M, 1).float()
if gamma is not None:
y_norm = y_norm * gamma.float()
dw = torch.matmul(dy_2d.to(comp_dtype).t(), y_norm.to(comp_dtype)).to(weight.dtype)
db = None
if ctx.has_bias and ctx.needs_input_grad[4]:
db = dy_2d.sum(dim=0, dtype=torch.float32).to(weight.dtype)
return dx, dgamma, None, dw, db, None, None, None, None, None
class _FusedSiLUMulCachedFP8DownFn(torch.autograd.Function):
"""End-to-end autograd fusion: `fused_silu_mul_fp8_quant` -> `CachedFP8Linear` (`w_down`).
Eliminates materializing BF16 `silu(gate) * up` [M, 2688] before `w_down` and runs
1-pass `fused_silu_mul_bwd` in backward.
"""
@staticmethod
def forward(
ctx,
gate_up: torch.Tensor,
weight: torch.Tensor,
bias: Optional[torch.Tensor],
w_fp8: Optional[torch.Tensor],
w_scale: Optional[torch.Tensor],
w_t_fp8: Optional[torch.Tensor],
w_t_scale: Optional[torch.Tensor],
scaling_mode: str,
) -> torch.Tensor:
orig_shape = gate_up.shape[:-1]
K = gate_up.shape[-1] // 2 # 2688
N = weight.shape[0] # 1024
M = gate_up.numel() // (2 * K)
out_dtype = gate_up.dtype if gate_up.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16
need_bf16 = not (
w_fp8 is not None
and w_scale is not None
and _can_use_fp8(gate_up)
and _shapes_ok_for_scaled_mm(M, K, N)
and scaling_mode == "rowwise"
and hasattr(torch, "_scaled_mm")
)
res = fused_silu_mul_fp8_quant(gate_up, return_bf16=need_bf16)
if need_bf16:
mid_fp8, mid_scale, mid_bf16 = res
else:
mid_fp8, mid_scale = res
mid_bf16 = None
used_fp8 = False
if not need_bf16:
try:
out_2d = _scaled_mm_rowwise_or_tensorwise(
mid_fp8.reshape(M, K),
w_fp8.t(),
mid_scale.reshape(M, 1),
w_scale.t(),
out_dtype=out_dtype,
bias=bias,
use_fast_accum=False,
)
used_fp8 = True
except (RuntimeError, NotImplementedError):
used_fp8 = False
if not used_fp8:
if mid_bf16 is None:
mid_bf16 = mid_fp8.to(out_dtype) * mid_scale.to(out_dtype)
out_2d = F.linear(
mid_bf16.reshape(M, K).to(out_dtype),
weight.to(out_dtype),
bias.to(out_dtype) if bias is not None else None,
)
ctx.save_for_backward(gate_up, mid_fp8, mid_scale, weight, w_t_fp8, w_t_scale)
ctx.has_bias = bias is not None
ctx.orig_dtype = gate_up.dtype
ctx.used_fp8 = used_fp8
return out_2d.to(gate_up.dtype).reshape(*orig_shape, N)
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
gate_up, mid_fp8, mid_scale, weight, w_t_fp8, w_t_scale = ctx.saved_tensors
orig_shape = grad_output.shape[:-1]
N = grad_output.shape[-1]
K = weight.shape[1]
dy_2d = grad_output.reshape(-1, N)
M = dy_2d.shape[0]
comp_dtype = dy_2d.dtype if dy_2d.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16
# 1. d_mid = dy @ W_down
d_mid_done = False
if (
ctx.used_fp8
and w_t_fp8 is not None
and w_t_scale is not None
and _can_use_fp8(dy_2d)
and _shapes_ok_for_scaled_mm(M, N, K)
and hasattr(torch, "_scaled_mm")
):
try:
dy_fp8, dy_scale = quantize_rowwise_fp8(dy_2d)
d_mid_2d = _scaled_mm_rowwise_or_tensorwise(
dy_fp8,
w_t_fp8.t(),
dy_scale,
w_t_scale.t(),
out_dtype=comp_dtype,
bias=None,
use_fast_accum=False,
)
d_mid_done = True
except (RuntimeError, NotImplementedError):
d_mid_done = False
if not d_mid_done:
d_mid_2d = torch.matmul(dy_2d.to(comp_dtype), weight.to(comp_dtype))
# 2. Single-pass Triton SwiGLU backward
d_gate_up = fused_silu_mul_bwd(d_mid_2d.reshape(*orig_shape, K), gate_up)
# 3. dW_down = dy^T @ mid (dequantize compact FP8 mid instead of storing BF16 mid)
dw = None
if ctx.needs_input_grad[1]:
mid_deq = mid_fp8.reshape(M, K).to(comp_dtype) * mid_scale.reshape(M, 1).to(comp_dtype)
dw = torch.matmul(dy_2d.to(comp_dtype).t(), mid_deq).to(weight.dtype)
db = None
if ctx.has_bias and ctx.needs_input_grad[2]:
db = dy_2d.sum(dim=0, dtype=torch.float32).to(weight.dtype)
return d_gate_up, dw, db, None, None, None, None, None
class CachedFP8Linear(nn.Module):
"""Drop-in `nn.Linear` wrapper that caches quantized FP8 weights across recurrent loops.
Designed for `shared_core` layers (`qkv_fg_fused`, `out_proj`, `w_gate_up`, `w_down`)
that are reused 24-40 loops x 4 grad-accum (~100x) per optimizer step.
Caches `(w_fp8, w_scale, w_t_fp8, w_t_scale)` once per optimizer step and invalidates
via `invalidate_fp8_cache()` after `optimizer.step()` (with an automatic `_version`
guard to prevent stale weights if mutated in-place).
"""
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = False,
scaling_mode: str = "rowwise",
use_fast_accum: bool = False,
enable_fp8: bool = True,
device=None,
dtype=None,
):
super().__init__()
if scaling_mode not in ("rowwise", "tensorwise"):
raise ValueError(f"scaling_mode must be 'rowwise' or 'tensorwise', got {scaling_mode!r}")
self.in_features = in_features
self.out_features = out_features
self.scaling_mode = scaling_mode
self.use_fast_accum = use_fast_accum
self.enable_fp8 = enable_fp8
factory_kwargs = {"device": device, "dtype": dtype}
self.weight = nn.Parameter(torch.empty((out_features, in_features), **factory_kwargs))
if bias:
self.bias = nn.Parameter(torch.empty((out_features,), **factory_kwargs))
else:
self.register_parameter("bias", None)
# Cached FP8 buffers (non-persistent; rebuilt lazily once per optimizer step)
self._w_fp8: Optional[torch.Tensor] = None
self._w_scale: Optional[torch.Tensor] = None
self._w_t_fp8: Optional[torch.Tensor] = None
self._w_t_scale: Optional[torch.Tensor] = None
self._cached_weight_version: int = -1
self._cache_hits: int = 0
self._cache_misses: int = 0
self.reset_parameters()
def reset_parameters(self) -> None:
nn.init.kaiming_uniform_(self.weight, a=5**0.5)
if self.bias is not None:
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
bound = 1.0 / (fan_in**0.5) if fan_in > 0 else 0.0
nn.init.uniform_(self.bias, -bound, bound)
self.invalidate_fp8_cache()
@classmethod
def from_linear(
cls,
linear: nn.Linear,
scaling_mode: str = "rowwise",
use_fast_accum: bool = False,
enable_fp8: bool = True,
) -> "CachedFP8Linear":
"""Wrap an existing `nn.Linear` sharing its exact `weight` and `bias` parameters."""
mod = cls.__new__(cls)
nn.Module.__init__(mod)
mod.in_features = linear.in_features
mod.out_features = linear.out_features
mod.scaling_mode = scaling_mode
mod.use_fast_accum = use_fast_accum
mod.enable_fp8 = enable_fp8
mod.weight = linear.weight
mod.bias = linear.bias
mod._w_fp8 = None
mod._w_scale = None
mod._w_t_fp8 = None
mod._w_t_scale = None
mod._cached_weight_version = -1
mod._cache_hits = 0
mod._cache_misses = 0
return mod
def invalidate_fp8_cache(self) -> None:
"""Invalidate cached FP8 weights. Call once after `optimizer.step()`."""
self._w_fp8 = None
self._w_scale = None
self._w_t_fp8 = None
self._w_t_scale = None
self._cached_weight_version = -1
def _get_cached_fp8_weights(
self,
) -> Tuple[
Optional[torch.Tensor],
Optional[torch.Tensor],
Optional[torch.Tensor],
Optional[torch.Tensor],
]:
if not self.enable_fp8 or not _can_use_fp8(self.weight):
return None, None, None, None
cur_ver = self.weight._version
if self._w_fp8 is not None and self._cached_weight_version == cur_ver:
self._cache_hits += 1
return self._w_fp8, self._w_scale, self._w_t_fp8, self._w_t_scale
with torch.no_grad():
w = self.weight.detach()
w_t = w.t().contiguous()
if self.scaling_mode == "rowwise":
w_fp8, w_scale = quantize_rowwise_fp8(w)
w_t_fp8, w_t_scale = quantize_rowwise_fp8(w_t)
else:
w_fp8, w_scale = quantize_tensorwise_fp8(w)
w_t_fp8, w_t_scale = quantize_tensorwise_fp8(w_t)
self._w_fp8 = w_fp8
self._w_scale = w_scale
self._w_t_fp8 = w_t_fp8
self._w_t_scale = w_t_scale
self._cached_weight_version = cur_ver
self._cache_misses += 1
return w_fp8, w_scale, w_t_fp8, w_t_scale
def forward(self, x: torch.Tensor) -> torch.Tensor:
w_fp8, w_scale, w_t_fp8, w_t_scale = self._get_cached_fp8_weights()
return _CachedFP8LinearFunction.apply(
x,
self.weight,
self.bias,
w_fp8,
w_scale,
w_t_fp8,
w_t_scale,
self.scaling_mode,
self.use_fast_accum,
)
def forward_from_rmsnorm(
self,
x: torch.Tensor,
gamma: Optional[torch.Tensor] = None,
eps: float = DEFAULT_EPS,
) -> torch.Tensor:
"""Fused `fused_rmsnorm_fp8_quant(x, gamma, eps)` -> `CachedFP8Linear`."""
w_fp8, w_scale, w_t_fp8, w_t_scale = self._get_cached_fp8_weights()
return _FusedRMSNormCachedFP8LinearFn.apply(
x,
gamma,
eps,
self.weight,
self.bias,
w_fp8,
w_scale,
w_t_fp8,
w_t_scale,
self.scaling_mode,
)
def forward_from_swiglu(self, gate_up: torch.Tensor) -> torch.Tensor:
"""Fused `fused_silu_mul_fp8_quant(gate_up)` -> `CachedFP8Linear` (`w_down`)."""
w_fp8, w_scale, w_t_fp8, w_t_scale = self._get_cached_fp8_weights()
return _FusedSiLUMulCachedFP8DownFn.apply(
gate_up,
self.weight,
self.bias,
w_fp8,
w_scale,
w_t_fp8,
w_t_scale,
self.scaling_mode,
)
def extra_repr(self) -> str:
return (
f"in_features={self.in_features}, out_features={self.out_features}, "
f"bias={self.bias is not None}, scaling_mode={self.scaling_mode!r}, "
f"enable_fp8={self.enable_fp8}"
)
def invalidate_all_fp8_caches(model: nn.Module) -> int:
"""Invalidate FP8 weight caches on all `CachedFP8Linear` modules in `model`.
Call once immediately after `optimizer.step()`.
Returns the number of modules invalidated.
"""
count = 0
for mod in model.modules():
if isinstance(mod, CachedFP8Linear):
mod.invalidate_fp8_cache()
count += 1
return count
def wrap_shared_core_with_cached_fp8(
model: nn.Module,
target_names: Optional[Iterable[str]] = None,
scaling_mode: str = "rowwise",
use_fast_accum: bool = False,
) -> int:
"""Replace targeted `nn.Linear` modules (e.g. `NVFP4_SHARED_CORE_TARGETS`) with `CachedFP8Linear`.
Returns the number of wrapped layers.
"""
target_set = set(target_names) if target_names is not None else None
replaced = 0
for full_name, mod in list(model.named_modules()):
if not isinstance(mod, nn.Linear):
continue
if target_set is not None and full_name not in target_set:
continue
parts = full_name.split(".")
parent = model
for p in parts[:-1]:
parent = getattr(parent, p)
setattr(
parent,
parts[-1],
CachedFP8Linear.from_linear(
mod,
scaling_mode=scaling_mode,
use_fast_accum=use_fast_accum,
),
)
replaced += 1
return replaced
__all__ = [
"D_STREAM",
"FFN_HIDDEN",
"D_TOTAL",
"DEFAULT_EPS",
"FP8_E4M3_MAX",
"FP8_SCALE_EPS",
"quantize_rowwise_fp8",
"quantize_tensorwise_fp8",
"fused_silu_mul_fp8_quant",
"fused_silu_mul_bwd",
"fused_rmsnorm_fp8_quant",
"fused_rmsnorm_bwd",
"CachedFP8Linear",
"invalidate_all_fp8_caches",
"wrap_shared_core_with_cached_fp8",
]
# Register fused_mola_online_merge as torch.library.custom_op for 0-graph-break torch.compile
def _mola_online_merge_fwd_dispatch(o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta):
B, H, T, D = q_normed.shape
M = k_mem_n.shape[1]
dt = o_tok.dtype
if o_tok.stride(-1) != 1:
o_tok = o_tok.contiguous()
if q_normed.dtype != dt or q_normed.stride(-1) != 1:
q_normed = q_normed.to(dt).contiguous()
if k_mem_n.dtype != dt or not k_mem_n.is_contiguous():
k_mem_n = k_mem_n.to(dt).contiguous()
if v_mem.dtype != dt or not v_mem.is_contiguous():
v_mem = v_mem.to(dt).contiguous()
lse_tok_f32 = lse_tok.detach().float()
if lse_tok_f32.stride(-1) != 1:
lse_tok_f32 = lse_tok_f32.contiguous()
beta_f32 = beta.float().contiguous()
out = torch.empty((B, H, T, D), device=o_tok.device, dtype=dt)
lse_mem = torch.empty((B, H, T), device=o_tok.device, dtype=torch.float32)
BLOCK_T = 64
scale = 1.0 / math.sqrt(D)
input_precision = "ieee" if dt == torch.float32 else "tf32"
grid = (triton.cdiv(T, BLOCK_T), B * H)
_triton_mola_online_merge_fwd[grid](
o_tok, lse_tok_f32, q_normed, k_mem_n, v_mem, beta_f32,
out, lse_mem,
o_tok.stride(0), o_tok.stride(1), o_tok.stride(2), o_tok.stride(3),
lse_tok_f32.stride(0), lse_tok_f32.stride(1), lse_tok_f32.stride(2),
q_normed.stride(0), q_normed.stride(1), q_normed.stride(2), q_normed.stride(3),
k_mem_n.stride(0), k_mem_n.stride(1), k_mem_n.stride(2),
v_mem.stride(0), v_mem.stride(1), v_mem.stride(2),
out.stride(0), out.stride(1), out.stride(2), out.stride(3),
lse_mem.stride(0), lse_mem.stride(1), lse_mem.stride(2),
H, T,
SCALE=scale, BLOCK_T=BLOCK_T, HEAD_DIM=D, M_MOLA=M,
INPUT_PRECISION=input_precision, num_warps=4, num_stages=2,
)
return out, lse_mem
def _mola_online_merge_bwd_dispatch(d_out, out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta):
B, H, T, D = q_normed.shape
M = k_mem_n.shape[1]
dt = out.dtype
ot_dt, q_dt, km_dt, vm_dt, beta_dt = out.dtype, q_normed.dtype, k_mem_n.dtype, v_mem.dtype, beta.dtype
if d_out.dtype != dt or d_out.stride(-1) != 1:
d_out = d_out.to(dt).contiguous()
if q_normed.dtype != dt or q_normed.stride(-1) != 1:
q_normed = q_normed.to(dt).contiguous()
if k_mem_n.dtype != dt or not k_mem_n.is_contiguous():
k_mem_n = k_mem_n.to(dt).contiguous()
if v_mem.dtype != dt or not v_mem.is_contiguous():
v_mem = v_mem.to(dt).contiguous()
lse_tok_f32 = lse_tok.detach().float()
if lse_tok_f32.stride(-1) != 1:
lse_tok_f32 = lse_tok_f32.contiguous()
beta_f32 = beta.float().contiguous()
d_o_tok = torch.empty((B, H, T, D), device=d_out.device, dtype=dt)
d_q_normed = torch.empty((B, H, T, D), device=d_out.device, dtype=dt)
d_k_mem_n = torch.zeros((H, M, D), device=d_out.device, dtype=torch.float32)
d_v_mem = torch.zeros((H, M, D), device=d_out.device, dtype=torch.float32)
d_beta = torch.zeros((H,), device=d_out.device, dtype=torch.float32)
BLOCK_T = 64
scale = 1.0 / math.sqrt(D)
input_precision = "ieee" if dt == torch.float32 else "tf32"
grid = (triton.cdiv(T, BLOCK_T), B * H)
_triton_mola_online_merge_bwd[grid](
d_out, out, lse_tok_f32, lse_mem, q_normed, k_mem_n, v_mem, beta_f32,
d_o_tok, d_q_normed, d_k_mem_n, d_v_mem, d_beta,
d_out.stride(0), d_out.stride(1), d_out.stride(2), d_out.stride(3),
out.stride(0), out.stride(1), out.stride(2), out.stride(3),
lse_tok_f32.stride(0), lse_tok_f32.stride(1), lse_tok_f32.stride(2),
lse_mem.stride(0), lse_mem.stride(1), lse_mem.stride(2),
q_normed.stride(0), q_normed.stride(1), q_normed.stride(2), q_normed.stride(3),
k_mem_n.stride(0), k_mem_n.stride(1), k_mem_n.stride(2),
v_mem.stride(0), v_mem.stride(1), v_mem.stride(2),
d_o_tok.stride(0), d_o_tok.stride(1), d_o_tok.stride(2), d_o_tok.stride(3),
d_q_normed.stride(0), d_q_normed.stride(1), d_q_normed.stride(2), d_q_normed.stride(3),
d_k_mem_n.stride(0), d_k_mem_n.stride(1), d_k_mem_n.stride(2),
d_v_mem.stride(0), d_v_mem.stride(1), d_v_mem.stride(2),
H, T,
SCALE=scale, BLOCK_T=BLOCK_T, HEAD_DIM=D, M_MOLA=M,
INPUT_PRECISION=input_precision, num_warps=4, num_stages=2,
)
return d_o_tok.to(ot_dt), d_q_normed.to(q_dt), d_k_mem_n.to(km_dt), d_v_mem.to(vm_dt), d_beta.to(beta_dt)
_HAS_MOLA_CUSTOM_OP = False
if hasattr(torch, "library") and hasattr(torch.library, "custom_op"):
try:
@torch.library.custom_op("l2gddr7::mola_online_merge_fwd", mutates_args=())
def _mola_op_fwd(
o_tok: torch.Tensor,
lse_tok: torch.Tensor,
q_normed: torch.Tensor,
k_mem_n: torch.Tensor,
v_mem: torch.Tensor,
beta: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
return _mola_online_merge_fwd_dispatch(o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta)
@_mola_op_fwd.register_fake
def _mola_op_fwd_fake(o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta):
B, H, T, D = o_tok.shape
return (
o_tok.new_empty((B, H, T, D)),
torch.empty((B, H, T), device=o_tok.device, dtype=torch.float32),
)
@torch.library.custom_op("l2gddr7::mola_online_merge_bwd", mutates_args=())
def _mola_op_bwd(
d_out: torch.Tensor,
out: torch.Tensor,
lse_tok: torch.Tensor,
lse_mem: torch.Tensor,
q_normed: torch.Tensor,
k_mem_n: torch.Tensor,
v_mem: torch.Tensor,
beta: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
return _mola_online_merge_bwd_dispatch(
d_out, out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta
)
@_mola_op_bwd.register_fake
def _mola_op_bwd_fake(d_out, out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta):
return (
out.new_empty(out.shape),
q_normed.new_empty(q_normed.shape),
k_mem_n.new_empty(k_mem_n.shape),
v_mem.new_empty(v_mem.shape),
beta.new_empty(beta.shape),
)
def _mola_setup_ctx(ctx, inputs, output):
o_tok, lse_tok, q_normed, k_mem_n, v_mem, beta = inputs
out, lse_mem = output
ctx.save_for_backward(out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta)
def _mola_backward(ctx, d_out, _d_lse_mem):
out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta = ctx.saved_tensors
d_o_tok, d_q, d_km, d_vm, d_beta = _mola_op_bwd(
d_out, out, lse_tok, lse_mem, q_normed, k_mem_n, v_mem, beta
)
return d_o_tok, None, d_q, d_km, d_vm, d_beta
_mola_op_fwd.register_autograd(_mola_backward, setup_context=_mola_setup_ctx)
_HAS_MOLA_CUSTOM_OP = True
except Exception:
_HAS_MOLA_CUSTOM_OP = False
class GDDR7SparseTable:
"""Direct-on-CUDA FP8 E4M3 (per-row FP32 w_scale + Philox SR) or BF16 sparse table
+ INT8 m + Row-Wise FP32 v_row (~2.05 B/param in FP8, ~3.0 B/param in BF16)."""
_compiled_rowv_fn = None
def __init__(self, name, n_rows, dim, device, init_std=0.02):
self.name = name
self.n_rows = n_rows
self.dim = dim
self.device = device
fp8_dt = getattr(torch, "float8_e4m3fn", None)
self.use_fp8 = bool(SPARSE_TABLE_USE_FP8 and fp8_dt is not None and device.type == "cuda")
self._fp8_dtype = fp8_dt
if self.use_fp8:
self.weight = torch.empty((n_rows, dim), device=device, dtype=fp8_dt)
self.w_scale = torch.empty((n_rows,), device=device, dtype=torch.float32)
chunk = 524_288
for r0 in range(0, n_rows, chunk):
r1 = min(n_rows, r0 + chunk)
tmp = torch.empty((r1 - r0, dim), device=device, dtype=torch.float32).normal_(0.0, init_std)
sc = (tmp.abs().amax(dim=-1) / FP8_E4M3_MAX).clamp_min(1e-12)
self.weight[r0:r1].copy_((tmp / sc.unsqueeze(-1)).clamp(-FP8_E4M3_MAX, FP8_E4M3_MAX).to(fp8_dt))
self.w_scale[r0:r1].copy_(sc)
else:
self.weight = torch.empty((n_rows, dim), device=device, dtype=torch.bfloat16)
self.w_scale = torch.ones((n_rows,), device=device, dtype=torch.float32)
chunk = 1_048_576
for r0 in range(0, n_rows, chunk):
r1 = min(n_rows, r0 + chunk)
self.weight[r0:r1].normal_(0.0, init_std)
self.q_m = torch.zeros((n_rows, dim), device=device, dtype=torch.int8)
self.m_scale = torch.zeros((n_rows,), device=device, dtype=torch.float32)
self.v_row = torch.zeros((n_rows,), device=device, dtype=torch.float32)
self.step_count = torch.zeros((n_rows,), device=device, dtype=torch.int32)
self.grad_buffer = []
self.visited_mask = torch.zeros((n_rows,), device=device, dtype=torch.bool)
self.last_unique_count = 0
self.last_grad_norm = 0.0
self.last_dead_slot_frac = 0.0
self._pending_grad_norm_t = None
self._pending_dead_slot_t = None
use_comp = USE_TORCH_COMPILE and device.type == "cuda" and hasattr(torch, "compile")
if GDDR7SparseTable._compiled_rowv_fn is None:
GDDR7SparseTable._compiled_rowv_fn = (
torch.compile(_sparse_adam_math_rowwise_v, mode="default", dynamic=True)
if use_comp
else _sparse_adam_math_rowwise_v
)
self._update_fn = GDDR7SparseTable._compiled_rowv_fn
def memory_bytes(self):
w_b = 1 if self.use_fp8 else 2
return (
self.weight.numel() * w_b
+ self.q_m.numel() * 1
+ (self.w_scale.numel() * 4 if self.use_fp8 else 0)
+ self.m_scale.numel() * 4
+ self.v_row.numel() * 4
+ self.step_count.numel() * 4
)
def lookup(self, indices):
orig_shape = indices.shape
flat_idx = indices.reshape(-1)
if not torch.is_grad_enabled():
return _sparse_plain_lookup_impl(
self.weight, self.w_scale, flat_idx, self.use_fp8
).view(*orig_shape, self.dim)
grad_hook = torch.empty(0, device=self.weight.device, requires_grad=True)
out = CoalescedSparseGatherFunction.apply(
self.weight, self.w_scale, flat_idx, self.grad_buffer, grad_hook, self.use_fp8
)
return out.view(*orig_shape, self.dim)
def finalize_telemetry(self):
"""Read deferred 0-D GPU telemetry tensors to Python floats after stream sync."""
if self._pending_grad_norm_t is not None:
self.last_grad_norm = float(self._pending_grad_norm_t.item())
self._pending_grad_norm_t = None
if self._pending_dead_slot_t is not None:
self.last_dead_slot_frac = float(self._pending_dead_slot_t.item())
self._pending_dead_slot_t = None
@torch.no_grad()
def sparse_adam_step(
self, lr, betas=(0.9, 0.98), eps=1e-6, collect_telemetry=False, defer_telemetry=False
):
if not self.grad_buffer:
if collect_telemetry:
self.last_unique_count = 0
self.last_grad_norm = 0.0
self.last_dead_slot_frac = 0.0
self._pending_grad_norm_t = None
self._pending_dead_slot_t = None
return
u_idx, g_sum = coalesce_compact_sparse_grads(
self.grad_buffer, self.dim, device=self.device
)
self.grad_buffer.clear()
self.visited_mask[u_idx] = True
grad_norm_t = g_sum.norm()
max_sparse_norm = MAX_GRAD_NORM * 10.0
g_sum.mul_((max_sparse_norm / (grad_norm_t + 1e-6)).clamp(max=1.0))
b1, b2 = betas
n_unique = u_idx.numel()
if _HAS_TRITON and self.device.type == "cuda" and (self.dim & (self.dim - 1)) == 0:
self._triton_seed = getattr(self, "_triton_seed", 0) + 1
_triton_sparse_adam_rowv_kernel[(n_unique,)](
self.weight, self.w_scale, self.q_m, self.m_scale, self.v_row, self.step_count,
u_idx, g_sum.contiguous(),
float(lr), float(b1), float(b2), math.log(b1), math.log(b2), float(eps), int(self._triton_seed),
n_unique,
D=self.dim,
STORE_FP8=self.use_fp8,
num_warps=4 if self.dim <= 128 else 8,
)
else:
self.step_count.index_add_(0, u_idx, torch.ones_like(u_idx, dtype=torch.int32))
lr_t = torch.tensor(lr, device=self.device, dtype=torch.float32)
for c0 in range(0, n_unique, SPARSE_OPT_CHUNK):
c1 = min(n_unique, c0 + SPARSE_OPT_CHUNK)
idx_c = u_idx[c0:c1]
g_c = g_sum[c0:c1]
m_prev = (
self.q_m.index_select(0, idx_c).float()
* self.m_scale.index_select(0, idx_c).unsqueeze(-1)
)
v_row_prev = self.v_row.index_select(0, idx_c)
row_counts = self.step_count.index_select(0, idx_c).float().unsqueeze(-1)
w_active = self.weight.index_select(0, idx_c).float()
if self.use_fp8:
w_active = w_active * self.w_scale.index_select(0, idx_c).unsqueeze(-1)
w_bf16, qm_new, m_sc, v_row_new = self._update_fn(
w_active, g_c, m_prev, v_row_prev, row_counts, lr_t, b1, b2, eps
)
if self.use_fp8:
w_f = w_bf16.float()
w_sc = (w_f.abs().amax(dim=-1) / FP8_E4M3_MAX).clamp_min(1e-12)
self.weight.index_copy_(
0, idx_c, (w_f / w_sc.unsqueeze(-1)).clamp(-FP8_E4M3_MAX, FP8_E4M3_MAX).to(self._fp8_dtype)
)
self.w_scale.index_copy_(0, idx_c, w_sc)
else:
self.weight.index_copy_(0, idx_c, w_bf16)
self.q_m.index_copy_(0, idx_c, qm_new)
self.m_scale.index_copy_(0, idx_c, m_sc)
self.v_row.index_copy_(0, idx_c, v_row_new)
if collect_telemetry:
self.last_unique_count = int(n_unique)
dead_t = (self.w_scale[u_idx] < 1e-4).float().mean() if self.use_fp8 else None
if defer_telemetry:
self._pending_grad_norm_t = grad_norm_t
self._pending_dead_slot_t = dead_t
else:
self.last_grad_norm = float(grad_norm_t.item())
self.last_dead_slot_frac = float(dead_t.item()) if dead_t is not None else 0.0
# ============================ TIER 1 GDDR7: LAYER-2 DEEPSEEK ENGRAM (ASYNC)
class EngramConditionalMemory(nn.Module):
"""DeepSeek Engram (arXiv:2601.07372) placed strictly after Prelude Loop 2,
with async CUDA stream prefetch to hide GDDR7 lookup latency behind Prelude.
"""
def __init__(self, canonical_map, cfg, device, rank=0, world_size=1):
super().__init__()
self.register_buffer("canonical_map", canonical_map, persistent=False)
self.rank = int(rank)
self.world_size = int(world_size)
self.n_heads = cfg["engram_heads"]
assert self.n_heads % self.world_size == 0, (
f"engram_heads ({self.n_heads}) must be divisible by world_size ({self.world_size})"
)
self.local_heads = self.n_heads // self.world_size
self.head_start = self.rank * self.local_heads
self.head_end = self.head_start + self.local_heads
self.rows_per_head = cfg["engram_rows_per_head"]
self.head_dim = cfg["engram_dim"]
self.local_row_offset = self.head_start * self.rows_per_head
total_rows = self.local_heads * self.rows_per_head
primes = torch.tensor(
[
[1000003, 1000033, 1],
[1000037, 1000039, 1],
[1000081, 1000099, 1],
[1000117, 1000121, 1],
[1000133, 1000151, 1000159],
[1000171, 1000183, 1000187],
[1000193, 1000199, 1000211],
[1000213, 1000231, 1000249],
],
device=device,
dtype=torch.long,
)[: self.n_heads]
self.register_buffer("primes", primes, persistent=False)
trigram_mask = (
torch.arange(self.n_heads, device=device, dtype=torch.long)
>= (self.n_heads // 2)
).to(torch.long)
self.register_buffer("trigram_mask", trigram_mask, persistent=False)
head_offsets = (
torch.arange(self.n_heads, device=device, dtype=torch.long)
* self.rows_per_head
)
self.register_buffer("head_offsets", head_offsets, persistent=False)
self.sparse_table = GDDR7SparseTable(
"Engram_Ngram_Table",
total_rows,
self.head_dim,
device=device,
init_std=1.0 / math.sqrt(D_STREAM),
)
self.norm_q = nn.Parameter(torch.ones(D_STREAM))
self.norm_k = nn.Parameter(torch.ones(D_STREAM))
self.norm_v = nn.Parameter(torch.ones(D_STREAM))
self.w_eng = nn.Linear(D_STREAM, D_STREAM, bias=False)
nn.init.zeros_(self.w_eng.weight)
self._gate_and_project_compiled = None
self.collect_telemetry = False
self.last_gate_mean = 0.0
self.last_gate_std = 0.0
def compute_ngram_indices(self, token_ids):
c0 = self.canonical_map[token_ids.clamp(0, self.canonical_map.numel() - 1)]
c_prev1 = F.pad(c0[:, :-1], (1, 0), value=0)
c_prev2 = F.pad(c0[:, :-2], (2, 0), value=0)
p0 = self.primes[:, 0].view(1, 1, -1)
p1 = self.primes[:, 1].view(1, 1, -1)
p2 = self.primes[:, 2].view(1, 1, -1)
tri = self.trigram_mask.view(1, 1, -1)
raw = (c0.unsqueeze(-1) * p0) ^ (c_prev1.unsqueeze(-1) * p1)
raw = raw ^ ((c_prev2.unsqueeze(-1) * p2) * tri)
return (raw.abs() % self.rows_per_head) + self.head_offsets.view(1, 1, -1)
def prefetch_embeddings(self, token_ids):
"""Launchable on a separate CUDA stream before Prelude Loop 1.
When world_size > 1, shards Engram's 8 heads evenly across ranks via differentiable all_to_all.
"""
indices = self.compute_ngram_indices(token_ids)
if self.world_size == 1 or not dist_is_active():
retrieved = self.sparse_table.lookup(indices)
return retrieved.reshape(token_ids.size(0), token_ids.size(1), D_STREAM)
B, T = token_ids.shape
all_idx = torch.empty((self.world_size, B, T, self.n_heads), device=indices.device, dtype=indices.dtype)
dist.all_gather_into_tensor(all_idx, indices.contiguous())
local_idx = all_idx[..., self.head_start : self.head_end] - self.local_row_offset
local_emb = self.sparse_table.lookup(local_idx) # [W, B, T, local_heads, head_dim]
gathered_emb = _DistAllToAllFn.apply(local_emb) # [W, B, T, local_heads, head_dim] -> rank r's batch across all W head shards
return gathered_emb.permute(1, 2, 0, 3, 4).reshape(B, T, D_STREAM)
def _gate_and_project(self, x1_ctx, e_t):
dt = self.w_eng.weight.dtype
q_normed = rms_norm(x1_ctx, self.norm_q)
k_normed = rms_norm(e_t, self.norm_k)
gate_logits = (q_normed.float() * k_normed.float()).sum(
dim=-1, keepdim=True
) / math.sqrt(D_STREAM)
gate = torch.sigmoid(gate_logits).to(dt)
gated_val = gate * rms_norm(e_t, self.norm_v, out_dtype=dt)
if self.training and ENGRAM_DROPOUT > 0.0:
gated_val = F.dropout(gated_val, p=ENGRAM_DROPOUT, training=True)
return x1_ctx + self.w_eng(gated_val).to(x1_ctx.dtype), gate
def apply_prefetched(self, x1_ctx, e_t):
fn = (
self._gate_and_project_compiled
if (self.training and self._gate_and_project_compiled is not None)
else self._gate_and_project
)
out, gate = fn(x1_ctx, e_t)
if self.collect_telemetry:
with torch.no_grad():
self.last_gate_mean = float(gate.mean().item())
self.last_gate_std = float(gate.std().item())
return out
def forward(self, x1_ctx, token_ids):
e_t = self.prefetch_embeddings(token_ids)
return self.apply_prefetched(x1_ctx, e_t)
# =================== TIER 2 GDDR7: TOKEN-SPARSE MULTI-HOP ULTRAMEMV2 TDQKR
class UltraMemV2TDQKRBridge(nn.Module):
"""Shared UltraMemV2 (arXiv:2508.18756) + Memory+ router/table supporting
flat token-sparse multi-hop lookups `[N_sel, D_STREAM]` from the Shared Core FFN.
"""
def __init__(self, cfg, device, rank=0, world_size=1):
super().__init__()
self.rank = int(rank)
self.world_size = int(world_size)
self.n_heads = cfg["ultramem_heads"]
self.grid_k = cfg["ultramem_k"]
self.slots_per_head = self.grid_k * self.grid_k
self.total_slots = self.n_heads * self.slots_per_head
shard_size = (self.total_slots + self.world_size - 1) // self.world_size
self.shard_start = self.rank * shard_size
self.shard_end = min(self.total_slots, self.shard_start + shard_size)
self.local_slots = max(1, self.shard_end - self.shard_start)
self.dv = cfg["ultramem_dv"]
self.rank = cfg["ultramem_tucker_rank"]
self.cand_k0 = cfg["ultramem_cand_k0"]
self.topk = cfg["ultramem_topk"]
self.dk = HEAD_DIM
q_out_dim = self.n_heads * self.rank * self.dk
self.w_q_row = nn.Linear(D_STREAM, q_out_dim, bias=False)
self.w_q_col = nn.Linear(D_STREAM, q_out_dim, bias=False)
self.k_row = nn.Parameter(
torch.randn(self.n_heads, self.grid_k, self.dk) * (self.dk ** -0.5)
)
self.k_col = nn.Parameter(
torch.randn(self.n_heads, self.grid_k, self.dk) * (self.dk ** -0.5)
)
eye_r = torch.eye(self.rank).unsqueeze(0).repeat(self.n_heads, 1, 1)
self.tucker_core = nn.Parameter(eye_r + 0.05 * torch.randn_like(eye_r))
self.log_temp = nn.Parameter(torch.zeros(self.n_heads))
self.sparse_table = GDDR7SparseTable(
"UltraMemV2_TDQKR_Table",
self.local_slots,
self.dv,
device=device,
init_std=1.0 / math.sqrt(self.dv),
)
head_offsets = (
torch.arange(self.n_heads, device=device, dtype=torch.long)
* self.slots_per_head
)
self.register_buffer("head_offsets", head_offsets, persistent=False)
key_head_offsets = (
torch.arange(self.n_heads, device=device, dtype=torch.long)
* self.grid_k
)
self.register_buffer("key_head_offsets", key_head_offsets, persistent=False)
self.pre_norm = nn.Parameter(torch.ones(D_STREAM))
self.post_norm = nn.Parameter(torch.ones(D_STREAM))
self.w_gate = nn.Linear(D_STREAM, self.dv, bias=False)
self.w_ive = nn.Linear(self.dv, D_STREAM, bias=False)
nn.init.zeros_(self.w_ive.weight) # zero Step-1 noise (matches Engram.w_eng!)
# Floored positive scale in [0.08, 0.50] (starts ~0.15, zero WD, cannot collapse to 0.009!)
self.bridge_scale_logit = nn.Parameter(torch.tensor(-1.60, dtype=torch.float32))
# DeepSeek-V3 Auxiliary-Loss-Free Top-k0 Bias + EMA Query Mean-Centering
self.register_buffer("b_row", torch.zeros(self.n_heads, self.grid_k, device=device, dtype=torch.float32))
self.register_buffer("b_col", torch.zeros(self.n_heads, self.grid_k, device=device, dtype=torch.float32))
self.register_buffer("ema_qr_mean", torch.zeros(self.n_heads, self.dk, device=device, dtype=torch.float32))
self.register_buffer("ema_qc_mean", torch.zeros(self.n_heads, self.dk, device=device, dtype=torch.float32))
self.register_buffer("step_c_row", torch.zeros(self.n_heads, self.grid_k, device=device, dtype=torch.float32), persistent=False)
self.register_buffer("step_c_col", torch.zeros(self.n_heads, self.grid_k, device=device, dtype=torch.float32), persistent=False)
self.register_buffer("step_q_sum_r", torch.zeros(self.n_heads, self.dk, device=device, dtype=torch.float32), persistent=False)
self.register_buffer("step_q_sum_c", torch.zeros(self.n_heads, self.dk, device=device, dtype=torch.float32), persistent=False)
self.step_tok_count = 0
self._route_flat_compiled = None
self._proj_flat_compiled = None
self.collect_telemetry = False
self.last_entropy_norm = 0.0
self.last_max_load_ratio = 1.0
self.last_bridge_rms_ratio = 0.0
@property
def bridge_scale(self):
return 0.08 + 0.42 * torch.sigmoid(self.bridge_scale_logit)
def _route_and_score_flat(self, x_flat):
"""Auxiliary-loss-free TDQKR routing with EMA query centering & re-normed mean-rank."""
N, _ = x_flat.shape
H, R, K, Dk = self.n_heads, self.rank, self.grid_k, self.dk
dt = self.w_gate.weight.dtype
h = rms_norm(x_flat, self.pre_norm, out_dtype=dt)
qr_raw = self.w_q_row(h.to(self.w_q_row.weight.dtype)).view(N, H, R, Dk)
qc_raw = self.w_q_col(h.to(self.w_q_col.weight.dtype)).view(N, H, R, Dk)
qr = l2_norm(qr_raw).to(dt)
qc = l2_norm(qc_raw).to(dt)
kr = l2_norm(self.k_row - self.k_row.mean(dim=1, keepdim=True)).to(dt) # centered keys defeat cone collapse
kc = l2_norm(self.k_col - self.k_col.mean(dim=1, keepdim=True)).to(dt)
# Re-normalized, EMA-centered mean-rank query defeats MoD top-12.5% cone collapse!
qr_mean_raw = qr.mean(dim=-2).transpose(0, 1).float() # [H, N, Dk]
qc_mean_raw = qc.mean(dim=-2).transpose(0, 1).float()
qr_m = l2_norm(qr_mean_raw - self.ema_qr_mean.unsqueeze(1)).to(dt)
qc_m = l2_norm(qc_mean_raw - self.ema_qc_mean.unsqueeze(1)).to(dt)
s_row_mean = torch.bmm(qr_m, kr.transpose(-1, -2)).transpose(0, 1) # [N, H, K]
s_col_mean = torch.bmm(qc_m, kc.transpose(-1, -2)).transpose(0, 1)
k0 = min(self.cand_k0, K)
# Biased candidate selection (loss-free load balance), unbiased Tucker scoring!
_, idx_r = torch.topk(s_row_mean.float() + self.b_row.unsqueeze(0), k=k0, dim=-1)
_, idx_c = torch.topk(s_col_mean.float() + self.b_col.unsqueeze(0), k=k0, dim=-1)
h_key_off = self.key_head_offsets.view(1, H, 1)
kr_sub = F.embedding(
(idx_r + h_key_off).reshape(-1), kr.reshape(H * K, Dk)
).view(N, H, k0, Dk)
kc_sub = F.embedding(
(idx_c + h_key_off).reshape(-1), kc.reshape(H * K, Dk)
).view(N, H, k0, Dk)
sr_sub = torch.matmul(qr, kr_sub.transpose(-1, -2)).float() # [N, H, R, k0]
sc_sub = torch.matmul(qc, kc_sub.transpose(-1, -2)).float()
return h, sr_sub, sc_sub, idx_r, idx_c, qr_mean_raw, qc_mean_raw
def _gate_and_project_flat(self, h, v_agg):
gated_v = v_agg * F.silu(self.w_gate(h))
return rms_norm(self.w_ive(gated_v), self.post_norm)
def forward_flat(self, x_flat):
route_fn = (
self._route_flat_compiled
if (self.training and self._route_flat_compiled is not None)
else self._route_and_score_flat
)
h, sr_sub, sc_sub, idx_r, idx_c, qr_mean_raw, qc_mean_raw = route_fn(x_flat)
# Custom Triton Kernel 2: in-register 32x32 Tucker scoring + top-16 + softmax (zero 33.5 MiB grid!)
inv_temp = (1.0 / torch.exp(self.log_temp).clamp(0.05, 10.0)).view(1, self.n_heads, 1).float()
_, sub_r, sub_c, weights_f32 = fused_tdqkr_tucker_topk(
sr_sub, sc_sub, self.tucker_core.float(), inv_temp, topk=self.topk
)
real_r = torch.gather(idx_r, dim=-1, index=sub_r)
real_c = torch.gather(idx_c, dim=-1, index=sub_c)
global_slots = real_r * self.grid_k + real_c + self.head_offsets.view(1, self.n_heads, 1)
weights = weights_f32.to(h.dtype)
# Accumulate top-k0 counts only on grad-enabled loops (skip no_grad TBPTT iters!)
if self.training and torch.is_grad_enabled():
with torch.no_grad():
H = self.n_heads
ir = idx_r.permute(1, 0, 2).reshape(H, -1)
ic = idx_c.permute(1, 0, 2).reshape(H, -1)
ones = torch.ones_like(ir, dtype=torch.float32)
self.step_c_row.scatter_add_(1, ir, ones)
self.step_c_col.scatter_add_(1, ic, ones)
self.step_q_sum_r.add_(qr_mean_raw.sum(dim=1))
self.step_q_sum_c.add_(qc_mean_raw.sum(dim=1))
self.step_tok_count += x_flat.size(0)
# Custom Triton Kernel 1: 1-pass int64-safe gather + weighted sum (1-GPU local or W-GPU row-sharded exact!)
if self.world_size == 1 or not dist_is_active():
v_agg = fused_ultramem_gather_reduce(
self.sparse_table.weight,
global_slots,
weights,
self.sparse_table.grad_buffer if torch.is_grad_enabled() else None,
w_scale=(self.sparse_table.w_scale if self.sparse_table.use_fp8 else None),
)
else:
N_loc = global_slots.size(0)
all_slots = torch.empty(
(self.world_size, *global_slots.shape),
device=global_slots.device,
dtype=global_slots.dtype,
)
dist.all_gather_into_tensor(all_slots, global_slots.contiguous())
all_weights = _DistAllGatherFn.apply(weights)
in_shard = (all_slots >= self.shard_start) & (all_slots < self.shard_end)
local_slots = (all_slots - self.shard_start).clamp(0, self.local_slots - 1)
local_weights = all_weights * in_shard.to(all_weights.dtype)
v_partial_flat = fused_ultramem_gather_reduce(
self.sparse_table.weight,
local_slots.reshape(self.world_size * N_loc, self.n_heads, self.topk),
local_weights.reshape(self.world_size * N_loc, self.n_heads, self.topk),
self.sparse_table.grad_buffer if torch.is_grad_enabled() else None,
w_scale=(self.sparse_table.w_scale if self.sparse_table.use_fp8 else None),
)
v_agg = _DistReduceScatterSumFn.apply(v_partial_flat.view(self.world_size, N_loc, self.dv))
proj_fn = (
self._proj_flat_compiled
if (self.training and self._proj_flat_compiled is not None)
else self._gate_and_project_flat
)
return proj_fn(h, v_agg), None
@torch.no_grad()
def update_routing_bias_and_ema(self, gamma=ULTRAMEM_BIAS_GAMMA, collect_telemetry=False):
"""Step-end DeepSeek-V3 loss-free top-k0 bias + EMA query centering update."""
if self.step_tok_count == 0:
return
tok_count_eff = float(self.step_tok_count)
if self.world_size > 1 and dist_is_active():
dist.all_reduce(self.step_c_row, op=dist.ReduceOp.SUM)
dist.all_reduce(self.step_c_col, op=dist.ReduceOp.SUM)
dist.all_reduce(self.step_q_sum_r, op=dist.ReduceOp.SUM)
dist.all_reduce(self.step_q_sum_c, op=dist.ReduceOp.SUM)
tok_count_eff *= float(self.world_size)
if gamma > 0.0:
avg_r = self.step_c_row.mean(dim=-1, keepdim=True)
avg_c = self.step_c_col.mean(dim=-1, keepdim=True)
# Asymmetric overload pushback (-5x max on hot keys, gentle +1x on cold keys, [-1.5, 1.5] range)
ratio_r = self.step_c_row / (avg_r + 1e-6)
ratio_c = self.step_c_col / (avg_c + 1e-6)
delta_r = torch.where(ratio_r > 1.0, -(ratio_r - 1.0).clamp(max=5.0), 1.0 - ratio_r)
delta_c = torch.where(ratio_c > 1.0, -(ratio_c - 1.0).clamp(max=5.0), 1.0 - ratio_c)
self.b_row.add_(gamma * delta_r)
self.b_col.add_(gamma * delta_c)
self.b_row.sub_(self.b_row.mean(dim=-1, keepdim=True))
self.b_col.sub_(self.b_col.mean(dim=-1, keepdim=True))
self.b_row.clamp_(-1.5, 1.5)
self.b_col.clamp_(-1.5, 1.5)
if gamma > 0.0:
q_mean_r = self.step_q_sum_r / tok_count_eff
q_mean_c = self.step_q_sum_c / tok_count_eff
self.ema_qr_mean.lerp_(q_mean_r, 0.05)
self.ema_qc_mean.lerp_(q_mean_c, 0.05)
if collect_telemetry:
p_r = self.step_c_row / self.step_c_row.sum(dim=-1, keepdim=True).clamp_min(1.0)
p_c = self.step_c_col / self.step_c_col.sum(dim=-1, keepdim=True).clamp_min(1.0)
p_avg = 0.5 * (p_r + p_c).clamp_min(1e-12)
ent = -(p_avg * p_avg.log()).sum(dim=-1).mean().item()
self.last_entropy_norm = float(ent / math.log(self.grid_k))
self.last_max_load_ratio = float(
max(p_r.max().item(), p_c.max().item()) * self.grid_k
)
self.step_c_row.zero_()
self.step_c_col.zero_()
self.step_q_sum_r.zero_()
self.step_q_sum_c.zero_()
self.step_tok_count = 0
# =========================== ON-CHIP L2 BLOCK: GDN-2 + SWA FLEX + MOLA + FFN
class CausalConv1dSiLU(nn.Module):
"""Uses fla.modules.ShortConvolution (zero-transpose Triton conv+SiLU) when available."""
def __init__(self, dim, kernel_size=GDN_CONV_KERNEL):
super().__init__()
self.dim = dim
self.kernel_size = kernel_size
if _HAS_FLA_CONV:
self.short_conv = _FLAShortConv(
hidden_size=dim, kernel_size=kernel_size, bias=False, activation="silu"
)
self.weight = None
else:
self.short_conv = None
self.weight = nn.Parameter(torch.empty(dim, 1, kernel_size))
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
def forward(self, x):
if self.short_conv is not None and x.is_cuda:
res = self.short_conv(x.to(self.short_conv.weight.dtype))
out = res[0] if isinstance(res, tuple) else res
return out.to(x.dtype)
w = self.short_conv.weight if self.short_conv is not None else self.weight
xt = F.pad(x.transpose(1, 2), (self.kernel_size - 1, 0))
out = F.conv1d(xt, w.to(xt.dtype), bias=None, groups=self.dim)
return F.silu(out.transpose(1, 2))
class SWGDN2LocalSWA(nn.Module):
"""Exact SWGDN2-G1 Pseudo-Query-Driven Sliding-Window Attention (Song & Chen, arXiv:2611.33257 Eq. 7-8).
Replaces fixed-coefficient ShortConv1d(W=4)+SiLU before GDN-2 recurrence with
content- & relative-offset-adaptive W=4 SWA using learned per-branch pseudo-queries
(Q, K, V), RMSNorm, and exact relative-offset RoPE:
(RoPE(p^X, t))^T RoPE(k_i, i) == (RoPE(p^X, t - i))^T k_i for delta = t - i in {0..W-1}.
"""
def __init__(self, n_heads, head_dim=HEAD_DIM, window_size=GDN_CONV_KERNEL):
super().__init__()
self.n_heads = int(n_heads)
self.head_dim = int(head_dim)
self.window_size = int(window_size)
# 3 branches (Q, K, V), G=1 group per head -> [3, H, D]
self.pseudo_q = nn.Parameter(
torch.randn(3, self.n_heads, self.head_dim) * (self.head_dim ** -0.5)
)
self.p_norm = nn.Parameter(torch.ones(self.head_dim))
self.k_norm = nn.Parameter(torch.ones(self.head_dim))
half = self.head_dim // 2
inv_freq = ROPE_BASE ** (-torch.arange(half, dtype=torch.float32) / half)
deltas = torch.arange(self.window_size, dtype=torch.float32) # [W] = {0, 1, 2, 3}
angles = torch.outer(deltas, inv_freq) # [W, D/2]
self.register_buffer("rel_cos", torch.cos(angles), persistent=False)
self.register_buffer("rel_sin", torch.sin(angles), persistent=False)
def _rotate_pseudo_q(self, p_n):
# p_n: [3, H, D] -> p_rot: [3, W, H, D] for relative offsets delta in {0..W-1}
half = self.head_dim // 2
p0 = p_n[..., :half].unsqueeze(1) # [3, 1, H, D/2]
p1 = p_n[..., half:].unsqueeze(1)
c = self.rel_cos.to(p_n.dtype).view(1, self.window_size, 1, half)
s = self.rel_sin.to(p_n.dtype).view(1, self.window_size, 1, half)
return torch.cat([p0 * c - p1 * s, p0 * s + p1 * c], dim=-1)
def forward(self, g_qkv):
B, T, _ = g_qkv.shape
H, D, W = self.n_heads, self.head_dim, self.window_size
dt = g_qkv.dtype
q, k, v = g_qkv.view(B, T, 3, H, D).unbind(dim=2) # each [B, T, H, D]
# Eq. (7): RMSNorm + relative-RoPE scoring on projected keys k for all 3 branches
p_n = rms_norm(self.pseudo_q, self.p_norm, out_dtype=dt) # [3, H, D]
k_n = rms_norm(k, self.k_norm, out_dtype=dt) # [B, T, H, D]
p_rot = self._rotate_pseudo_q(p_n) # [3, W, H, D]
# 1-pass Triton SWGDN2-G1 (registered as custom_op -> 0 graph breaks, eliminates ~600 MiB F.pad traffic!)
return fused_swgdn2_local_swa(q, k, v, k_n, p_rot)
class GatedDeltaNet2(nn.Module):
"""Per-head scalar-decay GDN-2 with fused 3x depthwise conv, in-kernel FLA
(L2Norm + gate + beta-sigmoid, scale=1.0, no double-gating), and Chunk-64
block-Schur WY fallback.
"""
def __init__(self, stable_symmetric=True, use_fla=USE_FLA_GDN, n_heads=N_HEADS):
super().__init__()
self.use_fla = bool(use_fla and _HAS_FLA and (not stable_symmetric))
self.stable_symmetric = stable_symmetric
self.n_heads = int(n_heads)
self.attn_dim = self.n_heads * HEAD_DIM
# SWGDN2-G1 (arXiv:2611.33257 Eq. 7-8): intra-SWA (W=4) replacing fixed ShortConv1d
self.local_swa = SWGDN2LocalSWA(self.n_heads, head_dim=HEAD_DIM, window_size=GDN_CONV_KERNEL)
self.f_proj_out = nn.Linear(HEAD_DIM, self.n_heads, bias=False)
a_init = torch.empty(self.n_heads, dtype=torch.float32).uniform_(1.0, 16.0)
self.A_log = nn.Parameter(torch.log(a_init))
dt = torch.exp(
torch.empty(self.n_heads, dtype=torch.float32).uniform_(
math.log(1e-3), math.log(0.1)
)
)
self.dt_bias = nn.Parameter(dt + torch.log(-torch.expm1(-dt)))
self.b_proj = nn.Linear(
D_STREAM, self.n_heads if self.use_fla else self.attn_dim, bias=False
)
self.w_proj = None if self.use_fla else nn.Linear(D_STREAM, self.attn_dim, bias=False)
self.g_proj_out = nn.Linear(HEAD_DIM, self.attn_dim, bias=True)
self.o_norm_weight = nn.Parameter(torch.ones(HEAD_DIM))
def _compute_features_and_gates(self, h, g_qkv, f_in):
B, T, _ = h.shape
H = self.n_heads
q, k, v = self.local_swa(g_qkv)
f_lin = self.f_proj_out(f_in.to(self.f_proj_out.weight.dtype)).float()
b_lin = self.b_proj(h.to(self.b_proj.weight.dtype)).float()
if self.use_fla:
return q, k, v, f_lin, b_lin, None
q = l2_norm(q).float()
k = l2_norm(k).float()
v = v.float()
f_sp = F.softplus(f_lin + self.dt_bias.float())
g_log = (-torch.exp(self.A_log.float()).view(1, 1, H) * f_sp).unsqueeze(-1)
b_gate = torch.sigmoid(b_lin).view(B, T, H, HEAD_DIM)
w_gate = torch.sigmoid(self.w_proj(h).float()).view(B, T, H, HEAD_DIM)
return q, k, v, g_log, b_gate, w_gate
@staticmethod
def recurrent_scan(q, k, v, g_log, b_gate, w_gate, stable_symmetric=True):
B, T, H, K = q.shape
V = v.shape[-1]
S = q.new_zeros(B, H, K, V, dtype=torch.float32)
outs = []
for t in range(T):
qt, kt, vt = q[:, t], k[:, t], v[:, t]
alpha_t = torch.exp(g_log[:, t])
bt, wt = b_gate[:, t], w_gate[:, t]
S_dec = S * alpha_t.unsqueeze(-1)
w_vt = wt * vt
if not stable_symmetric:
ek = bt * kt
erased = torch.einsum("bhkv,bhk->bhv", S_dec, ek)
S = S_dec + torch.einsum("bhk,bhv->bhkv", kt, w_vt - erased)
else:
ut = torch.sqrt(bt.clamp_min(1e-12)) * kt
erased = torch.einsum("bhkv,bhk->bhv", S_dec, ut)
res = torch.sqrt((-torch.expm1(2.0 * g_log[:, t])).clamp_min(1e-12))
k_eff = ut + res * (kt - ut)
S = (
S_dec
- torch.einsum("bhk,bhv->bhkv", ut, erased)
+ torch.einsum("bhk,bhv->bhkv", k_eff, w_vt)
)
outs.append(torch.einsum("bhkv,bhk->bhv", S, qt))
return torch.stack(outs, dim=1), S
@staticmethod
def chunkwise_wy(
q,
k,
v,
g_log,
b_gate,
w_gate,
chunk_size=GDN_CHUNK_SIZE,
stable_symmetric=True,
use_bf16_gram=True,
):
B, T, H, K = q.shape
V = v.shape[-1]
C = chunk_size
pad_t = (C - (T % C)) % C
if pad_t > 0:
q = F.pad(q, (0, 0, 0, 0, 0, pad_t))
k = F.pad(k, (0, 0, 0, 0, 0, pad_t))
v = F.pad(v, (0, 0, 0, 0, 0, pad_t))
g_log = F.pad(g_log, (0, 0, 0, 0, 0, pad_t))
b_gate = F.pad(b_gate, (0, 0, 0, 0, 0, pad_t))
w_gate = F.pad(w_gate, (0, 0, 0, 0, 0, pad_t))
T_pad = q.shape[1]
n_chunks = T_pad // C
def reshape_chunks(x):
return x.transpose(1, 2).reshape(B, H, n_chunks, C, -1)
qc, kc, vc, gc, bc, wc = map(
reshape_chunks, (q, k, v, g_log, b_gate, w_gate)
)
wvc = wc * vc
gamma = gc.cumsum(dim=-2)
dev = q.device
tril_strict = torch.tril(
torch.ones(C, C, device=dev, dtype=torch.bool), diagonal=-1
)
tril_incl = torch.tril(
torch.ones(C, C, device=dev, dtype=torch.bool), diagonal=0
)
eye_c = torch.eye(C, device=dev, dtype=torch.float32)
diff = (gamma - gamma.transpose(-1, -2)).masked_fill(~tril_incl, 0.0)
decay_tril = torch.exp(diff) * tril_incl
decay_strict = decay_tril * tril_strict
exp_gm = torch.exp(gamma)
gm_last = gamma[..., -1:, :]
exp_gm_last = torch.exp(gm_last)
end_decay = torch.exp(gm_last - gamma)
gram_dt = torch.bfloat16 if (use_bf16_gram and q.is_cuda) else torch.float32
exp_gm_last_g = exp_gm_last.to(gram_dt)
wvc_g = wvc.to(gram_dt)
S = q.new_zeros(B, H, K, V, dtype=gram_dt)
outs = []
if not stable_symmetric:
ec = bc * kc
L = torch.matmul(
ec.to(gram_dt), kc.to(gram_dt).transpose(-1, -2)
).float() * decay_strict
A = eye_c + L
A_inv = invert_unit_lower_tri(A).to(gram_dt)
W_wy = torch.matmul(A_inv, (exp_gm * ec).to(gram_dt))
U_wy = torch.matmul(A_inv, wvc_g)
M_g = (
torch.matmul(qc.to(gram_dt), kc.to(gram_dt).transpose(-1, -2)).float()
* decay_tril
).to(gram_dt)
o_local = torch.matmul(M_g, U_wy)
q_eff = (exp_gm * qc).to(gram_dt) - torch.matmul(M_g, W_wy)
k_end_t = (end_decay * kc).to(gram_dt).transpose(-1, -2)
dS_local = torch.matmul(k_end_t, U_wy)
for c_idx in range(n_chunks):
outs.append(
o_local[:, :, c_idx] + torch.matmul(q_eff[:, :, c_idx], S)
)
ws = torch.matmul(W_wy[:, :, c_idx], S)
S = (
S * exp_gm_last_g[:, :, c_idx]
+ dS_local[:, :, c_idx]
- torch.matmul(k_end_t[:, :, c_idx], ws)
)
else:
uc = torch.sqrt(bc.clamp_min(1e-12)) * kc
resc = torch.sqrt((-torch.expm1(2.0 * gc)).clamp_min(1e-12))
keffc = uc + resc * (kc - uc)
u_g = uc.to(gram_dt)
ke_g = keffc.to(gram_dt)
q_g = qc.to(gram_dt)
L_uu = torch.matmul(u_g, u_g.transpose(-1, -2)).float() * decay_strict
A_sym = eye_c + L_uu
R_uke_g = (
torch.matmul(u_g, ke_g.transpose(-1, -2)).float() * decay_strict
).to(gram_dt)
M_qke_g = (
torch.matmul(q_g, ke_g.transpose(-1, -2)).float() * decay_tril
).to(gram_dt)
M_qu_g = (
torch.matmul(q_g, u_g.transpose(-1, -2)).float() * decay_tril
).to(gram_dt)
A_inv = invert_unit_lower_tri(A_sym).to(gram_dt)
W_wy = torch.matmul(A_inv, (exp_gm * uc).to(gram_dt))
Z_local = torch.matmul(A_inv, torch.matmul(R_uke_g, wvc_g))
o_local = torch.matmul(M_qke_g, wvc_g) - torch.matmul(M_qu_g, Z_local)
q_eff = (exp_gm * qc).to(gram_dt) - torch.matmul(M_qu_g, W_wy)
ke_end_t = (end_decay * keffc).to(gram_dt).transpose(-1, -2)
u_end_t = (end_decay * uc).to(gram_dt).transpose(-1, -2)
dS_local = torch.matmul(ke_end_t, wvc_g) - torch.matmul(u_end_t, Z_local)
for c_idx in range(n_chunks):
outs.append(
o_local[:, :, c_idx] + torch.matmul(q_eff[:, :, c_idx], S)
)
ws = torch.matmul(W_wy[:, :, c_idx], S)
S = (
S * exp_gm_last_g[:, :, c_idx]
+ dS_local[:, :, c_idx]
- torch.matmul(u_end_t[:, :, c_idx], ws)
)
out = torch.cat(outs, dim=2).transpose(1, 2)[:, :T].float()
return out, S.float()
def forward(self, h, g_qkv, f_in, g_in, use_chunkwise=True):
B, T, _ = h.shape
dt = h.dtype
q, k, v, g_or_raw, b_or_raw, w_gate = self._compute_features_and_gates(h, g_qkv, f_in)
if self.use_fla and h.is_cuda:
out, _ = _fla_chunk_gdn(
q.to(dt),
k.to(dt),
v.to(dt),
g=g_or_raw.to(dt),
beta=b_or_raw.to(dt),
scale=1.0,
use_qk_l2norm_in_kernel=True,
use_gate_in_kernel=True,
A_log=self.A_log,
dt_bias=self.dt_bias,
use_beta_sigmoid_in_kernel=True,
)
out = out.float()
else:
if self.use_fla:
q = l2_norm(q).float()
k = l2_norm(k).float()
v = v.float()
f_sp = F.softplus(g_or_raw + self.dt_bias.float())
g_log = (-torch.exp(self.A_log.float()).view(1, 1, self.n_heads) * f_sp).unsqueeze(-1)
b_4d = torch.sigmoid(b_or_raw).unsqueeze(-1)
w_gate = b_4d
else:
g_log = g_or_raw
b_4d = b_or_raw.unsqueeze(-1) if b_or_raw.ndim == 3 else b_or_raw
if use_chunkwise:
out, _ = self.chunkwise_wy(
q, k, v, g_log, b_4d, w_gate,
stable_symmetric=self.stable_symmetric,
use_bf16_gram=True,
)
else:
out, _ = self.recurrent_scan(
q, k, v, g_log, b_4d, w_gate,
stable_symmetric=self.stable_symmetric,
)
out_normed = rms_norm(out, self.o_norm_weight)
g_out = F.silu(
F.linear(g_in, self.g_proj_out.weight).float()
+ self.g_proj_out.bias.float()
).view(B, T, self.n_heads, HEAD_DIM)
return (out_normed * g_out).reshape(B, T, self.attn_dim).to(dt)
class HiSASlidingWindowAttention(nn.Module):
"""BF16 SWA-only FlexAttention (score_mod=None) + exact online-softmax pre-RoPE MoLA
with cached RoPE (cos, sin) buffers.
"""
def __init__(self, use_reversible_mola=True, use_flex_attention=USE_FLEX_ATTENTION, n_heads=N_HEADS):
super().__init__()
self.use_reversible_mola = use_reversible_mola
self.use_flex_attention = use_flex_attention and _HAS_FLEX_ATTN
self.n_heads = int(n_heads)
self.attn_dim = self.n_heads * HEAD_DIM
self.q_norm_weight = nn.Parameter(torch.ones(HEAD_DIM))
self.k_norm_weight = nn.Parameter(torch.ones(HEAD_DIM))
if use_reversible_mola:
self.mola_k_mem = nn.Parameter(
torch.randn(self.n_heads, MOLA_MEM_SLOTS, HEAD_DIM) * (HEAD_DIM ** -0.5)
)
self.mola_v_mem = nn.Parameter(
torch.randn(self.n_heads, MOLA_MEM_SLOTS, HEAD_DIM) * (HEAD_DIM ** -0.5)
)
self.mola_beta = nn.Parameter(torch.zeros(self.n_heads))
half = HEAD_DIM // 2
inv_freq = ROPE_BASE ** (-torch.arange(half, dtype=torch.float32) / half)
dmax = torch.floor(HISA_PHI / inv_freq).to(torch.long)
max_pos = max(SEQ_LEN, 2048)
ang = torch.arange(max_pos, dtype=torch.float32)[:, None] * inv_freq[None, :]
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.register_buffer("pair_dmax", dmax, persistent=False)
self.register_buffer("rope_cos", ang.cos()[None, None, :, :], persistent=False)
self.register_buffer("rope_sin", ang.sin()[None, None, :, :], persistent=False)
self._block_mask_cache = {}
self._sdpa_mask_cache = {}
self._compiled_flex = (
torch.compile(flex_attention, mode="default")
if (self.use_flex_attention and USE_TORCH_COMPILE and hasattr(torch, "compile"))
else flex_attention
)
def _apply_interleaved_rope(self, q, k):
T = q.shape[2]
dt = q.dtype
if T <= self.rope_cos.size(2):
cos = self.rope_cos[:, :, :T, :].to(dt)
sin = self.rope_sin[:, :, :T, :].to(dt)
else:
pos = torch.arange(T, device=q.device, dtype=torch.float32)
ang = pos[:, None] * self.inv_freq[None, :]
cos = ang.cos().to(dt)[None, None, :, :]
sin = ang.sin().to(dt)[None, None, :, :]
def rotate(x):
x_even, x_odd = x[..., 0::2], x[..., 1::2]
return torch.stack(
[x_even * cos - x_odd * sin, x_even * sin + x_odd * cos], dim=-1
).flatten(-2)
return rotate(q), rotate(k)
def _scores_block_reference(self, qr, kr):
B, H, T, _ = qr.shape
S = HISA_BLOCK_TOKENS
C_feat = 2 * HISA_CHUNK_PAIRS
n_chunks = HEAD_DIM // C_feat
n_blocks = math.ceil(T / S)
scores = qr.new_zeros(B, H, T, T)
for bq in range(n_blocks):
q0, q1 = bq * S, min(T, (bq + 1) * S)
bk_min = max(0, (q0 - SWA_WINDOW + 1) // S)
for bk in range(bk_min, bq + 1):
k0, k1 = bk * S, min(T, (bk + 1) * S)
min_d = 0 if bq == bk else (bq - bk - 1) * S + 1
keep_pairs = min_d <= self.pair_dmax
if not keep_pairs.any():
continue
tile_score = qr.new_zeros(B, H, q1 - q0, k1 - k0)
for c in range(n_chunks):
p_slice = keep_pairs[
c * HISA_CHUNK_PAIRS : (c + 1) * HISA_CHUNK_PAIRS
]
if not p_slice.any():
continue
f0, f1 = c * C_feat, (c + 1) * C_feat
q_chunk = qr[:, :, q0:q1, f0:f1]
k_chunk = kr[:, :, k0:k1, f0:f1]
if not p_slice.all():
q_chunk = q_chunk * p_slice.repeat_interleave(2).to(qr.dtype)
tile_score = tile_score + torch.matmul(
q_chunk, k_chunk.transpose(-1, -2)
)
scores[:, :, q0:q1, k0:k1] = tile_score / math.sqrt(HEAD_DIM)
return scores
def _scores_block_fast(self, qr, kr):
B, H, T, D = qr.shape
S = HISA_BLOCK_TOKENS
if T % S != 0:
return self._scores_block_reference(qr, kr)
n_blocks = T // S
C_feat = 2 * HISA_CHUNK_PAIRS
max_db = min(n_blocks - 1, SWA_WINDOW // S)
qb = qr.view(B, H, n_blocks, S, D)
kb = kr.view(B, H, n_blocks, S, D)
scores = qr.new_zeros(B, H, n_blocks, S, n_blocks, S)
for db in range(max_db + 1):
min_d = 0 if db == 0 else (db - 1) * S + 1
keep_pairs = min_d <= self.pair_dmax
if not keep_pairs.any():
continue
active_chunks = [
c
for c in range(D // C_feat)
if keep_pairs[
c * HISA_CHUNK_PAIRS : (c + 1) * HISA_CHUNK_PAIRS
].any()
]
f_start = active_chunks[0] * C_feat
f_end = (active_chunks[-1] + 1) * C_feat
feat_mask = (
keep_pairs[f_start // 2 : f_end // 2]
.repeat_interleave(2)
.to(qr.dtype)
)
q_diag = qb[:, :, db:, :, f_start:f_end] * feat_mask
k_diag = kb[:, :, : n_blocks - db, :, f_start:f_end]
diag_scores = torch.matmul(q_diag, k_diag.transpose(-1, -2)) / math.sqrt(
HEAD_DIM
)
b_idx = torch.arange(n_blocks - db, device=qr.device)
scores[:, :, b_idx + db, :, b_idx, :] = diag_scores.permute(2, 0, 1, 3, 4)
return scores.view(B, H, T, T)
def _get_flex_block_mask(self, T, device):
key = (T, str(device))
bm = self._block_mask_cache.get(key)
if bm is None:
def swa_only_mask(b, h, q_idx, kv_idx):
return (q_idx >= kv_idx) & ((q_idx - kv_idx) < SWA_WINDOW)
bm = create_block_mask(
swa_only_mask,
B=None,
H=None,
Q_LEN=T,
KV_LEN=T,
device=device,
)
self._block_mask_cache[key] = bm
return bm
def _get_sdpa_token_mask(self, T, device, dtype):
key = (T, str(device), dtype)
mask = self._sdpa_mask_cache.get(key)
if mask is None:
idx = torch.arange(T, device=device)
dist = idx[:, None] - idx[None, :]
in_window = (dist >= 0) & (dist < SWA_WINDOW)
mask = torch.zeros((1, 1, T, T), device=device, dtype=dtype)
mask.masked_fill_(~in_window.view(1, 1, T, T), float("-inf"))
if len(self._sdpa_mask_cache) > 64:
self._sdpa_mask_cache.clear()
self._sdpa_mask_cache[key] = mask
return mask
def prepare_mask(self, T, device, dtype):
use_flex = (
self.use_flex_attention
and device.type == "cuda"
and (self.training or T == SEQ_LEN)
and (T > SWA_WINDOW)
)
if use_flex:
return self._get_flex_block_mask(T, device), None
if T <= SWA_WINDOW:
return None, None
return None, self._get_sdpa_token_mask(T, device, dtype)
def _run_flex_lse(self, q, k, v, block_mask):
is_compiling = (
hasattr(torch, "compiler")
and hasattr(torch.compiler, "is_compiling")
and torch.compiler.is_compiling()
)
fn = flex_attention if is_compiling else self._compiled_flex
return fn(q, k, v, block_mask=block_mask, return_lse=True)
def forward(self, sq, sk, sv, block_mask=None, tok_mask=None):
B, T, _ = sq.shape
dt = sq.dtype
q = sq.view(B, T, self.n_heads, HEAD_DIM)
k = sk.view(B, T, self.n_heads, HEAD_DIM)
v = sv.view(B, T, self.n_heads, HEAD_DIM)
q_normed = rms_norm(q, self.q_norm_weight, out_dtype=dt).transpose(1, 2)
k_normed = rms_norm(k, self.k_norm_weight, out_dtype=dt).transpose(1, 2)
v_t = v.to(dt).transpose(1, 2)
qr, kr = self._apply_interleaved_rope(q_normed, k_normed)
if self.use_reversible_mola and block_mask is not None:
o_tok, lse_tok = self._run_flex_lse(qr, kr, v_t, block_mask)
k_mem_n = rms_norm(self.mola_k_mem, self.k_norm_weight, out_dtype=dt)
is_comp = (
hasattr(torch, "compiler")
and hasattr(torch.compiler, "is_compiling")
and torch.compiler.is_compiling()
)
if (not is_comp) or (USE_TRITON_MOLA_IN_COMPILE and _HAS_MOLA_CUSTOM_OP):
# Custom Triton Kernel 3: 1-pass Pre-RoPE MoLA online-softmax merge (custom_op -> 0 graph breaks!)
if _HAS_MOLA_CUSTOM_OP and o_tok.is_cuda:
out, _ = _mola_op_fwd(
o_tok, lse_tok, q_normed, k_mem_n, self.mola_v_mem.to(dt), self.mola_beta
)
else:
out = fused_mola_online_merge(
o_tok, lse_tok, q_normed, k_mem_n, self.mola_v_mem.to(dt), self.mola_beta
)
else:
scores_mem = (
torch.matmul(q_normed, k_mem_n.transpose(-1, -2)).float()
/ math.sqrt(HEAD_DIM)
+ self.mola_beta.float().view(1, self.n_heads, 1, 1)
)
lse_mem = torch.logsumexp(scores_mem, dim=-1)
o_mem = torch.matmul(
torch.softmax(scores_mem, dim=-1).to(dt), self.mola_v_mem.to(dt)
)
alpha = torch.sigmoid(lse_mem - lse_tok.detach()).unsqueeze(-1).to(dt)
out = (1.0 - alpha) * o_tok + alpha * o_mem
elif self.use_reversible_mola:
k_mem_n = rms_norm(self.mola_k_mem, self.k_norm_weight, out_dtype=dt)
scores_tok = torch.matmul(qr, kr.transpose(-1, -2)).float() / math.sqrt(HEAD_DIM)
tm = (
tok_mask
if tok_mask is not None
else self._get_sdpa_token_mask(T, sq.device, torch.float32)
)
scores_tok = scores_tok + tm.float()
scores_mem = (
torch.matmul(q_normed, k_mem_n.transpose(-1, -2)).float()
/ math.sqrt(HEAD_DIM)
+ self.mola_beta.float().view(1, self.n_heads, 1, 1)
)
attn_joint = torch.softmax(torch.cat([scores_tok, scores_mem], dim=-1), dim=-1).to(dt)
out = torch.matmul(attn_joint[..., :T], v_t) + torch.matmul(
attn_joint[..., T:], self.mola_v_mem.to(dt)
)
else:
if T <= SWA_WINDOW:
out = F.scaled_dot_product_attention(qr, kr, v_t, is_causal=True)
elif block_mask is not None:
out, _ = self._run_flex_lse(qr, kr, v_t, block_mask)
else:
tm = (
tok_mask
if tok_mask is not None
else self._get_sdpa_token_mask(T, sq.device, dt)
)
out = F.scaled_dot_product_attention(qr, kr, v_t, attn_mask=tm)
return out.transpose(1, 2).reshape(B, T, self.attn_dim).to(dt)
class ReversibleReasoningBlock(nn.Module):
"""Single reversible block used for Prelude (2x), Shared Core (r loops), and Coda (2x).
- Optional gated Input Injection from post-Prelude anchor (a1, a2)
- Optional MoD-style token-sparse UltraMemV2 gate inside the FFN (top 12.5% tokens)
"""
def __init__(
self,
gdn_stable_symmetric=True,
use_reversible_mola=True,
use_anchor_inject=False,
use_gated_mem=False,
use_givens=True,
use_sandwich_norm=False,
anchor_init=-1.5,
seq_mixer="parallel",
):
super().__init__()
assert seq_mixer in ("parallel", "gdn", "swa"), f"Unknown seq_mixer={seq_mixer}"
self.seq_mixer = seq_mixer
self.use_anchor_inject = use_anchor_inject
self.use_gated_mem = use_gated_mem
self.use_givens = use_givens
self.use_sandwich_norm = use_sandwich_norm
self.theta = nn.Parameter(torch.tensor(math.pi / 64.0)) if use_givens else None
self.gamma_seq = nn.Parameter(torch.ones(D_STREAM))
self.gamma_seq_post = nn.Parameter(torch.ones(D_STREAM))
self.gamma_ffn = nn.Parameter(torch.ones(D_STREAM))
self.gamma_ffn_post = nn.Parameter(torch.ones(D_STREAM))
self.scale_1 = nn.Parameter(torch.tensor(INIT_SCALE))
self.scale_2 = nn.Parameter(torch.tensor(INIT_SCALE))
if use_sandwich_norm:
# Huginn sandwich-norm hard-clamps ||y1||, ||y2|| to unit RMS at 8..40 loops
self.stream_norm_1 = nn.Parameter(torch.ones(D_STREAM))
self.stream_norm_2 = nn.Parameter(torch.ones(D_STREAM))
if use_anchor_inject:
# Parcae ZOH decay (lam = exp(-softplus(-3.0)) ~= 0.953/iter -> no premature 16L freeze!)
self.zoh_log_decay_1 = nn.Parameter(torch.full((D_STREAM,), -3.0))
self.zoh_log_decay_2 = nn.Parameter(torch.full((D_STREAM,), -3.0))
self.anchor_gate_1 = nn.Parameter(torch.full((D_STREAM,), float(anchor_init)))
self.anchor_gate_2 = nn.Parameter(torch.full((D_STREAM,), float(anchor_init)))
full_heads = D_STREAM // HEAD_DIM # 16 heads x 64 = 1024 full-width sequential mixer
if seq_mixer == "gdn":
self.qkv_fg_fused = nn.Linear(D_STREAM, 3 * D_STREAM + 2 * HEAD_DIM, bias=False)
self.gdn = GatedDeltaNet2(stable_symmetric=gdn_stable_symmetric, n_heads=full_heads)
self.swa = None
elif seq_mixer == "swa":
self.qkv_fg_fused = nn.Linear(D_STREAM, 3 * D_STREAM, bias=False)
self.gdn = None
self.swa = HiSASlidingWindowAttention(use_reversible_mola=use_reversible_mola, n_heads=full_heads)
else:
# Parallel Prelude/Coda: single fused 1024 -> 3200 FP8 GEMM for GDN(512) + SWA(512)
self.qkv_fg_fused = nn.Linear(D_STREAM, 6 * ATTN_DIM + 2 * HEAD_DIM, bias=False)
self.gdn = GatedDeltaNet2(stable_symmetric=gdn_stable_symmetric, n_heads=N_HEADS)
self.swa = HiSASlidingWindowAttention(use_reversible_mola=use_reversible_mola, n_heads=N_HEADS)
self.out_proj = nn.Linear(D_STREAM, D_STREAM, bias=False)
self.w_gate_up = nn.Linear(D_STREAM, 2 * FFN_HIDDEN, bias=False)
self.w_down = nn.Linear(FFN_HIDDEN, D_STREAM, bias=False)
if use_gated_mem:
self.mem_need_gate = nn.Linear(D_STREAM, 1, bias=True)
nn.init.zeros_(self.mem_need_gate.bias)
self.register_buffer(
"eval_thr", torch.tensor(MEM_EVAL_THRESHOLD, dtype=torch.float32)
)
self._dense_step_compiled = None
self.last_mem_gate_mean = 0.0
self.last_mem_active_frac = 0.0
def _dense_step_impl(self, x1, x2, block_mask, tok_mask, k_base=None, v_base=None):
dt = x1.dtype
if self.use_givens and self.theta is not None:
th = self.theta.float()
c = torch.cos(th).to(dt)
s = torch.sin(th).to(dt)
xp1 = c * x1 - s * x2
xp2 = s * x1 + c * x2
else:
# Orientation-invariant reversible coupling (no >90 deg rotation drift at 24..40 loops!)
xp1, xp2 = x1, x2
if self.seq_mixer == "swa" and isinstance(self.qkv_fg_fused, CachedFP8Linear):
# 1-pass Triton RMSNorm->FP8 + cached FP8 weight GEMM (skips intermediate BF16 h_seq!)
sq, sk, sv = self.qkv_fg_fused.forward_from_rmsnorm(xp2, self.gamma_seq, eps=EPS).chunk(3, dim=-1)
mixed = self.swa(sq, sk, sv, block_mask=block_mask, tok_mask=tok_mask)
else:
h_seq = rms_norm(xp2, self.gamma_seq, out_dtype=self.qkv_fg_fused.weight.dtype)
if self.seq_mixer == "gdn":
g_qkv, f_in, g_in = self.qkv_fg_fused(h_seq).split(
[3 * D_STREAM, HEAD_DIM, HEAD_DIM], dim=-1
)
mixed = self.gdn(h_seq, g_qkv, f_in, g_in)
elif self.seq_mixer == "swa":
sq, sk, sv = self.qkv_fg_fused(h_seq).chunk(3, dim=-1)
if k_base is not None:
sk = sk + k_base.to(sk.dtype)
sv = sv + v_base.to(sv.dtype)
mixed = self.swa(sq, sk, sv, block_mask=block_mask, tok_mask=tok_mask)
else:
g_qkv, sq, sk, sv, f_in, g_in = self.qkv_fg_fused(h_seq).split(
[3 * ATTN_DIM, ATTN_DIM, ATTN_DIM, ATTN_DIM, HEAD_DIM, HEAD_DIM], dim=-1
)
mixed = torch.cat(
[
self.gdn(h_seq, g_qkv, f_in, g_in),
self.swa(sq, sk, sv, block_mask=block_mask, tok_mask=tok_mask),
],
dim=-1,
)
f_out = rms_norm(self.out_proj(mixed), self.gamma_seq_post)
y1 = xp1 + self.scale_1.to(dt) * f_out.to(dt)
if self.use_sandwich_norm:
y1 = rms_norm(y1, self.stream_norm_1, out_dtype=dt)
if (not self.use_gated_mem) and isinstance(self.w_gate_up, CachedFP8Linear):
h_ffn = None
gate_up = self.w_gate_up.forward_from_rmsnorm(y1, self.gamma_ffn, eps=EPS)
else:
h_ffn = rms_norm(y1, self.gamma_ffn, out_dtype=self.w_gate_up.weight.dtype)
gate_up = self.w_gate_up(h_ffn)
if isinstance(self.w_down, CachedFP8Linear):
# 1-pass Triton SwiGLU->FP8 + cached FP8 w_down GEMM (cuts ~500 MiB/block BF16<->FP8 traffic!)
ffn_out = rms_norm(self.w_down.forward_from_swiglu(gate_up), self.gamma_ffn_post).to(dt)
else:
gate, up = gate_up.chunk(2, dim=-1)
ffn_out = rms_norm(self.w_down(F.silu(gate) * up), self.gamma_ffn_post).to(dt)
# Return h_ffn and run N=1 mem_need_gate outside max-autotune (avoids Inductor [1,1024]->[1024] bwd squeeze bug!)
return y1, xp2, ffn_out, (h_ffn if self.use_gated_mem else None)
def compile_step(self, mode=CORE_COMPILE_MODE):
if hasattr(torch, "compile"):
self._dense_step_compiled = torch.compile(self._dense_step_impl, mode=mode)
def forward(
self,
x1,
x2,
a1=None,
a2=None,
bridge=None,
collect_telemetry=False,
cached_masks=None,
contraction_gate=None,
):
if self.swa is None:
bm, tm = None, None
elif cached_masks is not None:
bm, tm = cached_masks
else:
bm, tm = self.swa.prepare_mask(x1.shape[1], x1.device, self.qkv_fg_fused.weight.dtype)
if self.use_anchor_inject and a1 is not None:
# Custom Triton Kernel 2B: 1-pass OrthoInj + ZOH outside compile (zero graph breaks!)
lam1 = torch.exp(-F.softplus(self.zoh_log_decay_1.float()))
lam2 = torch.exp(-F.softplus(self.zoh_log_decay_2.float()))
g1 = torch.sigmoid(self.anchor_gate_1.float())
g2 = torch.sigmoid(self.anchor_gate_2.float())
x1 = fused_orthoinj_zoh(x1, a1, lam1, g1, eps=EPS)
x2 = fused_orthoinj_zoh(x2, a2, lam2, g2, eps=EPS)
fn = (
self._dense_step_compiled
if (self.training and self._dense_step_compiled is not None)
else self._dense_step_impl
)
tala_kv = getattr(self, "_active_tala_kv", None)
if tala_kv is not None:
y1, xp2, ffn_out, h_ffn_mg = fn(x1, x2, bm, tm, tala_kv[0], tala_kv[1])
else:
y1, xp2, ffn_out, h_ffn_mg = fn(x1, x2, bm, tm)
dt = x1.dtype
aux_loss = None
if self.use_gated_mem and bridge is not None and h_ffn_mg is not None:
# Custom Triton Kernel 5A: fused mem_need_gate + sigmoid + c_gate (guaranteed [1,1024] bwd!)
c_flat = contraction_gate.reshape(-1) if contraction_gate is not None else None
eff_score = fused_mod_gate_score(
h_ffn_mg.reshape(-1, D_STREAM),
self.mem_need_gate.weight,
self.mem_need_gate.bias,
c_flat,
)
n_tok = eff_score.numel()
if self.training or n_tok >= 8:
k_tok = max(1, int(n_tok * MEM_CAPACITY_FRAC))
top_g, top_idx = torch.topk(eff_score, k=k_tok, sorted=False)
h_sel = y1.reshape(-1, D_STREAM).index_select(0, top_idx)
m_sel, aux_loss = bridge.forward_flat(h_sel)
# MoD-style BCE calibration + EMA eval threshold on exact eff_score
if self.training and torch.is_grad_enabled():
is_sel = torch.zeros_like(eff_score, dtype=torch.float32)
is_sel.scatter_(0, top_idx, 1.0)
gate_bce = F.binary_cross_entropy(
eff_score.float().clamp(1e-6, 1.0 - 1e-6), is_sel
)
aux_loss = 0.05 * gate_bce
with torch.no_grad():
self.eval_thr.lerp_(top_g.min().detach().float(), 0.05)
# Custom Triton Kernel 5B: fused scaled scatter-add (no 16 MiB mem_delta / 64 MiB clone!)
ffn_out = fused_mod_scaled_scatter_add(
ffn_out.reshape(-1, D_STREAM),
top_idx,
top_g,
bridge.bridge_scale,
m_sel,
inplace=False,
).view_as(ffn_out)
if collect_telemetry:
with torch.no_grad():
self.last_mem_gate_mean = float(eff_score.mean().item())
self.last_mem_active_frac = float(k_tok / max(1, n_tok))
b_scale_f = float(bridge.bridge_scale.float().item())
b_rms = (
(top_g.float().pow(2) * m_sel.float().pow(2).mean(dim=-1)).mean().sqrt().item()
* abs(b_scale_f)
)
f_rms = ffn_out.float().pow(2).mean().sqrt().clamp_min(1e-6).item()
bridge.last_bridge_rms_ratio = float(b_rms / f_rms)
else:
sel_mask = eff_score > self.eval_thr
if sel_mask.any():
top_idx = sel_mask.nonzero(as_tuple=False).squeeze(-1)
top_g = eff_score.index_select(0, top_idx)
h_sel = y1.reshape(-1, D_STREAM).index_select(0, top_idx)
m_sel, _ = bridge.forward_flat(h_sel)
ffn_out = fused_mod_scaled_scatter_add(
ffn_out.reshape(-1, D_STREAM),
top_idx,
top_g,
bridge.bridge_scale,
m_sel,
inplace=False,
).view_as(ffn_out)
y2 = xp2 + self.scale_2.to(dt) * ffn_out
if self.use_sandwich_norm:
y2 = rms_norm(y2, self.stream_norm_2, out_dtype=dt)
return y1, y2, aux_loss
class ECHOCausalSelfRecursion(nn.Module):
"""ECHO Causal Self-Recursion (Zhou et al., 2026, arXiv:2610.24766)."""
def __init__(self):
super().__init__()
self.norm_h1 = nn.Parameter(torch.ones(D_STREAM))
self.norm_h2 = nn.Parameter(torch.ones(D_STREAM))
self.norm_e1 = nn.Parameter(torch.ones(D_STREAM))
self.norm_e2 = nn.Parameter(torch.ones(D_STREAM))
self.w_fuse = nn.Linear(2 * D_STREAM, D_STREAM, bias=False)
self._fuse_step_compiled = None
@staticmethod
def sample_dds_depth(probs=ECHO_DDS_PROBS):
p = torch.tensor(probs, dtype=torch.float32)
return int(torch.multinomial(p, num_samples=1).item()) + 1
def _fuse_step_impl(self, x1, x2, emb):
e1, e2 = emb.chunk(2, dim=-1)
dt = self.w_fuse.weight.dtype
def fuse(x, nx, e, ne):
parts = [rms_norm(x, nx, out_dtype=dt), rms_norm(e, ne, out_dtype=dt)]
return self.w_fuse(torch.cat(parts, dim=-1)).to(x.dtype)
return (
fuse(x1, self.norm_h1, e1, self.norm_e1),
fuse(x2, self.norm_h2, e2, self.norm_e2),
)
def fuse_step(self, x1, x2, emb):
fn = (
self._fuse_step_compiled
if (self.training and self._fuse_step_compiled is not None)
else self._fuse_step_impl
)
return fn(x1, x2, emb)
def forward(self, coda_block, h_backbone, future_token_embs):
x1, x2 = h_backbone.chunk(2, dim=-1)
horizon_states = []
for emb_k in future_token_embs:
x1, x2 = self.fuse_step(x1, x2, emb_k)
x1, x2, _ = coda_block(x1, x2)
horizon_states.append(torch.cat([x1, x2], dim=-1))
return horizon_states
# ================= UNIFIED PRELUDE + SHARED CORE + CODA + DUAL-TIER GDDR7 LM
class ContinuousLoopCond(nn.Module):
"""Continuous Fourier/sinusoidal depth conditioning for arbitrary post-training loop extrapolation.
Never uses a discrete nn.Embedding(max_loops, D) table: encodes both linear (r / r_ref) and
log-compressed (log(1+r) / log(1+r_ref)) depth ratios with zero-initialized FiLM outputs so
step-0 is an exact identity and post-training 2x+ loop doubling (e.g. 40L -> 80L+) is smooth.
"""
def __init__(
self,
d_stream: int = D_STREAM,
n_freqs: int = LOOP_FOURIER_FREQS,
hidden: int = LOOP_COND_HIDDEN,
):
super().__init__()
freqs = torch.exp(torch.linspace(0.0, math.log(16.0), n_freqs)) * math.pi
self.register_buffer("freqs", freqs, persistent=False)
self.fc1 = nn.Linear(4 * n_freqs, hidden)
self.fc_out = nn.Linear(hidden, 4 * d_stream)
nn.init.zeros_(self.fc_out.weight)
nn.init.zeros_(self.fc_out.bias)
def forward(self, loop_idx: int, r_ref: int = LOOP_COND_R_REF):
t_lin = float(loop_idx) / float(max(1, r_ref))
t_log = math.log1p(float(loop_idx)) / math.log1p(float(max(1, r_ref)))
ang_lin = self.freqs * t_lin
ang_log = self.freqs * t_log
feat = torch.cat(
[torch.sin(ang_lin), torch.cos(ang_lin), torch.sin(ang_log), torch.cos(ang_log)],
dim=-1,
).float()
h = F.silu(F.linear(feat, self.fc1.weight.float(), self.fc1.bias.float()))
out = F.linear(h, self.fc_out.weight.float(), self.fc_out.bias.float())
s1, b1, s2, b2 = out.chunk(4, dim=-1)
return s1, b1, s2, b2
class HoistedTALABase(nn.Module):
"""Option 1 Hoisted TALA-Base (arXiv:2611.39694, Eq. 13-14):
Derives a single shared token-anchored Base latent b = W_B(x0) from the initial token
embedding x0 (before any contextual attention) and pre-decodes (k_base, v_base) ONCE
per sequence outside the SharedCell loop, adding it as a zero-initialized residual to
Block 1 SWA keys and values across all 10L..40L (and 80L post-train) iterations.
"""
def __init__(self, d_in: int = D_TOTAL, d_base: int = TALA_BASE_DIM, d_kv: int = D_STREAM):
super().__init__()
self.norm = nn.Parameter(torch.ones(d_in))
self.w_down = nn.Linear(d_in, d_base, bias=False)
self.w_up_kv = nn.Linear(d_base, 2 * d_kv, bias=False)
nn.init.zeros_(self.w_up_kv.weight) # exact identity at step 0 (k_base=0, v_base=0)
def forward(self, x0: torch.Tensor):
h = rms_norm(x0, self.norm, out_dtype=self.w_down.weight.dtype)
b = self.w_down(h)
k_base, v_base = self.w_up_kv(b).chunk(2, dim=-1)
return k_base, v_base
class L2GDDR7HybridLanguageModel(nn.Module):
"""Unified Language Model:
- Outer Tied Vocabulary Embeddings & LM Head (L2-pinned Liger CE)
- Async CUDA Stream Prefetch for Layer-2 DeepSeek Engram (after Prelude 2)
- Prelude (2 blocks, FP8/BF16) -> Engram Gate -> Save h_anchor
- Shared L2-Pinned Core x r loops (PLN Stochastic Depth + TBPTT b=6 +
Gated h_anchor Injection + Top-12.5% MoD-Gated UltraMemV2 Multi-Hop)
- Coda (2 blocks, FP8/BF16) + ECHO Causal Self-Recursion
"""
def __init__(self, vocab_size, canonical_map, device, rank=0, world_size=1):
super().__init__()
self.vocab_size = vocab_size
self.tok_emb = nn.Embedding(vocab_size, D_VOCAB)
nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02)
self.emb_up = nn.Linear(D_VOCAB, D_TOTAL, bias=False)
self.lm_down = nn.Linear(D_TOTAL, D_VOCAB, bias=False)
use_sym = not (USE_FLA_GDN and _HAS_FLA)
self.prelude = nn.ModuleList(
[
ReversibleReasoningBlock(
gdn_stable_symmetric=use_sym,
use_reversible_mola=True,
use_anchor_inject=False,
use_gated_mem=False,
)
for _ in range(N_PRELUDE)
]
)
self.engram = EngramConditionalMemory(canonical_map, SPARSE_MEMORY_CFG, device, rank=rank, world_size=world_size)
# Sequential 2-block recurrent cell:
# Block 0: OrthoInj+ZOH + Full-Width GDN-2 (16 heads x 64 = 1024) + FFN
# Block 1: Full-Width SWA+MoLA (16 heads x 64 = 1024) + FFN + topK=32 UltraMemV2 + Post-Cell RMSNorm
self.shared_core = nn.ModuleList(
[
ReversibleReasoningBlock(
gdn_stable_symmetric=use_sym,
use_reversible_mola=True,
use_anchor_inject=(i == 0),
use_gated_mem=(i == N_SHARED_CELL_BLOCKS - 1),
use_givens=False,
use_sandwich_norm=(i == N_SHARED_CELL_BLOCKS - 1),
anchor_init=-1.5,
seq_mixer=("gdn" if i == 0 else "swa"),
)
for i in range(N_SHARED_CELL_BLOCKS)
]
)
self.last_eval_step_rms = 0.0
self.loop_cond = (
ContinuousLoopCond(D_STREAM, LOOP_FOURIER_FREQS, LOOP_COND_HIDDEN)
if ENABLE_CONTINUOUS_LOOP_COND
else None
)
self.tala_base = (
HoistedTALABase(D_TOTAL, TALA_BASE_DIM, D_STREAM)
if ENABLE_TALA_BASE
else None
)
self.bridge = UltraMemV2TDQKRBridge(SPARSE_MEMORY_CFG, device, rank=rank, world_size=world_size)
self.coda = nn.ModuleList(
[
ReversibleReasoningBlock(
gdn_stable_symmetric=use_sym,
use_reversible_mola=True,
use_anchor_inject=False,
use_gated_mem=False,
)
for _ in range(N_CODA)
]
)
self.echo = ECHOCausalSelfRecursion()
self.final_norm = nn.Parameter(torch.ones(D_TOTAL))
self._final_norm_compiled = None
self._engram_stream = (
torch.cuda.Stream(device=device) if (device.type == "cuda" and world_size == 1) else None
)
if PREFER_CUT_CE and _HAS_CUT_CE and device.type == "cuda":
self._liger_ce = None
self.ce_backend = "cut_cross_entropy"
elif _HAS_LIGER_CE and device.type == "cuda":
self._liger_ce = LigerFusedLinearCrossEntropyLoss()
self.ce_backend = "liger_fused_linear_ce"
else:
self._liger_ce = None
self.ce_backend = "chunked_checkpointed_ce"
def set_telemetry(self, enabled: bool):
self.engram.collect_telemetry = enabled
self.bridge.collect_telemetry = enabled
def compile_hot_paths(self, enabled: bool):
if not enabled or not hasattr(torch, "compile"):
return False
for blk in self.prelude:
blk.compile_step(mode="default")
for blk in self.shared_core:
blk.compile_step(mode=CORE_COMPILE_MODE)
for blk in self.coda:
blk.compile_step(mode="default")
self.engram._gate_and_project_compiled = torch.compile(
self.engram._gate_and_project, mode="default"
)
self.bridge._route_flat_compiled = torch.compile(
self.bridge._route_and_score_flat, mode="default", dynamic=False
)
self.bridge._proj_flat_compiled = torch.compile(
self.bridge._gate_and_project_flat, mode="default", dynamic=False
)
self.echo._fuse_step_compiled = torch.compile(
self.echo._fuse_step_impl, mode="default"
)
self._final_norm_compiled = torch.compile(self._apply_final_norm, mode="default", dynamic=True)
return True
def embed_tokens(self, input_ids):
return self.emb_up(self.tok_emb(input_ids))
def _apply_final_norm(self, hidden):
h_n = rms_norm(hidden, self.final_norm, out_dtype=self.lm_down.weight.dtype)
return self.lm_down(h_n).to(self.tok_emb.weight.dtype)
def forward_backbone(self, input_ids, n_shared_iters=6, tbptt_iters=None):
"""Run Prelude(2) + Async Layer-2 Engram + SharedCore(2-block cell x n_shared_iters) + Coda(2)."""
if self._engram_stream is not None:
cur_stream = torch.cuda.current_stream(input_ids.device)
self._engram_stream.wait_stream(cur_stream)
with torch.cuda.stream(self._engram_stream):
e_t_prefetched = self.engram.prefetch_embeddings(input_ids)
else:
e_t_prefetched = self.engram.prefetch_embeddings(input_ids)
x0 = self.embed_tokens(input_ids)
x1, x2 = x0.chunk(2, dim=-1)
for blk in self.prelude:
x1, x2, _ = blk(x1, x2)
if self._engram_stream is not None:
cur_stream = torch.cuda.current_stream(input_ids.device)
cur_stream.wait_stream(self._engram_stream)
e_t_prefetched.record_stream(cur_stream)
x1 = self.engram.apply_prefetched(x1, e_t_prefetched)
# Hoist SWA BlockMask once per micro-batch from SWA block (Block 1 in sequential shared_core!)
swa_blk = self.shared_core[-1] if self.shared_core[-1].swa is not None else self.coda[-1]
cached_masks = swa_blk.swa.prepare_mask(
x1.shape[1], x1.device, swa_blk.qkv_fg_fused.weight.dtype
)
# Unit-RMS anchor + Path-Independent Init (prevents shallow-loop cheating!)
a1, a2 = rms_norm(x1), rms_norm(x2)
if self.training:
x1 = torch.randn_like(a1) * 0.02
x2 = torch.randn_like(a2) * 0.02
else:
x1 = torch.zeros_like(a1)
x2 = torch.zeros_like(a2)
if tbptt_iters is not None and self.training and torch.is_grad_enabled():
n_nograd = max(0, n_shared_iters - tbptt_iters)
else:
n_nograd = 0
# Option 1 Hoisted TALA-Base: compute (k_base, v_base) ONCE per sequence outside the loop!
tala_blk = self.shared_core[-1] if (self.tala_base is not None and self.shared_core[-1].seq_mixer == "swa") else None
x1_prev = None
if n_nograd > 0:
with torch.no_grad():
if tala_blk is not None:
tala_blk._active_tala_kv = self.tala_base(x0)
try:
for iter_ng in range(n_nograd):
if x1_prev is not None:
step_rms = (x1 - x1_prev).pow(2).mean(dim=-1, dtype=torch.float32).sqrt()
c_gate = 0.65 + 0.35 * torch.tanh(step_rms / 0.05)
else:
c_gate = None
x1_prev = x1
if self.loop_cond is not None:
s1, b1, s2, b2 = self.loop_cond(iter_ng)
x1 = x1 * (1.0 + s1.to(x1.dtype)) + b1.to(x1.dtype)
x2 = x2 * (1.0 + s2.to(x2.dtype)) + b2.to(x2.dtype)
for blk in self.shared_core:
x1, x2, _ = blk(
x1,
x2,
a1=a1,
a2=a2,
bridge=self.bridge,
collect_telemetry=False,
cached_masks=cached_masks,
contraction_gate=c_gate,
)
finally:
if tala_blk is not None:
tala_blk._active_tala_kv = None
x1, x2 = x1.detach(), x2.detach()
x1_prev = x1_prev.detach() if x1_prev is not None else None
n_grad_iters = n_shared_iters - n_nograd
aux_total = x1.new_zeros((), dtype=torch.float32)
aux_count = 0
mid_idx = 0 # widest contrast inside TBPTT window (r_final - 3 vs r_final)
mid_pair = None
last_step_rms = None
prev_step_rms = None
if tala_blk is not None:
tala_blk._active_tala_kv = self.tala_base(x0)
try:
for idx_g in range(n_grad_iters):
is_last_iter = (idx_g == n_grad_iters - 1)
if last_step_rms is not None:
c_gate = 0.65 + 0.35 * torch.tanh(last_step_rms.detach() / 0.05)
elif x1_prev is not None:
sr = (x1 - x1_prev).pow(2).mean(dim=-1, dtype=torch.float32).sqrt()
c_gate = 0.65 + 0.35 * torch.tanh(sr.detach() / 0.05)
else:
c_gate = None
x1_before = x1
if self.loop_cond is not None:
s1, b1, s2, b2 = self.loop_cond(n_nograd + idx_g)
x1 = x1 * (1.0 + s1.to(x1.dtype)) + b1.to(x1.dtype)
x2 = x2 * (1.0 + s2.to(x2.dtype)) + b2.to(x2.dtype)
for b_idx, blk in enumerate(self.shared_core):
is_last_blk = is_last_iter and (b_idx == len(self.shared_core) - 1)
x1, x2, aux_l = blk(
x1,
x2,
a1=a1,
a2=a2,
bridge=self.bridge,
collect_telemetry=(self.bridge.collect_telemetry and is_last_blk),
cached_masks=cached_masks,
contraction_gate=c_gate,
)
if aux_l is not None:
aux_total = aux_total + aux_l
aux_count += 1
prev_step_rms = last_step_rms
last_step_rms = (x1 - x1_before).pow(2).mean(dim=-1, dtype=torch.float32).sqrt()
if self.training and n_grad_iters >= 2 and idx_g == mid_idx and RMID_LOSS_COEFF > 0.0:
b_mid = max(1, int(round(input_ids.size(0) * RMID_BATCH_FRAC)))
mid_pair = (x1[:b_mid], x2[:b_mid])
finally:
if tala_blk is not None:
tala_blk._active_tala_kv = None
aux_loss = aux_total / max(1, aux_count)
if self.training and CONTRACTION_REG_COEFF > 0.0 and prev_step_rms is not None and last_step_rms is not None:
aux_loss = aux_loss + CONTRACTION_REG_COEFF * F.relu(
last_step_rms - 0.97 * prev_step_rms.detach()
).mean()
if not self.training and last_step_rms is not None:
self.last_eval_step_rms = float(last_step_rms.mean().item())
# Coda readout refinement (plus Ouro r_mid sub-batch readout when active)
for blk in self.coda:
x1, x2, _ = blk(x1, x2, cached_masks=cached_masks)
h_out = torch.cat([x1, x2], dim=-1)
h_mid_out = None
if mid_pair is not None:
mx1, mx2 = mid_pair
for blk in self.coda:
mx1, mx2, _ = blk(mx1, mx2, cached_masks=cached_masks)
h_mid_out = torch.cat([mx1, mx2], dim=-1)
return h_out, aux_loss, h_mid_out
@staticmethod
def _chunk_ce_sum(h_chunk, w, t_chunk):
logits = F.linear(h_chunk, w).float()
return F.cross_entropy(logits, t_chunk, reduction="sum")
def compute_lm_loss(self, hidden, targets):
h_norm = self._apply_final_norm(hidden)
h_flat = h_norm.reshape(-1, D_VOCAB)
t_flat = targets.reshape(-1)
if self._liger_ce is not None:
n_tok = h_flat.size(0)
sub = LIGER_SUB_BATCH_TOKENS
if n_tok <= sub:
return self._liger_ce(self.tok_emb.weight, h_flat, t_flat)
total_loss = h_flat.new_zeros((), dtype=torch.float32)
for s in range(0, n_tok, sub):
e = min(n_tok, s + sub)
total_loss = total_loss + self._liger_ce(
self.tok_emb.weight, h_flat[s:e], t_flat[s:e]
) * ((e - s) / n_tok)
return total_loss
if self.ce_backend == "cut_cross_entropy":
return _cce_linear_cross_entropy(h_flat, self.tok_emb.weight, t_flat)
n_tok = h_flat.size(0)
total_loss = h_flat.new_zeros((), dtype=torch.float32)
use_ckpt = self.training and torch.is_grad_enabled()
for start in range(0, n_tok, CE_CHUNK_TOKENS):
end = min(n_tok, start + CE_CHUNK_TOKENS)
hc = h_flat[start:end]
tc = t_flat[start:end]
if use_ckpt:
total_loss = total_loss + checkpoint(
self._chunk_ce_sum, hc, self.tok_emb.weight, tc, use_reentrant=False
)
else:
total_loss = total_loss + self._chunk_ce_sum(hc, self.tok_emb.weight, tc)
return total_loss / n_tok
def forward_train(
self,
input_ids,
target_horizons,
n_shared_iters,
dds_depth=ECHO_FIXED_DEPTH,
echo_batch_frac=ECHO_BATCH_FRAC,
tbptt_iters=TBPTT_BACKPROP_ITERS,
):
h_backbone, aux_loss, h_mid_out = self.forward_backbone(
input_ids,
n_shared_iters=n_shared_iters,
tbptt_iters=tbptt_iters,
)
if echo_batch_frac > 0.0:
if dds_depth is None:
dds_depth = ECHOCausalSelfRecursion.sample_dds_depth()
dds_depth = min(dds_depth, len(target_horizons) - 1)
b_echo = max(1, int(round(input_ids.size(0) * echo_batch_frac)))
h_echo_in = h_backbone[:b_echo]
future_embs = [
self.embed_tokens(target_horizons[k - 1][:b_echo])
for k in range(1, dds_depth + 1)
]
horizon_states = self.echo(self.coda[-1], h_echo_in, future_embs)
norm_fn = (
self._final_norm_compiled
if (self.training and self._final_norm_compiled is not None)
else self._apply_final_norm
)
rmid_loss = None
if self.ce_backend == "cut_cross_entropy" and dds_depth == 1:
parts_h = [h_backbone, horizon_states[0]]
parts_t = [target_horizons[0], target_horizons[1][:b_echo]]
if h_mid_out is not None:
parts_h.append(h_mid_out)
parts_t.append(target_horizons[0][: h_mid_out.size(0)])
h_norm = norm_fn(torch.cat(parts_h, dim=0))
t_cat = torch.cat(parts_t, dim=0)
losses = _cce_linear_cross_entropy(
h_norm.reshape(-1, D_VOCAB),
self.tok_emb.weight,
t_cat.reshape(-1),
reduction="none",
)
T_seq = h_backbone.size(1)
n_main = h_backbone.size(0) * T_seq
n_echo = horizon_states[0].size(0) * T_seq
lm_loss = losses[:n_main].mean()
echo_loss = losses[n_main : n_main + n_echo].mean()
if h_mid_out is not None:
rmid_loss = losses[n_main + n_echo :].mean()
else:
lm_loss = self.compute_lm_loss(h_backbone, target_horizons[0])
if dds_depth == 1:
echo_loss = self.compute_lm_loss(
horizon_states[0], target_horizons[1][:b_echo]
)
else:
echo_losses = [
self.compute_lm_loss(
horizon_states[k - 1], target_horizons[k][:b_echo]
)
for k in range(1, dds_depth + 1)
]
echo_loss = torch.stack(echo_losses).mean()
if h_mid_out is not None:
rmid_loss = self.compute_lm_loss(
h_mid_out, target_horizons[0][: h_mid_out.size(0)]
)
total_loss = lm_loss + ECHO_LOSS_COEFF * echo_loss + aux_loss
if rmid_loss is not None:
mono_hinge = F.relu(lm_loss - rmid_loss.detach() + 0.01)
total_loss = total_loss + RMID_LOSS_COEFF * rmid_loss + MONO_LOSS_COEFF * mono_hinge
echo_det = echo_loss.detach()
else:
lm_loss = self.compute_lm_loss(h_backbone, target_horizons[0])
total_loss = lm_loss + aux_loss
echo_det = None
return total_loss, {
"lm_loss": lm_loss.detach(),
"echo_loss": echo_det,
"aux_loss": aux_loss.detach(),
"total_loss": total_loss.detach(),
}
@torch.no_grad()
def generate(
self, prompt_ids, max_new_tokens=32, effort="medium", temperature=0.8, top_p=0.9
):
"""Eager autoregressive generation with configurable thinking effort
('low'=8, 'medium'=16, 'high'=24, 'xhigh'=32, 'max'=40 total loops).
"""
self.eval()
self.set_telemetry(False)
total_loops = (
EFFORT_TOTAL_LOOPS[effort] if isinstance(effort, str) else int(effort)
)
n_iters = max(1, (total_loops - N_PRELUDE - N_CODA) // N_SHARED_CELL_BLOCKS)
seq = prompt_ids.clone()
for _ in range(max_new_tokens):
ctx = seq[:, -SEQ_LEN:]
h_out, _, _ = self.forward_backbone(ctx, n_shared_iters=n_iters, tbptt_iters=None)
h_last = self._apply_final_norm(h_out[:, -1, :])
logits = F.linear(h_last, self.tok_emb.weight).float()
if temperature <= 0.0:
next_tok = logits.argmax(dim=-1, keepdim=True)
else:
probs = F.softmax(logits / temperature, dim=-1)
sorted_probs, sorted_idx = torch.sort(probs, descending=True)
cum_probs = torch.cumsum(sorted_probs, dim=-1)
mask = (cum_probs - sorted_probs) > top_p
sorted_probs[mask] = 0.0
sorted_probs.div_(sorted_probs.sum(dim=-1, keepdim=True))
sampled = torch.multinomial(sorted_probs, num_samples=1)
next_tok = torch.gather(sorted_idx, -1, sampled)
seq = torch.cat([seq, next_tok], dim=1)
return seq
@torch.no_grad()
def echo_speculative_draft_test(self, input_ids, draft_depth=2, effort="medium"):
self.eval()
self.set_telemetry(False)
total_loops = (
EFFORT_TOTAL_LOOPS[effort] if isinstance(effort, str) else int(effort)
)
n_iters = max(1, (total_loops - N_PRELUDE - N_CODA) // N_SHARED_CELL_BLOCKS)
h_backbone, _, _ = self.forward_backbone(
input_ids, n_shared_iters=n_iters, tbptt_iters=None
)
h_norm = self._apply_final_norm(h_backbone[:, -1:, :])
tok_k0 = F.linear(h_norm, self.tok_emb.weight).argmax(dim=-1)
drafted = [tok_k0]
x1, x2 = h_backbone.chunk(2, dim=-1)
cur_tok = tok_k0
shifted_ids = input_ids
for _ in range(draft_depth):
shifted_ids = torch.cat([shifted_ids[:, 1:], cur_tok], dim=1)
emb_step = self.embed_tokens(shifted_ids)
x1, x2 = self.echo.fuse_step(x1, x2, emb_step)
x1, x2, _ = self.coda[-1](x1, x2)
h_k = self._apply_final_norm(torch.cat([x1[:, -1:, :], x2[:, -1:, :]], dim=-1))
cur_tok = F.linear(h_k, self.tok_emb.weight).argmax(dim=-1)
drafted.append(cur_tok)
return torch.cat(drafted, dim=1)
# ======================== 8-BIT BLOCKWISE MUON + FUSED FP32 ADAMW OPTIMIZER
def _zeropower_polar_express_bf16(G, steps=MUON_NS_STEPS):
"""5-step Polar Express orthogonalization (arXiv:2505.16932v2): -57% BF16 spectral error."""
X = G.bfloat16()
transposed = G.size(0) > G.size(1)
if transposed:
X = X.T
X = X / (X.float().norm().mul(1.01).to(X.dtype) + 1e-7)
for a, b, c in POLAR_EXPRESS_SAFE[:steps]:
A = X @ X.T
B = b * A + c * (A @ A)
X = a * X + B @ X
return (X.T if transposed else X).float()
def _adamw_update_bf16_compiled(p, g, m, v, lr_t, wd, b1, b2, bc1_t, bc2_t):
"""Compiled zero-recompile BF16 AdamW (0-D tensor scalars -> 1 single Triton kernel!)."""
m.mul_(b1).add_(g, alpha=1.0 - b1)
v.mul_(b2).addcmul_(g, g, value=1.0 - b2)
p_fp32 = p.float() * (1.0 - lr_t * wd) - lr_t * (m / bc1_t) / ((v / bc2_t).sqrt() + 1e-8)
return stochastic_round_bf16(p_fp32)
class Muon8BitWithAdamW:
"""8-Bit Blockwise Muon (BF16 NS5) + Fused CUDA FP32 AdamW + Eager BF16 tok_emb AdamW."""
def __init__(
self,
model,
lr_muon=LR_CORE_MUON,
lr_adamw=LR_CORE_ADAMW,
momentum=0.95,
nesterov=True,
ns_steps=MUON_NS_STEPS,
block_size=MUON_BLOCK_PAPER,
betas=(0.9, 0.95),
weight_decay=WEIGHT_DECAY_CORE,
compile_kernels=USE_TORCH_COMPILE,
):
self.lr_muon = lr_muon
self.lr_adamw = lr_adamw
self.momentum = momentum
self.nesterov = nesterov
self.ns_steps = ns_steps
self.block_size = block_size
self.betas = betas
self.weight_decay = weight_decay
self.step_count = 0
self._ns5_fn = (
torch.compile(_zeropower_polar_express_bf16, mode="default", dynamic=True)
if (compile_kernels and hasattr(torch, "compile"))
else _zeropower_polar_express_bf16
)
self._adamw_bf16_fn = (
torch.compile(_adamw_update_bf16_compiled, mode="default")
if (compile_kernels and hasattr(torch, "compile"))
else _adamw_update_bf16_compiled
)
self.params_2d, self.params_1d = partition_muon_adamw_params(
model.named_parameters()
)
shared_ids = {id(p) for p in model.shared_core.parameters()}
echo_ids = {id(p) for p in model.echo.parameters()}
self.muon_state = {}
for p in self.params_2d:
n_el = p.numel()
n_blk = math.ceil(n_el / block_size)
self.muon_state[id(p)] = {
"q_mom": torch.zeros(n_el, device=p.device, dtype=torch.int8),
"scales": torch.zeros(n_blk, device=p.device, dtype=torch.float32),
"v_row": torch.zeros(p.size(0), device=p.device, dtype=torch.float32),
"lr_base": LR_SHARED_MUON if id(p) in shared_ids else lr_muon,
}
# Split FP32 AdamW: decayed 2D/3D, zero-WD 1D/gates/ZOH, and 2x-LR echo params
fp32_decay, fp32_nodecay, fp32_echo = [], [], []
self.params_1d_bf16 = []
for p in self.params_1d:
if p.dtype != torch.float32:
self.params_1d_bf16.append(p)
elif id(p) in echo_ids:
fp32_echo.append(p)
elif p.ndim >= 2:
fp32_decay.append(p)
else:
fp32_nodecay.append(p)
adamw_groups = []
if fp32_decay:
adamw_groups.append({"params": fp32_decay, "weight_decay": weight_decay, "lr_mult": 1.0})
if fp32_nodecay:
adamw_groups.append({"params": fp32_nodecay, "weight_decay": 0.0, "lr_mult": 1.0})
if fp32_echo:
adamw_groups.append({"params": fp32_echo, "weight_decay": 0.0, "lr_mult": 2.0})
self.adamw_fp32_opt = (
torch.optim.AdamW(
adamw_groups,
lr=lr_adamw,
betas=betas,
fused=torch.cuda.is_available(),
)
if adamw_groups
else None
)
self.adamw_bf16_state = {
id(p): {
"m": torch.zeros_like(p, dtype=torch.float32),
"v": torch.zeros_like(p, dtype=torch.float32),
}
for p in self.params_1d_bf16
}
@staticmethod
def quantize_int8_blockwise(x_flat, block_size):
n_el = x_flat.numel()
n_blk = math.ceil(n_el / block_size)
pad = n_blk * block_size - n_el
x_pad = F.pad(x_flat.float(), (0, pad)) if pad > 0 else x_flat.float()
blocks = x_pad.view(n_blk, block_size)
scales = blocks.abs().amax(dim=-1) / 127.0
q = torch.clamp(
torch.round(blocks / scales.clamp_min(1e-12).unsqueeze(-1)), -127, 127
).to(torch.int8)
return q.view(-1)[:n_el], scales
@staticmethod
def dequantize_int8_blockwise(q_flat, scales, block_size, shape):
n_el = q_flat.numel()
n_blk = scales.numel()
pad = n_blk * block_size - n_el
q_pad = F.pad(q_flat, (0, pad)) if pad > 0 else q_flat
x = q_pad.float().view(n_blk, block_size) * scales.unsqueeze(-1)
return x.view(-1)[:n_el].view(shape)
@torch.no_grad()
def step(self, lr_scale=1.0):
self.step_count += 1
lr_m = self.lr_muon * lr_scale
lr_a = self.lr_adamw * lr_scale
for p in self.params_2d:
if p.grad is None:
continue
g = p.grad.float()
st = self.muon_state[id(p)]
m = self.dequantize_int8_blockwise(
st["q_mom"], st["scales"], self.block_size, p.shape
)
m = self.momentum * m + g
st["q_mom"], st["scales"] = self.quantize_int8_blockwise(
m.reshape(-1), self.block_size
)
u_in = (g + self.momentum * m) if self.nesterov else m
lr_p = st["lr_base"] * lr_scale
ortho = self._ns5_fn(u_in, self.ns_steps)
v_row = st["v_row"]
v_row.mul_(0.95).add_(ortho.pow(2).mean(dim=-1), alpha=0.05)
v_hat = v_row / (1.0 - 0.95 ** self.step_count)
ortho = ortho / (v_hat.sqrt().unsqueeze(-1) + 1e-8)
rms_scale = (0.2 * math.sqrt(p.numel())) / ortho.norm().clamp_min(1e-8)
p_fp32 = p.float()
if self.weight_decay > 0.0:
p_fp32.sub_(p_fp32 * (ortho * p_fp32 >= 0.0).float(), alpha=lr_p * self.weight_decay)
p_fp32.add_(ortho * (-lr_p * rms_scale))
write_back_(p, p_fp32)
if self.adamw_fp32_opt is not None:
for pg in self.adamw_fp32_opt.param_groups:
pg["lr"] = lr_a * pg.get("lr_mult", 1.0)
self.adamw_fp32_opt.step()
b1, b2 = self.betas
bc1 = 1.0 - b1 ** self.step_count
bc2 = 1.0 - b2 ** self.step_count
for p in self.params_1d_bf16:
if p.grad is None:
continue
st = self.adamw_bf16_state[id(p)]
lr_t = torch.tensor(lr_a, device=p.device, dtype=torch.float32)
bc1_t = torch.tensor(bc1, device=p.device, dtype=torch.float32)
bc2_t = torch.tensor(bc2, device=p.device, dtype=torch.float32)
p.copy_(
self._adamw_bf16_fn(
p, p.grad.float(), st["m"], st["v"], lr_t, self.weight_decay, b1, b2, bc1_t, bc2_t
)
)
# =========================================== PRE-FLIGHT MATHEMATICAL CHECKS
def run_preflight_checks(device):
prev_tf32 = torch.backends.cuda.matmul.allow_tf32
torch.backends.cuda.matmul.allow_tf32 = False
try:
_preflight_checks(device)
finally:
torch.backends.cuda.matmul.allow_tf32 = prev_tf32
def _preflight_checks(device):
banner("STEP 1 - Pre-Flight Paper-Exact Mathematical & Kernel Verification")
# 1. Stable Symmetric GDN-2 (Block-Schur Inverse) Chunkwise WY vs. Recurrence
torch.manual_seed(42)
q = l2_norm(torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device))
k = l2_norm(torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device))
v = torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device)
g = -F.softplus(torch.randn(1, 64, N_HEADS, 1, device=device) - 1.5)
b = torch.sigmoid(torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device))
w = torch.sigmoid(torch.randn(1, 64, N_HEADS, HEAD_DIM, device=device))
o_rec, s_rec = GatedDeltaNet2.recurrent_scan(
q, k, v, g, b, w, stable_symmetric=True
)
o_wy, s_wy = GatedDeltaNet2.chunkwise_wy(
q, k, v, g, b, w, chunk_size=16, stable_symmetric=True, use_bf16_gram=False
)
err_sym_wy = max(
(o_rec - o_wy).abs().max().item(), (s_rec - s_wy).abs().max().item()
)
print(
f" [{'PASS' if err_sym_wy < 1e-5 else 'FAIL'}] Stable Symmetric GDN-2 (Block-Schur WY) == Recurrence "
f"(max|err| = {err_sym_wy:.3e} < 1e-5)"
)
assert err_sym_wy < 1e-5
# 2. Vectorized Banded-Diagonal Flash-HiSA vs. Reference Tile-by-Tile Flash-HiSA
swa = HiSASlidingWindowAttention(
use_reversible_mola=True, use_flex_attention=False
).to(device)
qr = torch.randn(1, N_HEADS, 256, HEAD_DIM, device=device)
kr = torch.randn(1, N_HEADS, 256, HEAD_DIM, device=device)
s_ref = swa._scores_block_reference(qr, kr)
s_fast = swa._scores_block_fast(qr, kr)
err_hisa = (s_ref - s_fast).abs().max().item()
print(
f" [{'PASS' if err_hisa < 1e-5 else 'FAIL'}] Banded-Diagonal Flash-HiSA (arXiv:2611.26363) == Reference Block Rule "
f"(max|err| = {err_hisa:.3e} < 1e-5)"
)
assert err_hisa < 1e-5
# 3. FLA Blackwell Determinism & Finiteness Check
if USE_FLA_GDN and _HAS_FLA and device.type == "cuda":
import fla
qf = F.normalize(torch.randn(4, 256, N_HEADS, HEAD_DIM, device=device, dtype=torch.bfloat16), dim=-1)
kf = F.normalize(torch.randn(4, 256, N_HEADS, HEAD_DIM, device=device, dtype=torch.bfloat16), dim=-1)
vf = torch.randn(4, 256, N_HEADS, HEAD_DIM, device=device, dtype=torch.bfloat16)
gf = -F.softplus(torch.randn(4, 256, N_HEADS, device=device, dtype=torch.float32) - 1.5)
bf = torch.sigmoid(torch.randn(4, 256, N_HEADS, device=device, dtype=torch.float32))
o1, _ = _fla_chunk_gdn(qf, kf, vf, g=gf, beta=bf, scale=1.0)
o2, _ = _fla_chunk_gdn(qf, kf, vf, g=gf, beta=bf, scale=1.0)
diff_det = ((o1 - o2).float().norm() / o1.float().norm().clamp_min(1e-12)).item()
is_fin = bool(torch.isfinite(o1).all().item())
fla_ver = getattr(fla, "__version__", "unknown")
print(
f" [{'PASS' if (diff_det < 1e-4 and is_fin) else 'FAIL'}] FLA ({fla_ver}) Blackwell Determinism "
f"(rel L2 diff = {diff_det:.3e}, finite = {is_fin})"
)
assert diff_det < 1e-4 and is_fin, "FLA Blackwell forward corruption detected! Upgrade flash-linear-attention>=0.6.0"
# =========================================================== MAIN TRAINING
def main():
rank, local_rank, world_size, device = init_distributed()
is_main = (rank == 0)
if is_main:
run_preflight_checks(device)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
if hasattr(torch, "_dynamo"):
torch._dynamo.config.cache_size_limit = 64
if is_main:
banner(
f"STEP 2 - Loading Hugging Face Tokenizer ({TOKENIZER_HF_REPO}) & Streaming Wikipedia "
f"(world_size={world_size}, A100 BF16 + {world_size}-Way Sharded Sparse)"
)
tokenizer = load_internet_tokenizer()
vocab_size = tokenizer.get_vocab_size()
n_tok, np_dtype, val_prompts = prepare_internet_wiki_memmap(
tokenizer,
vocab_size,
out_path=MEMMAP_BIN_PATH,
prompts_path=VAL_PROMPTS_JSON,
max_tokens=MEMMAP_MAX_TOKENS,
)
if dist_is_active():
dist.barrier()
if not is_main:
tokenizer = load_internet_tokenizer()
vocab_size = tokenizer.get_vocab_size()
n_tok, np_dtype, val_prompts = prepare_internet_wiki_memmap(
tokenizer,
vocab_size,
out_path=MEMMAP_BIN_PATH,
prompts_path=VAL_PROMPTS_JSON,
max_tokens=MEMMAP_MAX_TOKENS,
)
canonical_map, n_canonical, comp_ratio = build_engram_canonical_map(
tokenizer, vocab_size, device
)
if is_main:
print(
f" Raw Vocabulary Size : {vocab_size:,d} tokens -> "
f"Engram Canonical Vocab: {n_canonical:,d} tokens (-{100 * comp_ratio:.1f}% surface redundancy)"
)
extra_horizon = 4 if ECHO_FIXED_DEPTH is None else max(2, ECHO_FIXED_DEPTH + 1)
loader = FastMemmapLoader(
MEMMAP_BIN_PATH,
np_dtype,
seq_len=SEQ_LEN,
batch_size=BATCH_SIZE,
device=device,
extra_horizon=extra_horizon,
val_prompts=val_prompts,
seed=1234 + rank * 997,
)
if is_main:
print(
f" FastMemmapLoader active ({n_tok:,d} tokens, zero CPU tokenization, {world_size} rank(s)). "
f"Collected {len(loader.val_prompts)} Wikipedia test prompts."
)
try:
banner(
"STEP 3 - Instantiating Final Locked Architecture: Prelude(1)+SharedCore(2)+Coda(1) + Factorized LM(1024) + 11.50B GDDR7 (1.5B Engram + 10B UltraMemV2 topK=32)"
)
if torch.cuda.is_available():
free_b, total_b = torch.cuda.mem_get_info()
print(
f" GPU VRAM Before Init : {(total_b - free_b) / GiB:.2f} GiB used / {total_b / GiB:.2f} GiB total"
)
t_init0 = time.perf_counter()
torch.manual_seed(42) # identical dense init across all ranks
model = L2GDDR7HybridLanguageModel(vocab_size, canonical_map, device, rank=rank, world_size=world_size)
model = cast_model_preserve_fp32_1d(model, device)
if dist_is_active():
for p in model.parameters():
dist.broadcast(p.data, src=0)
for b in model.buffers():
dist.broadcast(b.data, src=0)
n_fp8_layers, n_nvfp4_layers, nvfp4_backend = enable_precision_recipes(model, device)
compiled_ok = model.compile_hot_paths(USE_TORCH_COMPILE and device.type == "cuda")
opt_dense = Muon8BitWithAdamW(
model, compile_kernels=USE_TORCH_COMPILE and device.type == "cuda"
)
if torch.cuda.is_available():
torch.cuda.synchronize()
t_init = time.perf_counter() - t_init0
prelude_params = sum(p.numel() for p in model.prelude.parameters())
shared_params = sum(p.numel() for p in model.shared_core.parameters())
coda_params = sum(p.numel() for p in model.coda.parameters())
core_params = prelude_params + shared_params + coda_params
router_echo_params = (
sum(p.numel() for p in model.engram.parameters())
+ sum(p.numel() for p in model.bridge.parameters())
+ sum(p.numel() for p in model.echo.parameters())
+ model.final_norm.numel()
)
vocab_params = model.tok_emb.weight.numel() + model.emb_up.weight.numel() + model.lm_down.weight.numel()
engram_sparse_params = model.engram.sparse_table.weight.numel()
ultramem_sparse_params = model.bridge.sparse_table.weight.numel()
total_sparse_params = engram_sparse_params + ultramem_sparse_params
total_params = (
core_params + router_echo_params + vocab_params + total_sparse_params
)
sparse_gddr7_bytes = (
model.engram.sparse_table.memory_bytes()
+ model.bridge.sparse_table.memory_bytes()
)
gdn_desc = (
"FLA Triton chunk_gated_delta_rule (in-kernel L2Norm/Gate/Beta)"
if (model.shared_core[0].gdn.use_fla and device.type == "cuda")
else f"Chunk-{GDN_CHUNK_SIZE} Block-Schur WY ({'Symmetric' if model.shared_core[0].gdn.stable_symmetric else 'Asymmetric'})"
)
print(f" Initialization time : {t_init:.2f} s")
print(f" Precision recipes : torchao FP8 = {n_fp8_layers} layers | NVFP4 = {n_nvfp4_layers} ({nvfp4_backend})")
print(f" torch.compile hot paths enabled : {compiled_ok} (core mode={CORE_COMPILE_MODE})")
l2_active_fp8_mib = (shared_params + router_echo_params) / MiB
l2_total_fp8_mib = (core_params + router_echo_params) / MiB
print(f" Depth schedule / TBPTT : Prelude({N_PRELUDE}) + {N_SHARED_CELL_BLOCKS}-Block Sequential SharedCell(Blk0=GDN2-16h+OrthoInj -> Blk1=SWA+MoLA-16h+UltraMemV2+PostCellNorm, DeepBucket mean={PLN_MAIN_MEAN_ITERS:.1f}->{PLN_ANNEAL_MEAN_ITERS:.1f} iters, TBPTT={TBPTT_BACKPROP_ITERS}) + Coda({N_CODA})")
print(f" L2 Cache Residency Estimate (128 MiB L2): Active Shared+Routers ~{l2_active_fp8_mib:.1f} MiB FP8 | All Dense ~{l2_total_fp8_mib:.1f} MiB FP8")
print(f" Layer-2 Engram async CUDA stream : {model._engram_stream is not None}")
print(f" Multi-hop UltraMemV2 MoD gate : top {100 * MEM_CAPACITY_FRAC:.1f}% tokens/block (EMA eval_thr)")
print(f" Cross-Entropy backend : {model.ce_backend} (sub={LIGER_SUB_BATCH_TOKENS}, ECHO {int(ECHO_BATCH_FRAC*100)}% batch/micro)")
if PREFER_CUT_CE and not _HAS_CUT_CE:
print(f" (Cut Cross-Entropy import note: {_CCE_IMPORT_ERR})")
print(f" GDN-2 kernel backend : {gdn_desc} | LocalMix=SWGDN2-G1 Intra-SWA(W={GDN_CONV_KERNEL}) | FlashQLA={_HAS_FLASH_QLA}")
print(f" Sparse Adam / QuACK kernels : {'1-Pass Triton Row-v' if (_HAS_TRITON and device.type == 'cuda') else 'PyTorch Row-v'} | QuACK-RMS={_HAS_QUACK_RMS}")
print(f" Custom Triton Kernels : UltraMemGatherReduce={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | TDQKR-TopK={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | OrthoInj-ZOH={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | SWGDN2-SWA={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | MoD-GateScatter={'ON' if (_HAS_TRITON and device.type == 'cuda') else 'Fallback'} | MoLA-CustomOp={'ON' if (_HAS_MOLA_CUSTOM_OP and _HAS_TRITON and device.type == 'cuda') else 'Fallback'} | CachedFP8Core={USE_CACHED_FP8_CORE}")
if USE_FLA_GDN and not _HAS_FLA:
print(f" (FLA import note: {_FLA_IMPORT_ERR})")
print(f" On-Chip L2 Prelude+Shared+Coda params : {core_params:,d} ({core_params / 1e6:.2f} M; shared block = {shared_params / 1e6:.2f} M)")
print(f" On-Chip L2 Routers + IVE + ECHO params : {router_echo_params:,d} ({router_echo_params / 1e6:.2f} M)")
print(f" Outer Tied Vocab Embeddings / LM Head : {vocab_params:,d} ({vocab_params / 1e6:.2f} M)")
print(f" Tier 1 GDDR7 Engram N-Gram Table : {engram_sparse_params:,d} ({engram_sparse_params / 1e9:.3f} B)")
print(f" Tier 2 GDDR7 UltraMemV2 TDQKR Table : {ultramem_sparse_params:,d} ({ultramem_sparse_params / 1e9:.3f} B)")
print(f" TOTAL MODEL PARAMETERS : {total_params:,d} ({total_params / 1e9:.3f} Billion)")
print(f" GDDR7 Sparse Tables + 8-Bit Lazy State : {sparse_gddr7_bytes / GiB:.2f} GiB")
if torch.cuda.is_available():
alloc_b = torch.cuda.memory_allocated()
print(f" Total GPU VRAM Allocated : {alloc_b / GiB:.2f} GiB")
# ======================================================= TRAINING LOOP
banner(
f"STEP 4 - End-to-End Pretraining on Wikipedia ({MAX_STEPS} Steps, "
f"{BATCH_SIZE * SEQ_LEN * GRAD_ACCUM_STEPS:,d} tok/step)"
)
header = (
f"{'Step':>4} | {'Lp':>2} | {'tok/s':>7} | {'TotLoss':>7} | {'LMLoss':>6} | {'PPL':>7} | "
f"{'ECHOLoss':>8} | {'AuxBal':>7} | {'gCore':>5} | {'gRtr':>5} | {'gSprs':>5} | "
f"{'EngGate':>7} | {'MemGt':>5} | {'MemEnt':>6} | {'ActSlots':>8} | {'BrgRMS':>6}"
)
print(header)
print("-" * len(header))
grad_accum_local = max(1, GRAD_ACCUM_STEPS // world_size)
model.train()
tokens_per_step = BATCH_SIZE * SEQ_LEN * grad_accum_local * world_size
history = []
depth_rng = np.random.default_rng(1337)
shared_core_params = list(model.shared_core.parameters())
other_dense_params = (
list(model.prelude.parameters())
+ list(model.coda.parameters())
+ list(model.engram.parameters())
+ list(model.bridge.parameters())
+ list(model.echo.parameters())
+ (list(model.loop_cond.parameters()) if model.loop_cond is not None else [])
+ (list(model.tala_base.parameters()) if model.tala_base is not None else [])
+ [model.tok_emb.weight, model.emb_up.weight, model.lm_down.weight, model.final_norm]
)
sparse_opt_stream = (
torch.cuda.Stream(device=device)
if (ENABLE_ASYNC_SPARSE_ADAM and torch.cuda.is_available() and device.type == "cuda")
else None
)
bwd_done_event = torch.cuda.Event() if sparse_opt_stream is not None else None
sparse_done_event = torch.cuda.Event() if sparse_opt_stream is not None else None
if torch.cuda.is_available():
torch.cuda.synchronize()
t_window = time.perf_counter()
steps_in_window = 0
warmup_steps = max(10, int(0.05 * MAX_STEPS))
cooldown_start = int(0.80 * MAX_STEPS)
for step in range(1, MAX_STEPS + 1):
log_this_step = (step == 1) or (step % LOG_EVERY == 0) or (step == MAX_STEPS)
model.zero_grad(set_to_none=True)
# WSD (1-sqrt) LR schedule synchronized with PLN depth annealing at 80%
in_cooldown = step > cooldown_start
if step <= warmup_steps:
lr_scale = step / float(warmup_steps)
elif not in_cooldown:
lr_scale = 1.0
else:
t_cd = (step - cooldown_start) / max(1, MAX_STEPS - cooldown_start)
lr_scale = 0.05 + 0.95 * (1.0 - math.sqrt(min(1.0, max(0.0, t_cd))))
accum_lm = torch.zeros((), device=device, dtype=torch.float32)
accum_echo = torch.zeros((), device=device, dtype=torch.float32)
accum_aux = torch.zeros((), device=device, dtype=torch.float32)
accum_tot = torch.zeros((), device=device, dtype=torch.float32)
echo_micro_count = 0
step_loops_sum = 0
step_tbptt, _, _, _ = get_progressive_depth_stage(step, MAX_STEPS)
for micro_idx in range(grad_accum_local):
# Synchronized per-microbatch depth sampling across all ranks (zero straggler skew!)
n_iters = sample_pln_shared_iters(step, MAX_STEPS, depth_rng)
step_loops_sum += N_PRELUDE + n_iters * N_SHARED_CELL_BLOCKS + N_CODA
model.set_telemetry(
log_this_step and (micro_idx == grad_accum_local - 1)
)
x_ids, target_horizons = loader.next_batch()
loss, m_dict = model.forward_train(
x_ids,
target_horizons,
n_shared_iters=n_iters,
dds_depth=ECHO_FIXED_DEPTH,
echo_batch_frac=ECHO_BATCH_FRAC,
tbptt_iters=step_tbptt,
)
(loss / grad_accum_local).backward()
if log_this_step:
accum_lm += m_dict["lm_loss"]
accum_aux += m_dict["aux_loss"]
accum_tot += m_dict["total_loss"]
if m_dict["echo_loss"] is not None:
accum_echo += m_dict["echo_loss"]
echo_micro_count += 1
total_loops_step = int(round(step_loops_sum / grad_accum_local))
# Overlap sparse_adam_step on secondary CUDA stream behind clip + opt_dense.step() (NorMuon)!
# Dense params and GDDR7 sparse tables are 100% disjoint; bwd_done/sparse_done events ensure order.
if sparse_opt_stream is not None:
bwd_done_event.record()
with torch.cuda.stream(sparse_opt_stream):
sparse_opt_stream.wait_event(bwd_done_event)
model.engram.sparse_table.sparse_adam_step(
lr=LR_CORE_ADAMW * LR_ENGRAM_MULT * lr_scale,
collect_telemetry=log_this_step,
defer_telemetry=True,
)
model.bridge.sparse_table.sparse_adam_step(
lr=LR_CORE_ADAMW * LR_ULTRAMEM_MULT * lr_scale,
collect_telemetry=log_this_step,
defer_telemetry=True,
)
sparse_done_event.record(sparse_opt_stream)
# Hybrid DDP AllReduce over ~170M dense params (overlapped with sharded sparse_opt_stream!)
if dist_is_active():
for p in model.parameters():
if p.grad is not None:
dist.all_reduce(p.grad, op=dist.ReduceOp.AVG)
# Decoupled grad clipping: shared_core (TBPTT multi-visit) vs prelude/coda/routers
gnorm_core_t = torch.nn.utils.clip_grad_norm_(
shared_core_params, MAX_GRAD_NORM
)
gnorm_router_t = torch.nn.utils.clip_grad_norm_(
other_dense_params, MAX_GRAD_NORM
)
opt_dense.step(lr_scale=lr_scale)
if USE_CACHED_FP8_CORE:
invalidate_all_fp8_caches(model)
# LR-coupled DeepSeek-V3 bias update (only freeze final 2% so MemEnt stays >0.98 in cooldown!)
bias_gamma = (
0.0
if step > int(0.98 * MAX_STEPS)
else ULTRAMEM_BIAS_GAMMA * max(0.50, lr_scale)
)
model.bridge.update_routing_bias_and_ema(
gamma=bias_gamma,
collect_telemetry=log_this_step,
)
if sparse_opt_stream is not None:
torch.cuda.current_stream().wait_event(sparse_done_event)
else:
model.engram.sparse_table.sparse_adam_step(
lr=LR_CORE_ADAMW * LR_ENGRAM_MULT * lr_scale,
collect_telemetry=log_this_step,
)
model.bridge.sparse_table.sparse_adam_step(
lr=LR_CORE_ADAMW * LR_ULTRAMEM_MULT * lr_scale,
collect_telemetry=log_this_step,
)
steps_in_window += 1
if log_this_step:
if torch.cuda.is_available():
torch.cuda.synchronize()
model.engram.sparse_table.finalize_telemetry()
model.bridge.sparse_table.finalize_telemetry()
dt_window = max(time.perf_counter() - t_window, 1e-6)
tok_per_sec = (tokens_per_step * steps_in_window) / dt_window
t_window = time.perf_counter()
steps_in_window = 0
inv_accum = 1.0 / grad_accum_local
lm_l = float((accum_lm * inv_accum).item())
echo_l = float((accum_echo / max(1, echo_micro_count)).item())
aux_l = float((accum_aux * inv_accum).item())
tot_l = float((accum_tot * inv_accum).item())
ppl = math.exp(min(lm_l, 15.0))
gnorm_core = float(gnorm_core_t.item())
gnorm_router = float(gnorm_router_t.item())
gnorm_sparse = math.hypot(
model.engram.sparse_table.last_grad_norm,
model.bridge.sparse_table.last_grad_norm,
)
eng_gate = model.engram.last_gate_mean
mem_gt = model.shared_core[-1].last_mem_gate_mean
mem_ent = model.bridge.last_entropy_norm
act_slots = (
model.engram.sparse_table.last_unique_count
+ model.bridge.sparse_table.last_unique_count
)
brg_rms = model.bridge.last_bridge_rms_ratio
rec = {
"step": step,
"loops": total_loops_step,
"tok_s": tok_per_sec,
"tot_loss": tot_l,
"lm_loss": lm_l,
"ppl": ppl,
"echo_loss": echo_l,
"aux_loss": aux_l,
"gnorm_core": gnorm_core,
"gnorm_router": gnorm_router,
"gnorm_sparse": gnorm_sparse,
"eng_gate": eng_gate,
"mem_gt": mem_gt,
"mem_ent": mem_ent,
"act_slots": act_slots,
"brg_rms": brg_rms,
}
history.append(rec)
if is_main:
print(
f"{step:4d} | {total_loops_step:2d} | {tok_per_sec:7.0f} | {tot_l:7.3f} | "
f"{lm_l:6.3f} | {ppl:7.1f} | {echo_l:8.3f} | {aux_l:7.4f} | "
f"{gnorm_core:5.2f} | {gnorm_router:5.2f} | {gnorm_sparse:5.2f} | "
f"{eng_gate:7.3f} | {mem_gt:5.3f} | {mem_ent:6.3f} | {act_slots * world_size:8,d} | {brg_rms:6.3f}"
)
# ============================================= TELEMETRY HEALTH SUMMARY
banner("STEP 5 - Training & Sparse Memory Block Health Summary")
steady_records = history[1:] if len(history) > 1 else history
steady_tok_s = sum(r["tok_s"] for r in steady_records) / max(1, len(steady_records))
eng_visited = int(model.engram.sparse_table.visited_mask.sum().item())
ult_visited = int(model.bridge.sparse_table.visited_mask.sum().item())
print(f" Sustained Training Throughput : {steady_tok_s:,.0f} tok/s")
print(f" Initial -> Final Main LM Loss (PPL) : {history[0]['lm_loss']:.3f} ({history[0]['ppl']:.1f}) -> {history[-1]['lm_loss']:.3f} ({history[-1]['ppl']:.1f})")
print(f" Initial -> Final ECHO Horizon Loss : {history[0]['echo_loss']:.3f} -> {history[-1]['echo_loss']:.3f}")
print(f" Layer-2 Engram Collision Gate : mean = {model.engram.last_gate_mean:.3f} +/- {model.engram.last_gate_std:.3f}")
print(f" Shared Core Multi-Hop MemGate Mean : {model.shared_core[-1].last_mem_gate_mean:.3f} (Block-1 only, train cap = {100 * MEM_CAPACITY_FRAC:.1f}%, eval_thr = {[round(b.eval_thr.item(), 3) for b in model.shared_core if b.use_gated_mem]})")
print(f" UltraMemV2 TDQKR Routing Entropy : {model.bridge.last_entropy_norm:.4f} (1.000 = ideal uniform slot usage)")
print(f" UltraMemV2 Max Marginal Key Load Ratio : {model.bridge.last_max_load_ratio:.2f}x uniform")
print(f" Unique GDDR7 Slots Written During Run : Engram = {eng_visited:,d} | UltraMemV2 = {ult_visited:,d} | Total = {eng_visited + ult_visited:,d}")
if model.bridge.sparse_table.use_fp8:
print(
f" FP8 Sparse Tables (per-row w_scale+SR) : ACTIVE | Dead% (w_scale<1e-4): "
f"Engram={100.0 * model.engram.sparse_table.last_dead_slot_frac:.2f}% | "
f"UltraMemV2={100.0 * model.bridge.sparse_table.last_dead_slot_frac:.2f}%"
)
print(
f" Speedup Stack & Loop Conditioning : ProgDepth={ENABLE_PROGRESSIVE_DEPTH} | "
f"AsyncSparseAdam={ENABLE_ASYNC_SPARSE_ADAM} | ContinuousLoopCond={ENABLE_CONTINUOUS_LOOP_COND}"
)
lam_mean = float(torch.exp(-F.softplus(model.shared_core[0].zoh_log_decay_1.float())).mean().item())
print(f" Knowledge Bridge RMS Modulation Ratio : {model.bridge.last_bridge_rms_ratio:.4f} (bridge scale = {model.bridge.bridge_scale.item():.4f})")
print(f" Shared Core ZOH Carryover Lambda Mean : {lam_mean:.4f} (healthy range ~0.88 - 0.97)")
# ============================================ POST-TRAINING INFERENCE
banner("STEP 6 - Configurable Thinking Effort (8 / 16 / 24 / 32 / 40 Loops) & ECHO Tests")
if hasattr(loader, "data") and len(loader.data) >= 32 * (SEQ_LEN + 1):
model.eval()
model.set_telemetry(False)
val_arr = (
torch.from_numpy(loader.data[-32 * (SEQ_LEN + 1) :].astype(np.int64))
.view(32, SEQ_LEN + 1)
.to(device)
)
val_x, val_y = val_arr[:, :SEQ_LEN], val_arr[:, 1:]
print(f" Fixed Held-Out Validation PPL by Thinking Effort (eval_thr = {[round(b.eval_thr.item(), 3) for b in model.shared_core if b.use_gated_mem]}):")
with torch.no_grad():
for eff_name, tot_l in EFFORT_TOTAL_LOOPS.items():
n_it = max(1, (tot_l - N_PRELUDE - N_CODA) // N_SHARED_CELL_BLOCKS)
h_v, _, _ = model.forward_backbone(val_x, n_shared_iters=n_it, tbptt_iters=None)
v_loss = model.compute_lm_loss(h_v, val_y).item()
if is_main:
print(
f" {eff_name:>6} ({tot_l:2d} loops) -> Val Loss = {v_loss:.4f} | Val PPL = {math.exp(min(v_loss, 15.0)):7.2f} | StepRMS = {model.last_eval_step_rms:.4f}"
)
test_prompts = (
loader.val_prompts[:3]
if loader.val_prompts
else [
"The history of artificial intelligence began in",
"In physics and mathematics, the theory of",
"Wikipedia is a free online encyclopedia created and edited by",
]
)
for idx, prompt_str in enumerate(test_prompts, 1):
enc = tokenizer.encode(prompt_str)
p_ids = torch.tensor([enc.ids[:32]], dtype=torch.long, device=device)
t_g0 = time.perf_counter()
out_low = model.generate(p_ids, max_new_tokens=24, effort="low", temperature=0.7, top_p=0.9)
dt_low = time.perf_counter() - t_g0
out_med = model.generate(p_ids, max_new_tokens=24, effort="medium", temperature=0.7, top_p=0.9)
out_high = model.generate(p_ids, max_new_tokens=24, effort="high", temperature=0.7, top_p=0.9)
draft_tokens = model.echo_speculative_draft_test(p_ids, draft_depth=2, effort="medium")
draft_str = tokenizer.decode(draft_tokens[0].tolist())
if is_main:
print(f"\n [Prompt {idx}] {prompt_str!r}")
print(f" -> Low Effort (8 loops, {24 / dt_low:.1f} tok/s) : {tokenizer.decode(out_low[0].tolist())!r}")
print(f" -> Med Effort (16 loops) : {tokenizer.decode(out_med[0].tolist())!r}")
print(f" -> High Effort (24 loops) : {tokenizer.decode(out_high[0].tolist())!r}")
print(f" -> ECHO 3-Token Speculative Step : tokenIds={draft_tokens[0].tolist()} decoded={draft_str!r}")
finally:
loader.close()
if dist_is_active():
dist.destroy_process_group()
if __name__ == "__main__":
main() |