File size: 120,212 Bytes
643267a | 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 | """PAT fused attention. Only the publication training/prefill path is retained.
FP32 relative rotary products, query-owned backward, and Hopper ragged TMA
accumulation preserve the checkpoint producer's arithmetic.
"""
from __future__ import annotations
from .layout import PackedLayout
ROPE_BASE = 10_000.0
import math
from collections import OrderedDict
from collections.abc import Sequence
from dataclasses import dataclass
from threading import Lock
from typing import Any
import torch
try:
import triton
import triton.language as tl
from triton.tools.ragged_tma import atomic_add_ragged, create_ragged_descriptor
_HAS_TRITON = True
except ImportError:
triton = None
tl = None
_HAS_TRITON = False
_SUPPORTED_CHUNK_SIZES = frozenset({16, 32})
_SUPPORTED_DTYPES = frozenset({torch.float16, torch.bfloat16, torch.float32})
_PAT_MEMORY_BLOCK_Q = 64
_PAT_MEMORY_BACKWARD_BLOCK_K = 64
_PAT_MEMORY_FORWARD_WARPS = 4
_PAT_MEMORY_BACKWARD_WARPS = 4
_PAT_TOKEN_BACKWARD_WARPS = 4
_PAT_PLAN_CACHE_MAX_ENTRIES = 32
_PAT_PHASE_CACHE_MAX_ENTRIES = _PAT_PLAN_CACHE_MAX_ENTRIES
_PAT_PHASE_CACHE: OrderedDict[
tuple[KernelConfig, torch.device, torch.dtype, int, int], tuple[torch.Tensor, torch.Tensor]
] = OrderedDict()
_PAT_PHASE_CACHE_LOCK = Lock()
_PAT_FIXED_ROW_CACHE_MAX_ENTRIES = _PAT_PLAN_CACHE_MAX_ENTRIES
_PAT_FIXED_ROW_CACHE: OrderedDict[tuple[tuple[Any, ...], torch.device, int], torch.Tensor] = (
OrderedDict()
)
_PAT_FIXED_ROW_CACHE_LOCK = Lock()
_PAT_TRUSTED_MATERIALIZER = object()
def _memory_query_block_k(configured_block_k: int) -> int:
"""Bound the five-product query owner while respecting smaller K tiles."""
return min(_PAT_MEMORY_BACKWARD_BLOCK_K, int(configured_block_k))
def _power_of_two(name: str, value: int) -> int:
value_i = int(value)
if value_i <= 0 or value_i & value_i - 1:
raise ValueError(f"{name} must be a positive power of two; got {value!r}")
return value_i
def _block_d(head_dim: int) -> int:
return max(16, 1 << max(0, int(head_dim) - 1).bit_length())
def _validate_pat_head_dim(head_dim: int) -> int:
"""Validate the one ragged-TMA backward geometry before any launch."""
value = int(head_dim)
block_dimension = _block_d(value)
if value < 20 or value % 4 or block_dimension > 128:
raise ValueError(
f"PAT ragged-TMA backward requires head_dim divisible by 4 in [20, 128]; got {value}"
)
return block_dimension
def _require_pat_hopper(device: torch.device) -> None:
"""Require the descriptor atomics used by the publication kernel."""
capability = torch.cuda.get_device_capability(device)
if int(capability[0]) < 9:
raise RuntimeError(
f"production attention PAT requires an SM90-or-newer CUDA GPU for ragged TMA descriptor atomics; got compute capability {capability[0]}.{capability[1]}"
)
@dataclass(frozen=True)
class KernelConfig:
"""Fixed publication tile geometry and runtime context capacity."""
chunk_size: int
max_memory_size: int
block_q: int = 16
block_k_memory: int = 64
block_k_token: int = 16
warps: int = 4
stages: int = 3
def __post_init__(self) -> None:
if int(self.chunk_size) not in _SUPPORTED_CHUNK_SIZES:
raise ValueError(
f"production attention PAT supports chunk_size 16 or 32; got {self.chunk_size!r}"
)
if isinstance(self.max_memory_size, bool) or int(self.max_memory_size) < 4:
raise ValueError(
f"production attention PAT requires max_memory_size >= 4; got {self.max_memory_size!r}"
)
_power_of_two("block_q", self.block_q)
_power_of_two("block_k_memory", self.block_k_memory)
_power_of_two("block_k_token", self.block_k_token)
for name, value in (
("block_q", self.block_q),
("block_k_memory", self.block_k_memory),
("block_k_token", self.block_k_token),
):
if int(value) < 16 or int(value) > 128:
raise ValueError(
f"{name} must be a tensor-core tile size in [16, 128]; got {value!r}"
)
if int(self.warps) not in {2, 4, 8}:
raise ValueError(f"warps must be 2, 4, or 8; got {self.warps!r}")
if int(self.stages) not in {1, 2, 3, 4, 5}:
raise ValueError(f"stages must be in [1, 5]; got {self.stages!r}")
@dataclass(frozen=True)
class _PATMaterializedLayout:
"""One per-batch PAT layout and its canonical token-storage maps."""
layout: PackedLayout
canonical_order: torch.Tensor
logical_order: torch.Tensor
canonical_positions: torch.Tensor
canonical_key_positions: torch.Tensor
q_tile_rows: torch.Tensor
q_tile_starts: torch.Tensor
token_row_ids: torch.Tensor
memory_tile_union_start: torch.Tensor
memory_tile_union_end: torch.Tensor
memory_tile_interior_start: torch.Tensor
memory_tile_interior_end: torch.Tensor
token_owner_rows: torch.Tensor
token_owner_starts: torch.Tensor
block_q: int
block_k_memory: int
block_k_token: int
total_lexical_tokens: int
global_slots: int
storage: torch.Tensor
provenance: _PATMaterializationProvenance | None
@dataclass(frozen=True)
class _PATMaterializationProvenance:
"""Unforgeable batch-lifetime marker for the internal fused materializer."""
storage_identity: int
device: torch.device
stream: int
@dataclass(frozen=True)
class FixedGeometry:
"""Authoritative fixed-packer inputs consumed by the private materializer."""
row_offsets: torch.Tensor
row_lengths: torch.Tensor
row_content_lengths: torch.Tensor
chunk_piece_id: torch.Tensor
piece_chunk_base: torch.Tensor
eoc_abs_idx: torch.Tensor
token_count: int
max_row_length: int
max_chunk_index: int
planner_cache_key: tuple[Any, ...]
@property
def row_count(self) -> int:
return int(self.row_lengths.numel())
@property
def memory_tail_slots(self) -> int:
return int(self.eoc_abs_idx.size(1))
@dataclass(frozen=True)
class PATPlan:
"""O(tile) immutable launch metadata built once with the packed layout."""
config: KernelConfig
row_count: int
token_slots: int
total_lexical_tokens: int
local_tail_slots: int
memory_slots: int
global_slots: int
heads: int
head_dim: int
dtype: torch.dtype
row_offsets: torch.Tensor
row_pos_to_flat: torch.Tensor
row_lengths: torch.Tensor
row_chunk_indices: torch.Tensor
memory_query_start: torch.Tensor
row_memory_start_abs: torch.Tensor
row_memory_length: torch.Tensor
row_token_memory_length: torch.Tensor
row_exact_start_abs: torch.Tensor
row_exact_length: torch.Tensor
row_exact_query_phase_delta: torch.Tensor
row_compressed_eoc_local_key_phase_delta: torch.Tensor
q_tile_rows: torch.Tensor
q_tile_starts: torch.Tensor
token_row_ids: torch.Tensor
canonical_order: torch.Tensor
logical_order: torch.Tensor
memory_tile_union_start: torch.Tensor
memory_tile_union_end: torch.Tensor
memory_tile_interior_start: torch.Tensor
memory_tile_interior_end: torch.Tensor
token_owner_rows: torch.Tensor
token_owner_starts: torch.Tensor
memory_phase_cos: torch.Tensor
memory_phase_sin: torch.Tensor
metadata_signature: tuple[tuple[Any, ...], ...]
canonical_metadata: torch.Tensor
metadata_validation_result: torch.Tensor
metadata_validation_stream: int | None
_trusted_materialization: _PATMaterializationProvenance | None = None
@property
def query_tiles(self) -> int:
return int(self.q_tile_rows.numel())
@property
def token_tiles(self) -> int:
return int(self.token_owner_rows.numel())
@property
def memory_query_tiles(self) -> int:
return int(self.memory_tile_union_start.numel())
@property
def metadata(self) -> tuple[torch.Tensor, ...]:
return (
self.row_offsets,
self.row_pos_to_flat,
self.row_lengths,
self.row_chunk_indices,
self.memory_query_start,
self.row_memory_start_abs,
self.row_memory_length,
self.row_token_memory_length,
self.row_exact_start_abs,
self.row_exact_length,
self.row_exact_query_phase_delta,
self.row_compressed_eoc_local_key_phase_delta,
)
@property
def bound_metadata(self) -> tuple[torch.Tensor, ...]:
"""All mutable tensors whose exact identity/version binds this plan."""
return (*self.metadata, self.canonical_order, self.logical_order)
if _HAS_TRITON:
@triton.jit(
do_not_specialize=(
"rows",
"physical_tokens",
"target_tokens",
"total_lexical_tokens",
"q_tile_capacity",
"token_tile_capacity",
"memory_tile_count",
"pieces",
),
do_not_specialize_on_alignment=(
"rows",
"physical_tokens",
"target_tokens",
"total_lexical_tokens",
"q_tile_capacity",
"token_tile_capacity",
"memory_tile_count",
"pieces",
),
)
def _pat_materialize_layout_kernel(
physical_row_offsets_ptr,
physical_row_pos_to_flat_ptr,
physical_row_lengths_ptr,
physical_memory_query_start_ptr,
physical_memory_start_ptr,
physical_memory_length_ptr,
physical_eoc_ptr,
row_chunk_indices_ptr,
piece_chunk_base_ptr,
expected_row_geometry_ptr,
storage_ptr,
rows,
physical_tokens,
target_tokens,
total_lexical_tokens,
q_tile_capacity,
token_tile_capacity,
memory_tile_count,
pieces,
PHYSICAL_SLOTS: tl.constexpr,
LOCAL_SLOTS: tl.constexpr,
GLOBAL_SLOTS: tl.constexpr,
CHUNK_SIZE: tl.constexpr,
MAX_MEMORY_SIZE: tl.constexpr,
BLOCK_Q: tl.constexpr,
BLOCK_K_MEMORY: tl.constexpr,
BLOCK_K_TOKEN: tl.constexpr,
BLOCK_MEMORY_QUERY: tl.constexpr,
BLOCK_ROW: tl.constexpr,
TRUSTED_FIXED: tl.constexpr,
):
"""Materialize one exact PAT signature without scans or gathers."""
row = tl.program_id(0)
position = tl.arange(0, BLOCK_ROW)
row_mask = row < rows
physical_offset = tl.load(physical_row_offsets_ptr + row, mask=row_mask, other=0).to(
tl.int64
)
physical_length = tl.load(physical_row_lengths_ptr + row, mask=row_mask, other=0).to(
tl.int64
)
lexical_length = physical_length - PHYSICAL_SLOTS
target_offset = physical_offset + row * (LOCAL_SLOTS - PHYSICAL_SLOTS)
target_length = lexical_length + LOCAL_SLOTS
if TRUSTED_FIXED:
piece_id = tl.load(row_chunk_indices_ptr + row, mask=row_mask, other=-1).to(tl.int64)
piece_valid = row_mask & (piece_id >= 0) & (piece_id < pieces)
safe_piece_id = tl.maximum(0, tl.minimum(piece_id, pieces - 1))
piece_base = tl.load(
piece_chunk_base_ptr + safe_piece_id, mask=piece_valid, other=rows + 1
).to(tl.int64)
chunk_index = row - piece_base
else:
piece_valid = row_mask
chunk_index = tl.load(row_chunk_indices_ptr + row, mask=row_mask, other=-1).to(tl.int64)
expected_lexical_length = tl.load(
expected_row_geometry_ptr + row, mask=row_mask, other=-1
).to(tl.int64)
expected_chunk_index = tl.load(
expected_row_geometry_ptr + rows + row, mask=row_mask, other=-1
).to(tl.int64)
memory_query_start = tl.load(
physical_memory_query_start_ptr + row, mask=row_mask, other=-1
).to(tl.int64)
if TRUSTED_FIXED:
physical_memory_start = 0
physical_memory_length = 0
else:
physical_memory_start = tl.load(
physical_memory_start_ptr + row, mask=row_mask, other=-1
).to(tl.int64)
physical_memory_length = tl.load(
physical_memory_length_ptr + row, mask=row_mask, other=-1
).to(tl.int64)
previous_row = tl.maximum(row - 1, 0)
previous_offset = tl.load(
physical_row_offsets_ptr + previous_row, mask=row_mask, other=0
).to(tl.int64)
previous_length = tl.load(
physical_row_lengths_ptr + previous_row, mask=row_mask, other=0
).to(tl.int64)
if TRUSTED_FIXED:
previous_chunk = tl.load(
expected_row_geometry_ptr + rows + previous_row, mask=row_mask, other=0
).to(tl.int64)
else:
previous_chunk = tl.load(
row_chunk_indices_ptr + previous_row, mask=row_mask, other=0
).to(tl.int64)
expected_physical_offset = tl.where(row == 0, 0, previous_offset + previous_length)
previous_target_offset = tl.where(
row == 0, 0, previous_offset + previous_row * (LOCAL_SLOTS - PHYSICAL_SLOTS)
)
visible_memory_chunks = tl.minimum(chunk_index, MAX_MEMORY_SIZE - 1)
expected_memory_start = (row - visible_memory_chunks) * PHYSICAL_SLOTS
expected_memory_length = visible_memory_chunks * PHYSICAL_SLOTS
if TRUSTED_FIXED:
physical_memory_start = expected_memory_start
physical_memory_length = expected_memory_length
row_valid = (
row_mask
& piece_valid
& (physical_offset == expected_physical_offset)
& (physical_offset >= 0)
& (physical_offset + physical_length <= physical_tokens)
& (lexical_length > 0)
& (lexical_length <= CHUNK_SIZE)
& (lexical_length == expected_lexical_length)
& (memory_query_start == lexical_length)
& (chunk_index >= 0)
& (chunk_index == expected_chunk_index)
& ((row == 0) | (chunk_index == 0) | (chunk_index == previous_chunk + 1))
& (physical_memory_start >= 0)
& (physical_memory_length >= 0)
& (physical_memory_start % PHYSICAL_SLOTS == 0)
& (physical_memory_length % PHYSICAL_SLOTS == 0)
& (physical_memory_start + physical_memory_length <= rows * PHYSICAL_SLOTS)
& (physical_memory_start == expected_memory_start)
& (physical_memory_length == expected_memory_length)
& (target_offset >= 0)
& (target_offset + target_length <= target_tokens)
)
if TRUSTED_FIXED:
identity_invalid = position < 0
else:
physical_position_mask = row_mask & (position < physical_length)
physical_flat = physical_offset + position
physical_flat_in_bounds = (
physical_position_mask & (physical_flat >= 0) & (physical_flat < physical_tokens)
)
identity_value = tl.load(
physical_row_pos_to_flat_ptr + physical_flat, mask=physical_flat_in_bounds, other=-1
).to(tl.int64)
identity_invalid = physical_position_mask & (
~physical_flat_in_bounds | (identity_value != physical_flat)
)
physical_tail_mask = row_mask & (position < PHYSICAL_SLOTS)
physical_eoc = tl.load(
physical_eoc_ptr + row * PHYSICAL_SLOTS + position, mask=physical_tail_mask, other=-1
).to(tl.int64)
eoc_invalid = physical_tail_mask & (
physical_eoc != physical_offset + lexical_length + position
)
row_valid &= (tl.sum(identity_invalid.to(tl.int32), axis=0) == 0) & (
tl.sum(eoc_invalid.to(tl.int32), axis=0) == 0
)
row_offsets_base = 0
row_pos_to_flat_base = row_offsets_base + rows
row_lengths_base = row_pos_to_flat_base + target_tokens
row_chunk_indices_base = row_lengths_base + rows
memory_query_start_base = row_chunk_indices_base + rows
row_memory_start_base = memory_query_start_base + rows
row_memory_length_base = row_memory_start_base + rows
local_positions_base = row_memory_length_base + rows
query_positions_base = local_positions_base + target_tokens
eoc_base = query_positions_base + target_tokens
memory_positions_base = eoc_base + rows * LOCAL_SLOTS
row_token_memory_length_base = memory_positions_base + rows * GLOBAL_SLOTS
row_exact_start_base = row_token_memory_length_base + rows
row_exact_length_base = row_exact_start_base + rows
row_exact_delta_base = row_exact_length_base + rows
row_compressed_delta_base = row_exact_delta_base + rows
canonical_order_base = row_compressed_delta_base + rows
logical_order_base = canonical_order_base + target_tokens
canonical_positions_base = logical_order_base + target_tokens
canonical_key_positions_base = canonical_positions_base + target_tokens
token_row_ids_base = canonical_key_positions_base + target_tokens
q_tile_rows_base = token_row_ids_base + target_tokens
q_tile_starts_base = q_tile_rows_base + q_tile_capacity
token_owner_rows_base = q_tile_starts_base + q_tile_capacity
token_owner_starts_base = token_owner_rows_base + token_tile_capacity
memory_union_start_base = token_owner_starts_base + token_tile_capacity
memory_union_end_base = memory_union_start_base + memory_tile_count
memory_interior_start_base = memory_union_end_base + memory_tile_count
memory_interior_end_base = memory_interior_start_base + memory_tile_count
q_tile_counter_base = memory_interior_end_base + memory_tile_count
token_owner_counter_base = q_tile_counter_base + 1
validation_result_base = token_owner_counter_base + 1
invalid_value = -1
tl.store(
storage_ptr + row_offsets_base + row,
tl.where(row_valid, target_offset, invalid_value),
mask=row_mask,
)
tl.store(
storage_ptr + row_lengths_base + row,
tl.where(row_valid, target_length, invalid_value),
mask=row_mask,
)
tl.store(
storage_ptr + row_chunk_indices_base + row,
tl.where(row_valid, chunk_index, invalid_value),
mask=row_mask,
)
tl.store(
storage_ptr + memory_query_start_base + row,
tl.where(row_valid, lexical_length, invalid_value),
mask=row_mask,
)
scaled_memory_start = physical_memory_start // PHYSICAL_SLOTS * GLOBAL_SLOTS
scaled_memory_length = physical_memory_length // PHYSICAL_SLOTS * GLOBAL_SLOTS
tl.store(
storage_ptr + row_memory_start_base + row,
tl.where(row_valid, scaled_memory_start, invalid_value),
mask=row_mask,
)
tl.store(
storage_ptr + row_memory_length_base + row,
tl.where(row_valid, scaled_memory_length, invalid_value),
mask=row_mask,
)
tl.store(
storage_ptr + row_token_memory_length_base + row,
tl.where(row_valid, scaled_memory_length, invalid_value),
mask=row_mask,
)
tl.store(
storage_ptr + row_exact_start_base + row,
tl.where(row_valid, previous_target_offset, invalid_value),
mask=row_mask,
)
previous_exact_chunks = tl.minimum(chunk_index, 1)
exact_length = previous_exact_chunks * CHUNK_SIZE
exact_delta = tl.where(chunk_index == 0, 0, tl.where(chunk_index == 1, 1, CHUNK_SIZE))
tl.store(
storage_ptr + row_exact_length_base + row,
tl.where(row_valid, exact_length, invalid_value),
mask=row_mask,
)
tl.store(
storage_ptr + row_exact_delta_base + row,
tl.where(row_valid, exact_delta, invalid_value),
mask=row_mask,
)
tl.store(
storage_ptr + row_compressed_delta_base + row,
tl.where(row_valid, 0, invalid_value),
mask=row_mask,
)
target_position_mask = row_valid & (position < target_length)
logical_index = target_offset + position
local_base = chunk_index - previous_exact_chunks + previous_exact_chunks * CHUNK_SIZE
query_position = local_base + position
local_position = tl.where(
position >= lexical_length, local_base + lexical_length, query_position
)
lexical_index = physical_offset - row * PHYSICAL_SLOTS + position
canonical_index = tl.where(
position < lexical_length,
lexical_index,
total_lexical_tokens + row * LOCAL_SLOTS + position - lexical_length,
)
tl.store(
storage_ptr + row_pos_to_flat_base + logical_index,
logical_index,
mask=target_position_mask,
)
tl.store(
storage_ptr + local_positions_base + logical_index,
local_position,
mask=target_position_mask,
)
tl.store(
storage_ptr + query_positions_base + logical_index,
query_position,
mask=target_position_mask,
)
tl.store(
storage_ptr + canonical_order_base + canonical_index,
logical_index,
mask=target_position_mask,
)
tl.store(
storage_ptr + logical_order_base + logical_index,
canonical_index,
mask=target_position_mask,
)
tl.store(
storage_ptr + canonical_positions_base + canonical_index,
query_position,
mask=target_position_mask,
)
tl.store(
storage_ptr + canonical_key_positions_base + canonical_index,
local_position,
mask=target_position_mask,
)
tl.store(storage_ptr + token_row_ids_base + canonical_index, row, mask=target_position_mask)
lexical_q_tiles = (lexical_length + BLOCK_Q - 1) // BLOCK_Q
tail_q_tiles = (LOCAL_SLOTS + BLOCK_Q - 1) // BLOCK_Q
row_q_tiles = lexical_q_tiles + tail_q_tiles
q_tile_offset = (
tl.atomic_add(storage_ptr + q_tile_counter_base, row_q_tiles, mask=row_valid) - 1
)
q_tile_mask = row_valid & (position < row_q_tiles)
q_start = tl.where(
position < lexical_q_tiles,
position * BLOCK_Q,
lexical_length + (position - lexical_q_tiles) * BLOCK_Q,
)
tl.store(storage_ptr + q_tile_rows_base + q_tile_offset + position, row, mask=q_tile_mask)
tl.store(
storage_ptr + q_tile_starts_base + q_tile_offset + position, q_start, mask=q_tile_mask
)
row_token_tiles = (target_length + BLOCK_K_TOKEN - 1) // BLOCK_K_TOKEN
token_tile_offset = (
tl.atomic_add(storage_ptr + token_owner_counter_base, row_token_tiles, mask=row_valid)
- 1
)
token_tile_mask = row_valid & (position < row_token_tiles)
tl.store(
storage_ptr + token_owner_rows_base + token_tile_offset + position,
row,
mask=token_tile_mask,
)
tl.store(
storage_ptr + token_owner_starts_base + token_tile_offset + position,
position * BLOCK_K_TOKEN,
mask=token_tile_mask,
)
local_tail_mask = row_valid & (position < LOCAL_SLOTS)
tail_index = row * LOCAL_SLOTS + position
tl.store(
storage_ptr + eoc_base + tail_index,
target_offset + lexical_length + position,
mask=local_tail_mask,
)
global_tail_mask = row_valid & (position < GLOBAL_SLOTS)
global_index = row * GLOBAL_SLOTS + position
tl.store(
storage_ptr + memory_positions_base + global_index, chunk_index, mask=global_tail_mask
)
memory_tile = tl.program_id(0)
q_lane = tl.arange(0, BLOCK_MEMORY_QUERY)
q_token = memory_tile * BLOCK_MEMORY_QUERY + q_lane
q_valid = (memory_tile < memory_tile_count) & (q_token < target_tokens)
search_low = tl.zeros((BLOCK_MEMORY_QUERY,), tl.int64)
search_high = search_low + rows
for _ in tl.static_range(0, 32):
candidate = (search_low + search_high) // 2
candidate_valid = (search_low < search_high) & (candidate < rows)
candidate_physical_offset = tl.load(
physical_row_offsets_ptr + candidate, mask=q_valid & candidate_valid, other=0
).to(tl.int64)
candidate_lexical_offset = candidate_physical_offset - candidate * PHYSICAL_SLOTS
search_right = q_valid & candidate_valid & (q_token >= candidate_lexical_offset)
search_low = tl.where(search_right, candidate + 1, search_low)
search_high = tl.where(candidate_valid & ~search_right, candidate, search_high)
lexical_row = tl.maximum(search_low - 1, 0)
tail_row = (q_token - total_lexical_tokens) // LOCAL_SLOTS
query_row = tl.where(q_token < total_lexical_tokens, lexical_row, tail_row)
query_row_valid = q_valid & (query_row >= 0) & (query_row < rows)
if TRUSTED_FIXED:
query_chunk = tl.load(
expected_row_geometry_ptr + rows + query_row, mask=query_row_valid, other=0
).to(tl.int64)
query_memory_chunks = tl.minimum(query_chunk, MAX_MEMORY_SIZE - 1)
query_memory_start = (query_row - query_memory_chunks) * GLOBAL_SLOTS
query_memory_length = query_memory_chunks * GLOBAL_SLOTS
else:
query_physical_memory_start = tl.load(
physical_memory_start_ptr + query_row, mask=query_row_valid, other=0
).to(tl.int64)
query_physical_memory_length = tl.load(
physical_memory_length_ptr + query_row, mask=query_row_valid, other=0
).to(tl.int64)
query_memory_start = query_physical_memory_start // PHYSICAL_SLOTS * GLOBAL_SLOTS
query_memory_length = query_physical_memory_length // PHYSICAL_SLOTS * GLOBAL_SLOTS
query_memory_length = tl.where(
q_token < total_lexical_tokens,
tl.maximum(query_memory_length - GLOBAL_SLOTS, 0),
query_memory_length,
)
has_query_memory = query_row_valid & (query_memory_length > 0)
any_query_memory = tl.sum(has_query_memory.to(tl.int32), axis=0) > 0
union_start = tl.min(tl.where(has_query_memory, query_memory_start, 2147483647), axis=0)
union_end = tl.max(
tl.where(has_query_memory, query_memory_start + query_memory_length, 0), axis=0
)
common_start = tl.max(tl.where(has_query_memory, query_memory_start, 0), axis=0)
common_end = tl.min(
tl.where(has_query_memory, query_memory_start + query_memory_length, 2147483647), axis=0
)
union_start = tl.where(any_query_memory, union_start, 0)
union_end = tl.where(any_query_memory, union_end, 0)
common_start = tl.where(any_query_memory, common_start, 0)
common_end = tl.where(any_query_memory, common_end, 0)
start_delta = tl.maximum(common_start - union_start, 0)
end_delta = tl.maximum(common_end - union_start, 0)
aligned_start = (
union_start + (start_delta + BLOCK_K_MEMORY - 1) // BLOCK_K_MEMORY * BLOCK_K_MEMORY
)
aligned_end = union_start + end_delta // BLOCK_K_MEMORY * BLOCK_K_MEMORY
has_interior = aligned_start < aligned_end
interior_start = tl.where(has_interior, aligned_start, union_end)
interior_end = tl.where(has_interior, aligned_end, union_end)
memory_tile_mask = memory_tile < memory_tile_count
tl.store(
storage_ptr + memory_union_start_base + memory_tile, union_start, mask=memory_tile_mask
)
tl.store(
storage_ptr + memory_union_end_base + memory_tile, union_end, mask=memory_tile_mask
)
tl.store(
storage_ptr + memory_interior_start_base + memory_tile,
interior_start,
mask=memory_tile_mask,
)
tl.store(
storage_ptr + memory_interior_end_base + memory_tile,
interior_end,
mask=memory_tile_mask,
)
tl.atomic_xchg(storage_ptr + validation_result_base, 0, mask=row_mask & ~row_valid)
@triton.jit
def _pat_rotate_rows(
x,
cosine,
sine,
BLOCK_M: tl.constexpr,
BLOCK_D: tl.constexpr,
FP32_PRODUCTS: tl.constexpr = False,
):
if FP32_PRODUCTS:
source = x.to(tl.float32)
cosine, sine = (cosine.to(tl.float32), sine.to(tl.float32))
pairs = tl.reshape(source, (BLOCK_M, BLOCK_D // 2, 2))
even, odd = tl.split(pairs)
quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_M, BLOCK_D))
return tl.fma(quarter_turn, sine, source * cosine).to(x.dtype)
else:
pairs = tl.reshape(x, (BLOCK_M, BLOCK_D // 2, 2))
even, odd = tl.split(pairs)
quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_M, BLOCK_D))
return x * cosine + quarter_turn * sine
@triton.jit
def _pat_canonical_token_index(
row, row_offset, row_position, lexical_length, total_lexical_tokens, local_tail_slots
):
"""Map one logical row position into [all lexical][all local tails]."""
lexical_index = row_offset - row * local_tail_slots + row_position
tail_index = total_lexical_tokens + row * local_tail_slots + row_position - lexical_length
return tl.where(row_position < lexical_length, lexical_index, tail_index)
@triton.jit
def _pat_logical_query_from_canonical(
q_token, row, row_offset, lexical_length, total_lexical_tokens, local_tail_slots
):
"""Recover logical packed-row coordinates from a physical query index."""
lexical_start = row_offset - row * local_tail_slots
lexical_position = q_token - lexical_start
tail_position = q_token - total_lexical_tokens - row * local_tail_slots
q_pos = tl.where(
q_token < total_lexical_tokens, lexical_position, lexical_length + tail_position
)
return (row_offset + q_pos, q_pos)
@triton.jit
def _pat_online_step(q, k, v, valid, has_key, m, denominator, output, qk_scale):
scores = tl.dot(q, k, input_precision="ieee") * qk_scale
scores = tl.where(valid, scores, -float("inf"))
tile_max = tl.max(scores, axis=1)
next_m = tl.where(has_key, tl.maximum(m, tile_max), m)
alpha = tl.where(has_key, tl.exp2(m - next_m), 1.0)
probability = tl.where(valid, tl.exp2(scores - next_m[:, None]), 0.0)
output = output * alpha[:, None] + tl.dot(
probability.to(v.dtype), v, input_precision="ieee"
)
denominator = denominator * alpha + tl.sum(probability, axis=1)
return (next_m, denominator, output)
@triton.jit
def _pat_memory_forward_tile(
q_memory,
k_memory_ptr,
v_memory_ptr,
memory_tile_start,
memory_start,
memory_length,
has_memory,
union_end,
m,
denominator,
output,
qk_scale,
memory_slots,
head,
heads,
head_dim,
offs_k,
offs_d,
d_mask,
FULL_INTERIOR: tl.constexpr,
):
"""Process one original K tile, specializing its shared interior."""
k_abs = memory_tile_start + offs_k
if FULL_INTERIOR:
k = tl.load(
k_memory_ptr
+ k_abs[None, :] * heads * head_dim
+ head * head_dim
+ offs_d[:, None],
mask=d_mask[:, None],
other=0.0,
)
v = tl.load(
v_memory_ptr
+ k_abs[:, None] * heads * head_dim
+ head * head_dim
+ offs_d[None, :],
mask=d_mask[None, :],
other=0.0,
)
valid = has_memory[:, None]
has_key = has_memory
else:
k_mask = (k_abs < union_end) & (k_abs < memory_slots)
k = tl.load(
k_memory_ptr
+ k_abs[None, :] * heads * head_dim
+ head * head_dim
+ offs_d[:, None],
mask=d_mask[:, None] & k_mask[None, :],
other=0.0,
)
v = tl.load(
v_memory_ptr
+ k_abs[:, None] * heads * head_dim
+ head * head_dim
+ offs_d[None, :],
mask=k_mask[:, None] & d_mask[None, :],
other=0.0,
)
memory_end = memory_start + memory_length
valid = (
has_memory[:, None]
& k_mask[None, :]
& (k_abs[None, :] >= memory_start[:, None])
& (k_abs[None, :] < memory_end[:, None])
)
tile_end = tl.minimum(memory_tile_start + offs_k.shape[0], union_end)
has_key = has_memory & (memory_start < tile_end) & (memory_end > memory_tile_start)
return _pat_online_step(q_memory, k, v, valid, has_key, m, denominator, output, qk_scale)
@triton.jit(
do_not_specialize=("total_lexical_tokens",),
do_not_specialize_on_alignment=("total_lexical_tokens",),
)
def _pat_token_forward_kernel(
q_ptr,
k_token_ptr,
v_token_ptr,
out_ptr,
lse_ptr,
row_offsets_ptr,
row_lengths_ptr,
memory_query_start_ptr,
row_exact_start_ptr,
row_exact_length_ptr,
row_exact_delta_ptr,
phase_cos_ptr,
phase_sin_ptr,
q_tile_rows_ptr,
q_tile_starts_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
heads,
head_dim,
BLOCK_Q: tl.constexpr,
BLOCK_K_TOKEN: tl.constexpr,
BLOCK_D: tl.constexpr,
FP32_ROTARY_PRODUCTS: tl.constexpr = False,
):
tile = tl.program_id(0)
head = tl.program_id(1)
row = tl.load(q_tile_rows_ptr + tile)
q_start = tl.load(q_tile_starts_ptr + tile)
row_offset = tl.load(row_offsets_ptr + row)
row_length = tl.load(row_lengths_ptr + row)
lexical_length = tl.load(memory_query_start_ptr + row)
query_is_eoc = q_start >= lexical_length
offs_q = tl.arange(0, BLOCK_Q)
offs_d = tl.arange(0, BLOCK_D)
q_pos = q_start + offs_q
q_mask = (q_pos < row_length) & tl.where(
query_is_eoc, q_pos >= lexical_length, q_pos < lexical_length
)
d_mask = offs_d < head_dim
q_flat = row_offset + q_pos
q_token = _pat_canonical_token_index(
row, row_offset, q_pos, lexical_length, total_lexical_tokens, local_tail_slots
)
q = tl.load(
q_ptr + q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :],
mask=q_mask[:, None] & d_mask[None, :],
other=0.0,
)
m = tl.full((BLOCK_Q,), -float("inf"), tl.float32)
denominator = tl.zeros((BLOCK_Q,), tl.float32)
output = tl.zeros((BLOCK_Q, BLOCK_D), tl.float32)
qk_scale = scale * 1.4426950408889634
offs_kt = tl.arange(0, BLOCK_K_TOKEN)
local_stop = tl.where(
query_is_eoc, row_length, tl.minimum(lexical_length, q_start + BLOCK_Q)
)
local_start = 0
while local_start < local_stop:
local_pos = local_start + offs_kt
local_token = _pat_canonical_token_index(
row, row_offset, local_pos, lexical_length, total_lexical_tokens, local_tail_slots
)
local_mask = local_pos < local_stop
k = tl.load(
k_token_ptr
+ local_token[None, :] * heads * head_dim
+ head * head_dim
+ offs_d[:, None],
mask=d_mask[:, None] & local_mask[None, :],
other=0.0,
)
v = tl.load(
v_token_ptr
+ local_token[:, None] * heads * head_dim
+ head * head_dim
+ offs_d[None, :],
mask=local_mask[:, None] & d_mask[None, :],
other=0.0,
)
visible = query_is_eoc | (local_pos[None, :] <= q_pos[:, None])
valid = q_mask[:, None] & local_mask[None, :] & visible
m, denominator, output = _pat_online_step(
q, k, v, valid, q_mask, m, denominator, output, qk_scale
)
local_start += BLOCK_K_TOKEN
exact_start = tl.load(row_exact_start_ptr + row)
exact_length = tl.where(query_is_eoc, 0, tl.load(row_exact_length_ptr + row))
exact_delta = tl.load(row_exact_delta_ptr + row)
exact_phase_offset = exact_delta * BLOCK_D + offs_d
table_cosine = tl.load(phase_cos_ptr + exact_phase_offset, mask=d_mask, other=1.0)
table_sine = tl.load(phase_sin_ptr + exact_phase_offset, mask=d_mask, other=0.0)
has_exact_phase = exact_delta != 0
exact_cosine = tl.where(has_exact_phase, table_cosine, 1.0)
exact_sine = tl.where(has_exact_phase, -table_sine, 0.0)
q_exact = _pat_rotate_rows(
q,
exact_cosine[None, :].to(q.dtype),
exact_sine[None, :].to(q.dtype),
BLOCK_M=BLOCK_Q,
BLOCK_D=BLOCK_D,
FP32_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
exact_offset_start = (q_start + 1) // BLOCK_K_TOKEN * BLOCK_K_TOKEN
exact_source_row = tl.maximum(row - 1, 0)
while exact_offset_start < exact_length:
exact_offset = exact_offset_start + offs_kt
exact_token = exact_start - exact_source_row * local_tail_slots + exact_offset
exact_mask = exact_offset < exact_length
k = tl.load(
k_token_ptr
+ exact_token[None, :] * heads * head_dim
+ head * head_dim
+ offs_d[:, None],
mask=d_mask[:, None] & exact_mask[None, :],
other=0.0,
)
v = tl.load(
v_token_ptr
+ exact_token[:, None] * heads * head_dim
+ head * head_dim
+ offs_d[None, :],
mask=exact_mask[:, None] & d_mask[None, :],
other=0.0,
)
valid = q_mask[:, None] & exact_mask[None, :] & (exact_offset[None, :] > q_pos[:, None])
exact_tile_stop = tl.minimum(exact_offset_start + BLOCK_K_TOKEN, exact_length)
has_exact_key = q_mask & (q_pos + 1 < exact_tile_stop)
m, denominator, output = _pat_online_step(
q_exact, k, v, valid, has_exact_key, m, denominator, output, qk_scale
)
exact_offset_start += BLOCK_K_TOKEN
safe_denominator = tl.where(q_mask, denominator, 1.0)
normalized = output / safe_denominator[:, None]
lse = tl.where(q_mask, m + tl.log2(safe_denominator), 0.0)
tl.store(
out_ptr + q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :],
normalized,
mask=q_mask[:, None] & d_mask[None, :],
)
tl.store(lse_ptr + q_flat * heads + head, lse, mask=q_mask)
@triton.jit(
do_not_specialize=("total_lexical_tokens", "memory_slots"),
do_not_specialize_on_alignment=("total_lexical_tokens", "memory_slots"),
)
def _pat_newest_forward_kernel(
q_ptr,
k_memory_ptr,
v_memory_ptr,
token_out_ptr,
lse_ptr,
row_offsets_ptr,
memory_query_start_ptr,
row_memory_start_ptr,
row_memory_length_ptr,
phase_cos_ptr,
phase_sin_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
memory_slots,
heads,
head_dim,
GLOBAL_SLOTS: tl.constexpr,
CHUNK_SIZE: tl.constexpr,
BLOCK_Q: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_D: tl.constexpr,
FP32_ROTARY_PRODUCTS: tl.constexpr = False,
):
"""Merge newest memory into lexical seed tiles owned by one row/head."""
row = tl.program_id(0)
head = tl.program_id(1)
row_offset = tl.load(row_offsets_ptr + row)
lexical_length = tl.load(memory_query_start_ptr + row)
offs_k = tl.arange(0, BLOCK_K)
offs_d = tl.arange(0, BLOCK_D)
d_mask = offs_d < head_dim
memory_start = tl.load(row_memory_start_ptr + row)
memory_length = tl.load(row_memory_length_ptr + row)
has_newest_memory = memory_length >= GLOBAL_SLOTS
newest_start = memory_start + memory_length - GLOBAL_SLOTS
newest_phase_offset = (CHUNK_SIZE - 1) * BLOCK_D + offs_d
newest_cosine = tl.load(phase_cos_ptr + newest_phase_offset, mask=d_mask, other=1.0)
newest_sine = tl.load(phase_sin_ptr + newest_phase_offset, mask=d_mask, other=0.0)
qk_scale = scale * 1.4426950408889634
q_start = 0
while q_start < lexical_length:
offs_q = tl.arange(0, BLOCK_Q)
q_pos = q_start + offs_q
q_mask = (q_pos < lexical_length) & has_newest_memory
q_flat = row_offset + q_pos
q_token = _pat_canonical_token_index(
row, row_offset, q_pos, lexical_length, total_lexical_tokens, local_tail_slots
)
token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :]
q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0)
output = tl.load(
token_out_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0
).to(tl.float32)
seed_lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(
tl.float32
)
m = tl.where(q_mask, seed_lse, -float("inf"))
denominator = tl.where(q_mask, 1.0, 0.0).to(tl.float32)
q_newest = _pat_rotate_rows(
q,
newest_cosine[None, :].to(q.dtype),
newest_sine[None, :].to(q.dtype),
BLOCK_M=BLOCK_Q,
BLOCK_D=BLOCK_D,
FP32_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
newest_offset_start = 0
while newest_offset_start < GLOBAL_SLOTS:
newest_offset = newest_offset_start + offs_k
newest_abs = newest_start + newest_offset
newest_mask = (
has_newest_memory & (newest_offset < GLOBAL_SLOTS) & (newest_abs < memory_slots)
)
newest_k = tl.load(
k_memory_ptr
+ newest_abs[None, :] * heads * head_dim
+ head * head_dim
+ offs_d[:, None],
mask=d_mask[:, None] & newest_mask[None, :],
other=0.0,
)
newest_v = tl.load(
v_memory_ptr
+ newest_abs[:, None] * heads * head_dim
+ head * head_dim
+ offs_d[None, :],
mask=newest_mask[:, None] & d_mask[None, :],
other=0.0,
)
newest_valid = q_mask[:, None] & newest_mask[None, :]
m, denominator, output = _pat_online_step(
q_newest,
newest_k,
newest_v,
newest_valid,
q_mask,
m,
denominator,
output,
qk_scale,
)
newest_offset_start += BLOCK_K
safe_denominator = tl.where(q_mask, denominator, 1.0)
normalized = output / safe_denominator[:, None]
final_lse = tl.where(q_mask, m + tl.log2(safe_denominator), 0.0)
tl.store(
token_out_ptr + token_offsets, normalized, mask=q_mask[:, None] & d_mask[None, :]
)
tl.store(lse_ptr + q_flat * heads + head, final_lse, mask=q_mask)
q_start += BLOCK_Q
@triton.jit(
do_not_specialize=("total_lexical_tokens", "tokens", "memory_slots"),
do_not_specialize_on_alignment=("total_lexical_tokens", "tokens", "memory_slots"),
)
def _pat_memory_forward_kernel(
q_ptr,
k_memory_ptr,
v_memory_ptr,
token_out_ptr,
out_ptr,
lse_ptr,
row_offsets_ptr,
memory_query_start_ptr,
row_memory_start_ptr,
row_memory_length_ptr,
phase_cos_ptr,
phase_sin_ptr,
token_row_ids_ptr,
memory_tile_union_start_ptr,
memory_tile_union_end_ptr,
memory_tile_interior_start_ptr,
memory_tile_interior_end_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
tokens,
memory_slots,
heads,
head_dim,
GLOBAL_SLOTS: tl.constexpr,
CHUNK_SIZE: tl.constexpr,
BLOCK_Q: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_D: tl.constexpr,
FP32_ROTARY_PRODUCTS: tl.constexpr = False,
):
"""Merge exact per-query compressed memory into token-only seed state."""
tile = tl.program_id(0)
head = tl.program_id(1)
offs_q = tl.arange(0, BLOCK_Q)
offs_k = tl.arange(0, BLOCK_K)
offs_d = tl.arange(0, BLOCK_D)
q_token = tile * BLOCK_Q + offs_q
q_mask = q_token < tokens
row = tl.load(token_row_ids_ptr + q_token, mask=q_mask, other=0)
row_offset = tl.load(row_offsets_ptr + row, mask=q_mask, other=0)
lexical_length = tl.load(memory_query_start_ptr + row, mask=q_mask, other=0)
q_flat, q_pos = _pat_logical_query_from_canonical(
q_token, row, row_offset, lexical_length, total_lexical_tokens, local_tail_slots
)
query_is_eoc = q_pos >= lexical_length
d_mask = offs_d < head_dim
token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :]
q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0)
phase_row = tl.where(query_is_eoc, CHUNK_SIZE - 1, tl.minimum(q_pos, CHUNK_SIZE - 1))
phase_offset = phase_row[:, None] * BLOCK_D + offs_d[None, :]
cosine = tl.load(
phase_cos_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=1.0
)
sine = tl.load(
phase_sin_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=0.0
)
q_memory = _pat_rotate_rows(
q,
cosine.to(q.dtype),
sine.to(q.dtype),
BLOCK_M=BLOCK_Q,
BLOCK_D=BLOCK_D,
FP32_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
output = tl.load(
token_out_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0
).to(tl.float32)
seed_lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(tl.float32)
m = tl.where(q_mask, seed_lse, -float("inf"))
denominator = tl.where(q_mask, 1.0, 0.0).to(tl.float32)
qk_scale = scale * 1.4426950408889634
memory_start = tl.load(row_memory_start_ptr + row, mask=q_mask, other=0)
memory_length = tl.load(row_memory_length_ptr + row, mask=q_mask, other=0)
if GLOBAL_SLOTS > 0:
memory_length = tl.where(
query_is_eoc, memory_length, tl.maximum(memory_length - GLOBAL_SLOTS, 0)
)
has_memory = q_mask & (memory_length > 0)
union_start = tl.load(memory_tile_union_start_ptr + tile)
union_end = tl.load(memory_tile_union_end_ptr + tile)
interior_start = tl.load(memory_tile_interior_start_ptr + tile)
interior_end = tl.load(memory_tile_interior_end_ptr + tile)
memory_tile_start = union_start
while memory_tile_start < interior_start:
m, denominator, output = _pat_memory_forward_tile(
q_memory,
k_memory_ptr,
v_memory_ptr,
memory_tile_start,
memory_start,
memory_length,
has_memory,
union_end,
m,
denominator,
output,
qk_scale,
memory_slots,
head,
heads,
head_dim,
offs_k,
offs_d,
d_mask,
FULL_INTERIOR=False,
)
memory_tile_start += BLOCK_K
memory_tile_start = interior_start
while memory_tile_start < interior_end:
m, denominator, output = _pat_memory_forward_tile(
q_memory,
k_memory_ptr,
v_memory_ptr,
memory_tile_start,
memory_start,
memory_length,
has_memory,
union_end,
m,
denominator,
output,
qk_scale,
memory_slots,
head,
heads,
head_dim,
offs_k,
offs_d,
d_mask,
FULL_INTERIOR=True,
)
memory_tile_start += BLOCK_K
memory_tile_start = interior_end
while memory_tile_start < union_end:
m, denominator, output = _pat_memory_forward_tile(
q_memory,
k_memory_ptr,
v_memory_ptr,
memory_tile_start,
memory_start,
memory_length,
has_memory,
union_end,
m,
denominator,
output,
qk_scale,
memory_slots,
head,
heads,
head_dim,
offs_k,
offs_d,
d_mask,
FULL_INTERIOR=False,
)
memory_tile_start += BLOCK_K
safe_denominator = tl.where(q_mask, denominator, 1.0)
normalized = output / safe_denominator[:, None]
final_lse = tl.where(q_mask, m + tl.log2(safe_denominator), 0.0)
tl.store(out_ptr + token_offsets, normalized, mask=q_mask[:, None] & d_mask[None, :])
tl.store(lse_ptr + q_flat * heads + head, final_lse, mask=q_mask)
@triton.jit(
do_not_specialize=("total_lexical_tokens", "tokens"),
do_not_specialize_on_alignment=("total_lexical_tokens", "tokens"),
)
def _pat_delta_kernel(
out_ptr,
do_ptr,
delta_ptr,
row_offsets_ptr,
memory_query_start_ptr,
token_row_ids_ptr,
total_lexical_tokens,
local_tail_slots,
tokens,
heads,
head_dim,
BLOCK_Q: tl.constexpr,
BLOCK_D: tl.constexpr,
):
tile = tl.program_id(0)
head = tl.program_id(1)
q_token = tile * BLOCK_Q + tl.arange(0, BLOCK_Q)
offs_d = tl.arange(0, BLOCK_D)
q_mask = q_token < tokens
row = tl.load(token_row_ids_ptr + q_token, mask=q_mask, other=0)
row_offset = tl.load(row_offsets_ptr + row, mask=q_mask, other=0)
lexical_length = tl.load(memory_query_start_ptr + row, mask=q_mask, other=0)
q_flat, _ = _pat_logical_query_from_canonical(
q_token, row, row_offset, lexical_length, total_lexical_tokens, local_tail_slots
)
mask = q_mask[:, None] & (offs_d[None, :] < head_dim)
offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :]
output = tl.load(out_ptr + offsets, mask=mask, other=0.0).to(tl.float32)
gradient = tl.load(do_ptr + offsets, mask=mask, other=0.0).to(tl.float32)
value = tl.sum(output * gradient, axis=1)
tl.store(delta_ptr + q_flat * heads + head, value, mask=q_mask)
@triton.jit
def _pat_five_dot_edge(q, k, v, do, lse, delta, valid, scale):
"""All five backward matrix products for one visible Q/K tile edge."""
scores = tl.dot(q, k, input_precision="ieee") * (scale * 1.4426950408889634)
probability = tl.where(valid, tl.exp2(scores - lse[:, None]), 0.0)
probability_gradient = tl.dot(do, tl.trans(v), input_precision="ieee")
score_gradient = tl.where(valid, probability * (probability_gradient - delta[:, None]), 0.0)
dq = tl.dot(score_gradient.to(k.dtype), tl.trans(k), input_precision="ieee") * scale
dk = tl.dot(tl.trans(score_gradient.to(q.dtype)), q, input_precision="ieee") * scale
dv = tl.dot(tl.trans(probability.to(do.dtype)), do, input_precision="ieee")
return (dq, dk, dv)
@triton.jit
def _pat_atomic_dq(dq_accum_ptr, dq, q_token, q_mask, offs_d, d_mask, head, heads, head_dim):
offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :]
tl.atomic_add(dq_accum_ptr + offsets, dq, mask=q_mask[:, None] & d_mask[None, :])
@triton.jit(
do_not_specialize=("total_lexical_tokens", "tokens", "memory_slots"),
do_not_specialize_on_alignment=("total_lexical_tokens", "tokens", "memory_slots"),
)
def _pat_memory_query_owner_backward_kernel(
dk_descriptor,
dv_descriptor,
q_ptr,
k_memory_ptr,
v_memory_ptr,
lse_ptr,
do_ptr,
delta_ptr,
dq_accum_ptr,
row_offsets_ptr,
memory_query_start_ptr,
phase_cos_ptr,
phase_sin_ptr,
token_row_ids_ptr,
memory_tile_union_start_ptr,
memory_tile_union_end_ptr,
total_lexical_tokens,
local_tail_slots,
row_memory_start_ptr,
row_memory_length_ptr,
scale,
tokens,
memory_slots,
heads,
head_dim,
GLOBAL_SLOTS: tl.constexpr,
CHUNK_SIZE: tl.constexpr,
BLOCK_Q: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_D: tl.constexpr,
FP32_ROTARY_PRODUCTS: tl.constexpr = False,
):
tile = tl.program_id(0)
head = tl.program_id(1)
offs_q = tl.arange(0, BLOCK_Q)
offs_k = tl.arange(0, BLOCK_K)
offs_d = tl.arange(0, BLOCK_D)
q_token = tile * BLOCK_Q + offs_q
q_mask = q_token < tokens
row = tl.load(token_row_ids_ptr + q_token, mask=q_mask, other=0)
row_offset = tl.load(row_offsets_ptr + row, mask=q_mask, other=0)
lexical_length = tl.load(memory_query_start_ptr + row, mask=q_mask, other=0)
q_flat, q_pos = _pat_logical_query_from_canonical(
q_token, row, row_offset, lexical_length, total_lexical_tokens, local_tail_slots
)
query_is_eoc = q_pos >= lexical_length
d_mask = offs_d < head_dim
token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :]
q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0)
do = tl.load(do_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0)
lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(tl.float32)
saved_delta = tl.load(delta_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(
tl.float32
)
memory_start = tl.load(row_memory_start_ptr + row, mask=q_mask, other=0)
memory_length = tl.load(row_memory_length_ptr + row, mask=q_mask, other=0)
if GLOBAL_SLOTS > 0:
memory_length = tl.where(
query_is_eoc, memory_length, tl.maximum(memory_length - GLOBAL_SLOTS, 0)
)
phase_row = tl.where(query_is_eoc, CHUNK_SIZE - 1, tl.minimum(q_pos, CHUNK_SIZE - 1))
phase_offset = phase_row[:, None] * BLOCK_D + offs_d[None, :]
cosine = tl.load(
phase_cos_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=1.0
)
sine = tl.load(
phase_sin_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=0.0
)
transformed_q = _pat_rotate_rows(
q,
cosine.to(q.dtype),
sine.to(q.dtype),
BLOCK_M=BLOCK_Q,
BLOCK_D=BLOCK_D,
FP32_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
has_memory = q_mask & (memory_length > 0)
union_start = tl.load(memory_tile_union_start_ptr + tile)
union_end = tl.load(memory_tile_union_end_ptr + tile)
union_count = union_end - union_start
descriptor_start = union_start.to(tl.int32)
descriptor_count = union_count.to(tl.int32)
transformed_dq = tl.zeros((BLOCK_Q, BLOCK_D), tl.float32)
memory_tile_start = union_start
while memory_tile_start < union_end:
k_abs = memory_tile_start + offs_k
k_mask = (k_abs < union_end) & (k_abs < memory_slots)
k = tl.load(
k_memory_ptr
+ k_abs[None, :] * heads * head_dim
+ head * head_dim
+ offs_d[:, None],
mask=d_mask[:, None] & k_mask[None, :],
other=0.0,
)
v = tl.load(
v_memory_ptr
+ k_abs[:, None] * heads * head_dim
+ head * head_dim
+ offs_d[None, :],
mask=k_mask[:, None] & d_mask[None, :],
other=0.0,
)
valid = (
has_memory[:, None]
& k_mask[None, :]
& (k_abs[None, :] >= memory_start[:, None])
& (k_abs[None, :] < memory_start[:, None] + memory_length[:, None])
)
scores = tl.dot(transformed_q, k, input_precision="ieee") * (scale * 1.4426950408889634)
probability = tl.where(valid, tl.exp2(scores - lse[:, None]), 0.0)
probability_gradient = tl.dot(do, tl.trans(v), input_precision="ieee")
score_gradient = tl.where(
valid, probability * (probability_gradient - saved_delta[:, None]), 0.0
)
transformed_dq += (
tl.dot(score_gradient.to(k.dtype), tl.trans(k), input_precision="ieee") * scale
)
dk = (
tl.dot(
tl.trans(score_gradient.to(transformed_q.dtype)),
transformed_q,
input_precision="ieee",
)
* scale
)
atomic_add_ragged(
dk_descriptor,
descriptor_start,
descriptor_count,
[(memory_tile_start - union_start).to(tl.int32), head, 0],
tl.reshape(dk, (BLOCK_K, 1, BLOCK_D)),
)
dv = tl.dot(tl.trans(probability.to(do.dtype)), do, input_precision="ieee")
atomic_add_ragged(
dv_descriptor,
descriptor_start,
descriptor_count,
[(memory_tile_start - union_start).to(tl.int32), head, 0],
tl.reshape(dv, (BLOCK_K, 1, BLOCK_D)),
)
memory_tile_start += BLOCK_K
original_dq = _pat_rotate_rows(
transformed_dq,
cosine.to(transformed_dq.dtype),
-sine.to(transformed_dq.dtype),
BLOCK_M=BLOCK_Q,
BLOCK_D=BLOCK_D,
FP32_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
tl.store(dq_accum_ptr + token_offsets, original_dq, mask=q_mask[:, None] & d_mask[None, :])
@triton.jit
def _pat_token_query_edge(
q_ptr,
lse_ptr,
do_ptr,
delta_ptr,
dq_accum_ptr,
k,
v,
k_abs,
owner_local_pos,
owner_k_mask,
row,
q_start,
row_offsets_ptr,
row_lengths_ptr,
memory_query_start_ptr,
row_exact_start_ptr,
row_exact_length_ptr,
row_exact_delta_ptr,
phase_cos_ptr,
phase_sin_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
head,
heads,
head_dim,
EXACT_LANE: tl.constexpr,
EOC_QUERY: tl.constexpr,
CHUNK_SIZE: tl.constexpr,
BLOCK_Q: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_D: tl.constexpr,
FP32_ROTARY_PRODUCTS: tl.constexpr = False,
):
offs_q = tl.arange(0, BLOCK_Q)
offs_d = tl.arange(0, BLOCK_D)
q_pos = q_start + offs_q
row_offset = tl.load(row_offsets_ptr + row)
row_length = tl.load(row_lengths_ptr + row)
lexical_length = tl.load(memory_query_start_ptr + row)
q_mask = (q_pos < row_length) & tl.where(
EOC_QUERY, q_pos >= lexical_length, q_pos < lexical_length
)
d_mask = offs_d < head_dim
q_flat = row_offset + q_pos
q_token = _pat_canonical_token_index(
row, row_offset, q_pos, lexical_length, total_lexical_tokens, local_tail_slots
)
token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :]
q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0)
do = tl.load(do_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0)
lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(tl.float32)
saved_delta = tl.load(delta_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(
tl.float32
)
if EXACT_LANE:
exact_start = tl.load(row_exact_start_ptr + row)
exact_length = tl.load(row_exact_length_ptr + row)
exact_offset = k_abs - exact_start
k_mask = owner_k_mask & (exact_offset >= 0) & (exact_offset < exact_length)
valid = q_mask[:, None] & k_mask[None, :] & (exact_offset[None, :] > q_pos[:, None])
exact_delta = tl.load(row_exact_delta_ptr + row)
exact_phase_offset = exact_delta * BLOCK_D + offs_d
table_cosine = tl.load(phase_cos_ptr + exact_phase_offset, mask=d_mask, other=1.0)
table_sine = tl.load(phase_sin_ptr + exact_phase_offset, mask=d_mask, other=0.0)
has_exact_phase = exact_delta != 0
cosine = tl.where(has_exact_phase, table_cosine, 1.0)
sine = tl.where(has_exact_phase, -table_sine, 0.0)
transformed_q = _pat_rotate_rows(
q,
cosine[None, :].to(q.dtype),
sine[None, :].to(q.dtype),
BLOCK_M=BLOCK_Q,
BLOCK_D=BLOCK_D,
FP32_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
else:
k_mask = owner_k_mask
visible = EOC_QUERY | (owner_local_pos[None, :] <= q_pos[:, None])
valid = q_mask[:, None] & k_mask[None, :] & visible
transformed_q = q
dq, dk, dv = _pat_five_dot_edge(transformed_q, k, v, do, lse, saved_delta, valid, scale)
if EXACT_LANE:
original_dq = _pat_rotate_rows(
dq,
cosine[None, :].to(dq.dtype),
-sine[None, :].to(dq.dtype),
BLOCK_M=BLOCK_Q,
BLOCK_D=BLOCK_D,
FP32_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
else:
original_dq = dq
_pat_atomic_dq(
dq_accum_ptr, original_dq, q_token, q_mask, offs_d, d_mask, head, heads, head_dim
)
return (dk, dv)
@triton.jit
def _pat_newest_memory_query_edge(
q_ptr,
lse_ptr,
do_ptr,
delta_ptr,
dq_accum_ptr,
k,
v,
memory_k_mask,
row,
q_start,
row_offsets_ptr,
lexical_length,
phase_cos_ptr,
phase_sin_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
head,
heads,
head_dim,
CHUNK_SIZE: tl.constexpr,
BLOCK_Q: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_D: tl.constexpr,
FP32_ROTARY_PRODUCTS: tl.constexpr = False,
):
"""Backward edge for the newest, locally positioned memory group."""
offs_q = tl.arange(0, BLOCK_Q)
offs_d = tl.arange(0, BLOCK_D)
q_pos = q_start + offs_q
row_offset = tl.load(row_offsets_ptr + row)
q_mask = q_pos < lexical_length
d_mask = offs_d < head_dim
q_flat = row_offset + q_pos
q_token = _pat_canonical_token_index(
row, row_offset, q_pos, lexical_length, total_lexical_tokens, local_tail_slots
)
token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :]
q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0)
do = tl.load(do_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0)
lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(tl.float32)
saved_delta = tl.load(delta_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(
tl.float32
)
phase_offset = (CHUNK_SIZE - 1) * BLOCK_D + offs_d
cosine = tl.load(phase_cos_ptr + phase_offset, mask=d_mask, other=1.0)
sine = tl.load(phase_sin_ptr + phase_offset, mask=d_mask, other=0.0)
transformed_q = _pat_rotate_rows(
q,
cosine[None, :].to(q.dtype),
sine[None, :].to(q.dtype),
BLOCK_M=BLOCK_Q,
BLOCK_D=BLOCK_D,
FP32_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
valid = q_mask[:, None] & memory_k_mask[None, :]
transformed_dq, dk, dv = _pat_five_dot_edge(
transformed_q, k, v, do, lse, saved_delta, valid, scale
)
original_dq = _pat_rotate_rows(
transformed_dq,
cosine[None, :].to(transformed_dq.dtype),
-sine[None, :].to(transformed_dq.dtype),
BLOCK_M=BLOCK_Q,
BLOCK_D=BLOCK_D,
FP32_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
_pat_atomic_dq(
dq_accum_ptr, original_dq, q_token, q_mask, offs_d, d_mask, head, heads, head_dim
)
return (dk, dv)
@triton.jit(
do_not_specialize=("total_lexical_tokens", "memory_slots"),
do_not_specialize_on_alignment=("total_lexical_tokens", "memory_slots"),
)
def _pat_newest_memory_owner_backward_kernel(
q_ptr,
k_memory_ptr,
v_memory_ptr,
lse_ptr,
do_ptr,
delta_ptr,
dq_accum_ptr,
dk_memory_accum_ptr,
dv_memory_accum_ptr,
row_offsets_ptr,
memory_query_start_ptr,
row_memory_start_ptr,
row_memory_length_ptr,
phase_cos_ptr,
phase_sin_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
memory_slots,
heads,
head_dim,
GLOBAL_SLOTS: tl.constexpr,
CHUNK_SIZE: tl.constexpr,
BLOCK_Q: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_D: tl.constexpr,
FP32_ROTARY_PRODUCTS: tl.constexpr = False,
):
"""One row/head owner for the newest collapsed memory-group edge."""
row = tl.program_id(0)
head = tl.program_id(1)
lexical_length = tl.load(memory_query_start_ptr + row)
memory_start = tl.load(row_memory_start_ptr + row)
memory_length = tl.load(row_memory_length_ptr + row)
owns_newest = memory_length >= GLOBAL_SLOTS
newest_start = memory_start + memory_length - GLOBAL_SLOTS
offs_k = tl.arange(0, BLOCK_K)
offs_d = tl.arange(0, BLOCK_D)
d_mask = offs_d < head_dim
newest_offset_start = 0
while newest_offset_start < GLOBAL_SLOTS:
newest_offset = newest_offset_start + offs_k
newest_abs = newest_start + newest_offset
newest_mask = owns_newest & (newest_offset < GLOBAL_SLOTS) & (newest_abs < memory_slots)
newest_k = tl.load(
k_memory_ptr
+ newest_abs[None, :] * heads * head_dim
+ head * head_dim
+ offs_d[:, None],
mask=d_mask[:, None] & newest_mask[None, :],
other=0.0,
)
newest_v = tl.load(
v_memory_ptr
+ newest_abs[:, None] * heads * head_dim
+ head * head_dim
+ offs_d[None, :],
mask=newest_mask[:, None] & d_mask[None, :],
other=0.0,
)
newest_dk = tl.zeros((BLOCK_K, BLOCK_D), tl.float32)
newest_dv = tl.zeros((BLOCK_K, BLOCK_D), tl.float32)
newest_q_start = 0
newest_q_stop = tl.where(owns_newest, lexical_length, 0)
while newest_q_start < newest_q_stop:
edge_dk, edge_dv = _pat_newest_memory_query_edge(
q_ptr,
lse_ptr,
do_ptr,
delta_ptr,
dq_accum_ptr,
newest_k,
newest_v,
newest_mask,
row,
newest_q_start,
row_offsets_ptr,
lexical_length,
phase_cos_ptr,
phase_sin_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
head,
heads,
head_dim,
CHUNK_SIZE=CHUNK_SIZE,
BLOCK_Q=BLOCK_Q,
BLOCK_K=BLOCK_K,
BLOCK_D=BLOCK_D,
FP32_ROTARY_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
newest_dk += edge_dk
newest_dv += edge_dv
newest_q_start += BLOCK_Q
newest_offsets = (
newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :]
)
newest_store_mask = newest_mask[:, None] & d_mask[None, :]
tl.atomic_add(dk_memory_accum_ptr + newest_offsets, newest_dk, mask=newest_store_mask)
tl.atomic_add(dv_memory_accum_ptr + newest_offsets, newest_dv, mask=newest_store_mask)
newest_offset_start += BLOCK_K
@triton.jit(
do_not_specialize=("total_lexical_tokens", "row_count"),
do_not_specialize_on_alignment=("total_lexical_tokens", "row_count"),
)
def _pat_token_owner_backward_kernel(
q_ptr,
k_token_ptr,
v_token_ptr,
lse_ptr,
do_ptr,
delta_ptr,
dq_accum_ptr,
dk_token_ptr,
dv_token_ptr,
row_offsets_ptr,
row_lengths_ptr,
memory_query_start_ptr,
row_exact_start_ptr,
row_exact_length_ptr,
row_exact_delta_ptr,
phase_cos_ptr,
phase_sin_ptr,
owner_rows_ptr,
owner_starts_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
row_count,
heads,
head_dim,
CHUNK_SIZE: tl.constexpr,
BLOCK_Q: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_D: tl.constexpr,
FP32_ROTARY_PRODUCTS: tl.constexpr = False,
):
owner = tl.program_id(0)
head = tl.program_id(1)
row = tl.load(owner_rows_ptr + owner)
k_start = tl.load(owner_starts_ptr + owner)
row_offset = tl.load(row_offsets_ptr + row)
row_length = tl.load(row_lengths_ptr + row)
lexical_length = tl.load(memory_query_start_ptr + row)
offs_k = tl.arange(0, BLOCK_K)
offs_d = tl.arange(0, BLOCK_D)
local_pos = k_start + offs_k
k_abs = row_offset + local_pos
k_token = _pat_canonical_token_index(
row, row_offset, local_pos, lexical_length, total_lexical_tokens, local_tail_slots
)
k_mask = local_pos < row_length
d_mask = offs_d < head_dim
k = tl.load(
k_token_ptr + k_token[None, :] * heads * head_dim + head * head_dim + offs_d[:, None],
mask=d_mask[:, None] & k_mask[None, :],
other=0.0,
)
v = tl.load(
v_token_ptr + k_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :],
mask=k_mask[:, None] & d_mask[None, :],
other=0.0,
)
dk = tl.zeros((BLOCK_K, BLOCK_D), tl.float32)
dv = tl.zeros((BLOCK_K, BLOCK_D), tl.float32)
q_start = k_start // BLOCK_Q * BLOCK_Q
while q_start < lexical_length:
edge_dk, edge_dv = _pat_token_query_edge(
q_ptr,
lse_ptr,
do_ptr,
delta_ptr,
dq_accum_ptr,
k,
v,
k_abs,
local_pos,
k_mask,
row,
q_start,
row_offsets_ptr,
row_lengths_ptr,
memory_query_start_ptr,
row_exact_start_ptr,
row_exact_length_ptr,
row_exact_delta_ptr,
phase_cos_ptr,
phase_sin_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
head,
heads,
head_dim,
EXACT_LANE=False,
EOC_QUERY=False,
CHUNK_SIZE=CHUNK_SIZE,
BLOCK_Q=BLOCK_Q,
BLOCK_K=BLOCK_K,
BLOCK_D=BLOCK_D,
FP32_ROTARY_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
dk += edge_dk
dv += edge_dv
q_start += BLOCK_Q
q_start = lexical_length
while q_start < row_length:
edge_dk, edge_dv = _pat_token_query_edge(
q_ptr,
lse_ptr,
do_ptr,
delta_ptr,
dq_accum_ptr,
k,
v,
k_abs,
local_pos,
k_mask,
row,
q_start,
row_offsets_ptr,
row_lengths_ptr,
memory_query_start_ptr,
row_exact_start_ptr,
row_exact_length_ptr,
row_exact_delta_ptr,
phase_cos_ptr,
phase_sin_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
head,
heads,
head_dim,
EXACT_LANE=False,
EOC_QUERY=True,
CHUNK_SIZE=CHUNK_SIZE,
BLOCK_Q=BLOCK_Q,
BLOCK_K=BLOCK_K,
BLOCK_D=BLOCK_D,
FP32_ROTARY_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
dk += edge_dk
dv += edge_dv
q_start += BLOCK_Q
consumer = row + 1
has_consumer = consumer < row_count
consumer_exact_start = tl.load(row_exact_start_ptr + consumer, mask=has_consumer, other=-1)
consumer_exact_length = tl.load(row_exact_length_ptr + consumer, mask=has_consumer, other=0)
owns_exact = (
has_consumer & (consumer_exact_start == row_offset) & (consumer_exact_length > k_start)
)
consumer_lexical_length = tl.load(
memory_query_start_ptr + consumer, mask=owns_exact, other=0
)
exact_q_stop = tl.minimum(consumer_lexical_length, k_start + BLOCK_K)
q_start = 0
while owns_exact & (q_start < exact_q_stop):
edge_dk, edge_dv = _pat_token_query_edge(
q_ptr,
lse_ptr,
do_ptr,
delta_ptr,
dq_accum_ptr,
k,
v,
k_abs,
local_pos,
k_mask,
consumer,
q_start,
row_offsets_ptr,
row_lengths_ptr,
memory_query_start_ptr,
row_exact_start_ptr,
row_exact_length_ptr,
row_exact_delta_ptr,
phase_cos_ptr,
phase_sin_ptr,
total_lexical_tokens,
local_tail_slots,
scale,
head,
heads,
head_dim,
EXACT_LANE=True,
EOC_QUERY=False,
CHUNK_SIZE=CHUNK_SIZE,
BLOCK_Q=BLOCK_Q,
BLOCK_K=BLOCK_K,
BLOCK_D=BLOCK_D,
FP32_ROTARY_PRODUCTS=FP32_ROTARY_PRODUCTS,
)
dk += edge_dk
dv += edge_dv
q_start += BLOCK_Q
tl.store(
dk_token_ptr + k_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :],
dk,
mask=k_mask[:, None] & d_mask[None, :],
)
tl.store(
dv_token_ptr + k_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :],
dv,
mask=k_mask[:, None] & d_mask[None, :],
)
@triton.jit(do_not_specialize=("elements",), do_not_specialize_on_alignment=("elements",))
def _pat_cast_linear_kernel(accum_ptr, output_ptr, elements, BLOCK: tl.constexpr):
offsets = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
valid = offsets < elements
values = tl.load(accum_ptr + offsets, mask=valid, other=0.0)
tl.store(output_ptr + offsets, values, mask=valid)
class _PATFn(torch.autograd.Function):
@staticmethod
def forward(
ctx: Any,
q: torch.Tensor,
k_memory: torch.Tensor,
v_memory: torch.Tensor,
k_token: torch.Tensor,
v_token: torch.Tensor,
row_offsets: torch.Tensor,
row_lengths: torch.Tensor,
memory_query_start: torch.Tensor,
row_memory_start_abs: torch.Tensor,
row_memory_length: torch.Tensor,
row_token_memory_length: torch.Tensor,
row_exact_start_abs: torch.Tensor,
row_exact_length: torch.Tensor,
row_exact_query_phase_delta: torch.Tensor,
scale: float,
plan: PATPlan,
) -> torch.Tensor:
output = torch.empty_like(q)
lse = torch.empty((int(q.size(0)), int(q.size(1))), device=q.device, dtype=torch.float32)
config = plan.config
block_dimension = _block_d(plan.head_dim)
token_output = (
torch.empty(q.shape, device=q.device, dtype=torch.float32)
if plan.memory_slots
else output
)
_pat_token_forward_kernel[plan.query_tiles, plan.heads](
q,
k_token,
v_token,
token_output,
lse,
row_offsets,
row_lengths,
memory_query_start,
row_exact_start_abs,
row_exact_length,
row_exact_query_phase_delta,
plan.memory_phase_cos,
plan.memory_phase_sin,
plan.q_tile_rows,
plan.q_tile_starts,
plan.total_lexical_tokens,
plan.local_tail_slots,
float(scale),
plan.heads,
plan.head_dim,
BLOCK_Q=int(config.block_q),
BLOCK_K_TOKEN=int(config.block_k_token),
BLOCK_D=block_dimension,
num_warps=int(config.warps),
num_stages=int(config.stages),
FP32_ROTARY_PRODUCTS=True,
)
if plan.memory_slots:
_pat_newest_forward_kernel[plan.row_count, plan.heads](
q,
k_memory,
v_memory,
token_output,
lse,
row_offsets,
memory_query_start,
row_memory_start_abs,
row_memory_length,
plan.memory_phase_cos,
plan.memory_phase_sin,
plan.total_lexical_tokens,
plan.local_tail_slots,
float(scale),
plan.memory_slots,
plan.heads,
plan.head_dim,
GLOBAL_SLOTS=int(plan.global_slots),
CHUNK_SIZE=int(config.chunk_size),
BLOCK_Q=int(config.block_q),
BLOCK_K=int(config.block_k_token),
BLOCK_D=block_dimension,
num_warps=int(config.warps),
num_stages=int(config.stages),
FP32_ROTARY_PRODUCTS=True,
)
memory_query_tiles = plan.memory_query_tiles
_pat_memory_forward_kernel[memory_query_tiles, plan.heads](
q,
k_memory,
v_memory,
token_output,
output,
lse,
row_offsets,
memory_query_start,
row_memory_start_abs,
row_memory_length,
plan.memory_phase_cos,
plan.memory_phase_sin,
plan.token_row_ids,
plan.memory_tile_union_start,
plan.memory_tile_union_end,
plan.memory_tile_interior_start,
plan.memory_tile_interior_end,
plan.total_lexical_tokens,
plan.local_tail_slots,
float(scale),
plan.token_slots,
plan.memory_slots,
plan.heads,
plan.head_dim,
GLOBAL_SLOTS=int(plan.global_slots),
CHUNK_SIZE=int(config.chunk_size),
BLOCK_Q=_PAT_MEMORY_BLOCK_Q,
BLOCK_K=int(config.block_k_memory),
BLOCK_D=block_dimension,
num_warps=_PAT_MEMORY_FORWARD_WARPS,
num_stages=int(config.stages),
FP32_ROTARY_PRODUCTS=True,
)
ctx.save_for_backward(
q,
k_memory,
v_memory,
k_token,
v_token,
output,
lse,
row_offsets,
row_lengths,
memory_query_start,
row_memory_start_abs,
row_memory_length,
row_token_memory_length,
row_exact_start_abs,
row_exact_length,
row_exact_query_phase_delta,
)
ctx.scale = float(scale)
ctx.plan = plan
return output
@staticmethod
def backward(ctx: Any, grad_output: torch.Tensor) -> tuple[Any, ...]:
(
q,
k_memory,
v_memory,
k_token,
v_token,
output,
lse,
row_offsets,
row_lengths,
memory_query_start,
row_memory_start_abs,
row_memory_length,
_row_token_memory_length,
row_exact_start_abs,
row_exact_length,
row_exact_query_phase_delta,
) = ctx.saved_tensors[:16]
plan: PATPlan = ctx.plan
config = plan.config
block_dimension = _block_d(plan.head_dim)
do = grad_output.contiguous()
delta = torch.empty((plan.token_slots, plan.heads), device=q.device, dtype=torch.float32)
delta_tiles = triton.cdiv(plan.token_slots, int(config.block_q))
_pat_delta_kernel[delta_tiles, plan.heads](
output,
do,
delta,
row_offsets,
memory_query_start,
plan.token_row_ids,
plan.total_lexical_tokens,
plan.local_tail_slots,
plan.token_slots,
plan.heads,
plan.head_dim,
BLOCK_Q=int(config.block_q),
BLOCK_D=block_dimension,
num_warps=int(config.warps),
num_stages=int(config.stages),
)
dq_accum = (
torch.empty(q.shape, device=q.device, dtype=torch.float32)
if plan.memory_slots
else torch.zeros(q.shape, device=q.device, dtype=torch.float32)
)
dk_memory = torch.empty_like(k_memory)
dv_memory = torch.empty_like(v_memory)
dk_token = torch.empty_like(k_token, dtype=k_token.dtype)
dv_token = torch.empty_like(v_token)
dk_memory_accum = torch.zeros(k_memory.shape, device=k_memory.device, dtype=torch.float32)
dv_memory_accum = torch.zeros(v_memory.shape, device=v_memory.device, dtype=torch.float32)
if plan.memory_slots:
memory_query_tiles = plan.memory_query_tiles
if memory_query_tiles:
query_block_k = _memory_query_block_k(int(config.block_k_memory))
dk_descriptor = create_ragged_descriptor(
dk_memory_accum, [query_block_k, 1, block_dimension]
)
dv_descriptor = create_ragged_descriptor(
dv_memory_accum, [query_block_k, 1, block_dimension]
)
_pat_memory_query_owner_backward_kernel[memory_query_tiles, plan.heads](
dk_descriptor,
dv_descriptor,
q,
k_memory,
v_memory,
lse,
do,
delta,
dq_accum,
row_offsets,
memory_query_start,
plan.memory_phase_cos,
plan.memory_phase_sin,
plan.token_row_ids,
plan.memory_tile_union_start,
plan.memory_tile_union_end,
plan.total_lexical_tokens,
plan.local_tail_slots,
row_memory_start_abs,
row_memory_length,
float(ctx.scale),
plan.token_slots,
plan.memory_slots,
plan.heads,
plan.head_dim,
GLOBAL_SLOTS=int(plan.global_slots),
CHUNK_SIZE=int(config.chunk_size),
BLOCK_Q=_PAT_MEMORY_BLOCK_Q,
BLOCK_K=query_block_k,
BLOCK_D=block_dimension,
num_warps=_PAT_MEMORY_BACKWARD_WARPS,
num_stages=int(config.stages),
FP32_ROTARY_PRODUCTS=True,
)
_pat_newest_memory_owner_backward_kernel[plan.row_count, plan.heads](
q,
k_memory,
v_memory,
lse,
do,
delta,
dq_accum,
dk_memory_accum,
dv_memory_accum,
row_offsets,
memory_query_start,
row_memory_start_abs,
row_memory_length,
plan.memory_phase_cos,
plan.memory_phase_sin,
plan.total_lexical_tokens,
plan.local_tail_slots,
float(ctx.scale),
plan.memory_slots,
plan.heads,
plan.head_dim,
GLOBAL_SLOTS=int(plan.global_slots),
CHUNK_SIZE=int(config.chunk_size),
BLOCK_Q=int(config.block_q),
BLOCK_K=int(config.block_k_token),
BLOCK_D=block_dimension,
num_warps=_PAT_TOKEN_BACKWARD_WARPS,
num_stages=int(config.stages),
FP32_ROTARY_PRODUCTS=True,
)
if plan.token_tiles:
_pat_token_owner_backward_kernel[plan.token_tiles, plan.heads](
q,
k_token,
v_token,
lse,
do,
delta,
dq_accum,
dk_token,
dv_token,
row_offsets,
row_lengths,
memory_query_start,
row_exact_start_abs,
row_exact_length,
row_exact_query_phase_delta,
plan.memory_phase_cos,
plan.memory_phase_sin,
plan.token_owner_rows,
plan.token_owner_starts,
plan.total_lexical_tokens,
plan.local_tail_slots,
float(ctx.scale),
plan.row_count,
plan.heads,
plan.head_dim,
CHUNK_SIZE=int(config.chunk_size),
BLOCK_Q=int(config.block_q),
BLOCK_K=int(config.block_k_token),
BLOCK_D=block_dimension,
num_warps=_PAT_TOKEN_BACKWARD_WARPS,
num_stages=int(config.stages),
FP32_ROTARY_PRODUCTS=True,
)
if plan.memory_slots:
memory_elements = int(k_memory.numel())
cast_grid = (triton.cdiv(memory_elements, 256),)
_pat_cast_linear_kernel[cast_grid](
dk_memory_accum, dk_memory, memory_elements, BLOCK=256, num_warps=4
)
_pat_cast_linear_kernel[cast_grid](
dv_memory_accum, dv_memory, memory_elements, BLOCK=256, num_warps=4
)
dq = torch.empty_like(q)
elements = int(q.numel())
_pat_cast_linear_kernel[triton.cdiv(elements, 256),](
dq_accum, dq, elements, BLOCK=256, num_warps=4
)
return (
dq,
dk_memory,
dv_memory,
dk_token,
dv_token,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
)
def attention(
*,
q_canonical: torch.Tensor,
k_memory: torch.Tensor,
v_memory: torch.Tensor,
k_token_canonical: torch.Tensor,
v_token_canonical: torch.Tensor,
scale: float,
plan: PATPlan,
) -> torch.Tensor:
"""Launch the one canonical lexical-prefix/tail-suffix kernel core."""
return _PATFn.apply(
q_canonical,
k_memory,
v_memory,
k_token_canonical,
v_token_canonical,
plan.row_offsets,
plan.row_lengths,
plan.memory_query_start,
plan.row_memory_start_abs,
plan.row_memory_length,
plan.row_token_memory_length,
plan.row_exact_start_abs,
plan.row_exact_length,
plan.row_exact_query_phase_delta,
float(scale),
plan,
)
@dataclass(frozen=True)
class _PATLayoutKey:
full: tuple[Any, ...]
fixed: tuple[Any, ...]
context: tuple[Any, ...]
layer_zero: bool
dynamic_local_slots: int | None
dynamic_global_slots: int | None
def _parse_pat_attention_layout_key(value: Any) -> _PATLayoutKey:
"""Parse the one exact key grammar emitted by packed production training."""
try:
hash(value)
except TypeError as exc:
raise ValueError("PAT production planner key must be immutable and hashable") from exc
if not isinstance(value, tuple):
raise TypeError("PAT production planner key must be a tuple")
full = value
layer_zero = False
root = value
if len(root) == 2 and root[1] == "layer0_local_attention":
layer_zero = True
root = root[0]
if not isinstance(root, tuple) or len(root) != 11 or root[1] != "token_level_context":
raise ValueError(
"PAT planner key must be exactly token_level_context, optionally wrapped once by layer0_local_attention"
)
context = root
base = context[0]
dynamic_local_slots: int | None = None
dynamic_global_slots: int | None = None
if isinstance(base, tuple) and len(base) == 4 and (base[1] == "dynamic_memory"):
dynamic_local_slots = _required_plain_int("dynamic local slots", base[2], minimum=1)
dynamic_global_slots = _required_plain_int("dynamic global slots", base[3], minimum=1)
base = base[0]
if not isinstance(base, tuple) or len(base) != 10 or base[0] != "packed_training":
raise ValueError("PAT planner key must terminate in exactly one packed_training key")
return _PATLayoutKey(
full=full,
fixed=base,
context=context,
layer_zero=layer_zero,
dynamic_local_slots=dynamic_local_slots,
dynamic_global_slots=dynamic_global_slots,
)
def _required_plain_int(name: str, value: Any, *, minimum: int = 0) -> int:
if isinstance(value, bool) or not isinstance(value, int) or int(value) < minimum:
raise ValueError(f"PAT trusted planner key requires {name} >= {minimum}; got {value!r}")
return int(value)
def _cached_fixed_row_geometry(
*,
fixed_key: tuple[Any, ...],
lexical_lengths: Sequence[int],
chunk_indices: Sequence[int],
device: torch.device,
) -> torch.Tensor:
"""Cache the planner key's immutable per-row validator on its CUDA stream."""
stream = int(torch.cuda.current_stream(device).cuda_stream)
key = (fixed_key, device, stream)
with _PAT_FIXED_ROW_CACHE_LOCK:
cached = _PAT_FIXED_ROW_CACHE.get(key)
if cached is not None:
_PAT_FIXED_ROW_CACHE.move_to_end(key)
return cached
with torch.inference_mode(False):
cached = torch.tensor(
[*lexical_lengths, *chunk_indices], device=device, dtype=torch.int64
).contiguous()
_PAT_FIXED_ROW_CACHE[key] = cached
while len(_PAT_FIXED_ROW_CACHE) > _PAT_FIXED_ROW_CACHE_MAX_ENTRIES:
_PAT_FIXED_ROW_CACHE.popitem(last=False)
return cached
def _materialize_pat_attention_layout(
physical_layout: PackedLayout | FixedGeometry,
*,
local_slots: int,
global_slots: int,
chunk_size: int,
max_memory_size: int,
block_q: int = 16,
block_k_memory: int = 64,
block_k_token: int = 16,
_trusted_internal: object | None = None,
) -> _PATMaterializedLayout:
"""Build one live PAT signature in one slab and one Triton launch."""
trusted_fixed = _trusted_internal is _PAT_TRUSTED_MATERIALIZER
if trusted_fixed:
if not isinstance(physical_layout, FixedGeometry):
raise TypeError("trusted PAT materialization requires fixed geometry")
elif not isinstance(physical_layout, PackedLayout):
raise TypeError("physical_layout must be PackedLayout")
if not _HAS_TRITON:
raise RuntimeError("PAT layout materialization requires Triton")
local_width = _required_plain_int("local_slots", local_slots, minimum=1)
global_width = _required_plain_int("global_slots", global_slots, minimum=1)
chunk = _required_plain_int("chunk_size", chunk_size, minimum=1)
max_memory = _required_plain_int("max_memory_size", max_memory_size, minimum=4)
query_block = _power_of_two("block_q", block_q)
memory_block = _power_of_two("block_k_memory", block_k_memory)
token_block = _power_of_two("block_k_token", block_k_token)
if query_block < 16 or query_block > 128:
raise ValueError("block_q must be in [16, 128]")
if token_block < 16 or token_block > 128:
raise ValueError("block_k_token must be in [16, 128]")
if memory_block < 16 or memory_block > 128:
raise ValueError("block_k_memory must be in [16, 128]")
if _trusted_internal not in {None, _PAT_TRUSTED_MATERIALIZER}:
raise ValueError("invalid PAT materializer provenance request")
if chunk not in _SUPPORTED_CHUNK_SIZES:
raise ValueError(f"PAT layout materialization supports chunk_size 16 or 32; got {chunk}")
device = physical_layout.row_lengths.device
if device.type != "cuda":
raise RuntimeError("PAT fused layout materialization supports CUDA execution only")
_require_pat_hopper(device)
rows = int(physical_layout.row_count)
physical_tokens = int(physical_layout.token_count)
physical_slots = int(physical_layout.memory_tail_slots)
if rows <= 0 or physical_tokens <= 0 or physical_slots <= 0:
raise ValueError(
"PAT fused layout materialization requires nonempty rows and a positive physical EOC width"
)
if not trusted_fixed and physical_layout.row_pos_to_flat_is_identity is not True:
raise ValueError("PAT fused layout materialization requires identity-packed rows")
max_lexical_length = int(physical_layout.max_row_length) - physical_slots
if max_lexical_length <= 0 or max_lexical_length > chunk:
raise ValueError("PAT physical max lexical row length must be in [1, chunk_size]")
if int(physical_layout.max_chunk_index) < 0:
raise ValueError("PAT physical max_chunk_index must be non-negative")
physical_row_offsets = physical_layout.row_offsets
physical_row_lengths = physical_layout.row_lengths
physical_memory_query_start = (
physical_layout.row_content_lengths if trusted_fixed else physical_layout.memory_query_start
)
physical_eoc = physical_layout.eoc_abs_idx
physical_row_chunk_or_piece = (
physical_layout.chunk_piece_id if trusted_fixed else physical_layout.row_chunk_indices
)
physical_piece_chunk_base = (
physical_layout.piece_chunk_base if trusted_fixed else physical_row_offsets
)
physical_row_pos_to_flat = (
physical_row_offsets if trusted_fixed else physical_layout.row_pos_to_flat
)
physical_memory_start = (
physical_row_offsets if trusted_fixed else physical_layout.row_memory_start_abs
)
physical_memory_length = (
physical_row_offsets if trusted_fixed else physical_layout.row_memory_length
)
expected_tensors = [
("row_offsets", physical_row_offsets, (rows,)),
("row_lengths", physical_row_lengths, (rows,)),
("memory_query_start", physical_memory_query_start, (rows,)),
("eoc_abs_idx", physical_eoc, (rows, physical_slots)),
("row_chunk_indices", physical_row_chunk_or_piece, (rows,)),
]
if trusted_fixed:
expected_tensors.append(
(
"piece_chunk_base",
physical_piece_chunk_base,
(int(physical_piece_chunk_base.numel()),),
)
)
else:
expected_tensors.extend(
(
("row_pos_to_flat", physical_row_pos_to_flat, (physical_tokens,)),
("row_memory_start_abs", physical_memory_start, (rows,)),
("row_memory_length", physical_memory_length, (rows,)),
)
)
for name, tensor, shape in expected_tensors:
if (
not torch.is_tensor(tensor)
or tuple(tensor.shape) != shape
or tensor.dtype != torch.int64
or (tensor.device != device)
or (not tensor.is_contiguous())
):
raise ValueError(
f"PAT physical {name} must be a contiguous int64 {list(shape)} tensor on {device}"
)
fixed_key = physical_layout.planner_cache_key
if (
not isinstance(fixed_key, tuple)
or len(fixed_key) != 10
or fixed_key[0] != "packed_training"
or (type(fixed_key[1]) is not bool)
):
raise ValueError(
"PAT physical planner key must be packed_training with an explicit include_piece_start_bos flag"
)
key_rows = _required_plain_int("row_count", fixed_key[2], minimum=1)
key_max_row = _required_plain_int("physical max row length", fixed_key[3], minimum=1)
key_tokens = _required_plain_int("physical token count", fixed_key[4], minimum=1)
key_chunk = _required_plain_int("chunk_size", fixed_key[5], minimum=1)
key_eoc = _required_plain_int("physical EOC width", fixed_key[6], minimum=1)
key_max_memory = _required_plain_int("max_memory_size", fixed_key[7], minimum=4)
if (
key_rows != rows
or key_max_row != int(physical_layout.max_row_length)
or key_tokens != physical_tokens
or (key_chunk != chunk)
or (key_eoc != physical_slots)
or (key_max_memory != max_memory)
):
raise ValueError("PAT physical layout disagrees with its fixed-training planner key")
chunks_per_piece = fixed_key[8]
short_rows_raw = fixed_key[9]
if not isinstance(chunks_per_piece, tuple) or not chunks_per_piece:
raise ValueError("PAT fixed-training key requires chunks_per_piece")
piece_counts = tuple(
_required_plain_int("chunks_per_piece entry", value, minimum=1)
for value in chunks_per_piece
)
if sum(piece_counts) != rows or not isinstance(short_rows_raw, tuple):
raise ValueError("PAT fixed-training key has malformed piece geometry")
piece_ends: set[int] = set()
piece_cursor = 0
for count in piece_counts:
piece_cursor += count
piece_ends.add(piece_cursor)
short_rows: dict[int, int] = {}
previous_short_row = -1
for entry in short_rows_raw:
if not isinstance(entry, tuple) or len(entry) != 2:
raise ValueError("PAT short-row entries must be pairs")
row = _required_plain_int("short row index", entry[0])
length = _required_plain_int("short row length", entry[1], minimum=1)
if (
row >= rows
or row <= previous_short_row
or length >= chunk
or (row + 1 not in piece_ends)
):
raise ValueError("PAT fixed-training key contains an invalid short row")
short_rows[row] = length
previous_short_row = row
expected_lexical_lengths = [short_rows.get(row, chunk) for row in range(rows)]
expected_chunk_indices = [
chunk_index for piece_count in piece_counts for chunk_index in range(piece_count)
]
expected_row_geometry = _cached_fixed_row_geometry(
fixed_key=fixed_key,
lexical_lengths=expected_lexical_lengths,
chunk_indices=expected_chunk_indices,
device=device,
)
total_lexical_tokens = physical_tokens - rows * physical_slots
expected_lexical_tokens = rows * chunk - sum(chunk - length for length in short_rows.values())
if total_lexical_tokens <= 0 or total_lexical_tokens != expected_lexical_tokens:
raise ValueError("PAT physical token count disagrees with fixed-training row lengths")
target_tokens = total_lexical_tokens + rows * local_width
target_max_row = max_lexical_length + local_width
full_lexical_q_tiles = (chunk + query_block - 1) // query_block
tail_q_tiles = (local_width + query_block - 1) // query_block
query_tile_capacity = rows * (full_lexical_q_tiles + tail_q_tiles)
query_tiles = rows * (full_lexical_q_tiles + tail_q_tiles) - sum(
full_lexical_q_tiles - (length + query_block - 1) // query_block
for length in short_rows.values()
)
full_token_tiles = (chunk + local_width + token_block - 1) // token_block
token_tile_capacity = rows * full_token_tiles
token_tiles = rows * full_token_tiles - sum(
full_token_tiles - (length + local_width + token_block - 1) // token_block
for length in short_rows.values()
)
if query_tiles <= 0 or token_tiles <= 0:
raise RuntimeError("PAT materializer derived empty launch geometry")
memory_query_tiles = math.ceil(target_tokens / _PAT_MEMORY_BLOCK_Q)
if memory_query_tiles <= 0:
raise RuntimeError("PAT materializer derived empty memory launch geometry")
planner_cache_key = (
(fixed_key, "dynamic_memory", local_width, global_width),
"token_level_context",
2,
max_memory,
chunk,
1,
global_width,
"packed_local",
"fixed_token_window",
False,
True,
)
_parse_pat_attention_layout_key(planner_cache_key)
section_counts = (
("row_offsets", rows),
("row_pos_to_flat", target_tokens),
("row_lengths", rows),
("row_chunk_indices", rows),
("memory_query_start", rows),
("row_memory_start_abs", rows),
("row_memory_length", rows),
("local_positions", target_tokens),
("query_positions", target_tokens),
("eoc_abs_idx", rows * local_width),
("memory_positions", rows * global_width),
("row_token_memory_length", rows),
("row_exact_start_abs", rows),
("row_exact_length", rows),
("row_exact_query_phase_delta", rows),
("row_compressed_eoc_local_key_phase_delta", rows),
("canonical_order", target_tokens),
("logical_order", target_tokens),
("canonical_positions", target_tokens),
("canonical_key_positions", target_tokens),
("token_row_ids", target_tokens),
("q_tile_rows", query_tile_capacity),
("q_tile_starts", query_tile_capacity),
("token_owner_rows", token_tile_capacity),
("token_owner_starts", token_tile_capacity),
("memory_tile_union_start", memory_query_tiles),
("memory_tile_union_end", memory_query_tiles),
("memory_tile_interior_start", memory_query_tiles),
("memory_tile_interior_end", memory_query_tiles),
("q_tile_counter", 1),
("token_owner_counter", 1),
("validation_result", 1),
)
section_offsets: dict[str, tuple[int, int]] = {}
storage_elements = 0
for name, count in section_counts:
section_offsets[name] = (storage_elements, storage_elements + count)
storage_elements += count
storage = torch.ones((storage_elements,), device=device, dtype=torch.int64)
block_row = 1 << (chunk + max(physical_slots, local_width) - 1).bit_length()
_pat_materialize_layout_kernel[max(rows, memory_query_tiles),](
physical_row_offsets,
physical_row_pos_to_flat,
physical_row_lengths,
physical_memory_query_start,
physical_memory_start,
physical_memory_length,
physical_eoc,
physical_row_chunk_or_piece,
physical_piece_chunk_base,
expected_row_geometry,
storage,
rows,
physical_tokens,
target_tokens,
total_lexical_tokens,
query_tile_capacity,
token_tile_capacity,
memory_query_tiles,
int(physical_piece_chunk_base.numel()),
PHYSICAL_SLOTS=physical_slots,
LOCAL_SLOTS=local_width,
GLOBAL_SLOTS=global_width,
CHUNK_SIZE=chunk,
MAX_MEMORY_SIZE=max_memory,
BLOCK_Q=query_block,
BLOCK_K_MEMORY=memory_block,
BLOCK_K_TOKEN=token_block,
BLOCK_MEMORY_QUERY=_PAT_MEMORY_BLOCK_Q,
BLOCK_ROW=block_row,
TRUSTED_FIXED=_trusted_internal is _PAT_TRUSTED_MATERIALIZER,
num_warps=2 if block_row <= 64 else 4,
num_stages=1,
)
def section(name: str) -> torch.Tensor:
start, stop = section_offsets[name]
return storage.narrow(0, start, stop - start)
def exact_section(name: str, count: int) -> torch.Tensor:
return section(name).narrow(0, 0, int(count))
validation_result = section("validation_result")
if _trusted_internal is None:
if int(validation_result.item()) != 1:
raise ValueError("PAT physical layout values are malformed")
else:
torch._assert_async(
validation_result, "PAT fixed-training layout disagrees with its exhaustive planner key"
)
layout = PackedLayout(
row_offsets=section("row_offsets"),
row_pos_to_flat=section("row_pos_to_flat"),
row_lengths=section("row_lengths"),
row_chunk_indices=section("row_chunk_indices"),
memory_query_start=section("memory_query_start"),
row_memory_start_abs=section("row_memory_start_abs"),
row_memory_length=section("row_memory_length"),
local_positions=section("local_positions"),
eoc_abs_idx=section("eoc_abs_idx").view(rows, local_width),
memory_positions=section("memory_positions"),
row_pos_to_flat_is_identity=True,
max_row_length=target_max_row,
max_chunk_index=int(physical_layout.max_chunk_index),
query_positions=section("query_positions"),
row_token_memory_length=section("row_token_memory_length"),
row_exact_start_abs=section("row_exact_start_abs"),
row_exact_length=section("row_exact_length"),
row_exact_query_phase_delta=section("row_exact_query_phase_delta"),
row_compressed_eoc_local_key_phase_delta=section(
"row_compressed_eoc_local_key_phase_delta"
),
planner_cache=None if trusted_fixed else physical_layout.planner_cache,
planner_cache_key=planner_cache_key,
token_context_schedule="fixed_token_window",
fixed_window_contiguous_position_width=1,
chronological_fixed_window=True,
global_memory_slots_per_chunk=global_width,
)
return _PATMaterializedLayout(
layout=layout,
canonical_order=section("canonical_order"),
logical_order=section("logical_order"),
canonical_positions=section("canonical_positions"),
canonical_key_positions=section("canonical_key_positions"),
q_tile_rows=exact_section("q_tile_rows", query_tiles),
q_tile_starts=exact_section("q_tile_starts", query_tiles),
token_row_ids=section("token_row_ids"),
memory_tile_union_start=section("memory_tile_union_start"),
memory_tile_union_end=section("memory_tile_union_end"),
memory_tile_interior_start=section("memory_tile_interior_start"),
memory_tile_interior_end=section("memory_tile_interior_end"),
token_owner_rows=exact_section("token_owner_rows", token_tiles),
token_owner_starts=exact_section("token_owner_starts", token_tiles),
block_q=query_block,
block_k_memory=memory_block,
block_k_token=token_block,
total_lexical_tokens=total_lexical_tokens,
global_slots=global_width,
storage=storage,
provenance=_PATMaterializationProvenance(
storage_identity=id(storage),
device=device,
stream=int(torch.cuda.current_stream(device).cuda_stream),
),
)
def materialize_layout(
fixed_geometry: FixedGeometry, *, local_slots: int, global_slots: int, config: KernelConfig
) -> _PATMaterializedLayout:
"""Internal one-launch materializer whose output may bind without revalidation."""
if not isinstance(config, KernelConfig):
raise TypeError("config must be KernelConfig")
return _materialize_pat_attention_layout(
fixed_geometry,
local_slots=local_slots,
global_slots=global_slots,
chunk_size=int(config.chunk_size),
max_memory_size=int(config.max_memory_size),
block_q=int(config.block_q),
block_k_memory=int(config.block_k_memory),
block_k_token=int(config.block_k_token),
_trusted_internal=_PAT_TRUSTED_MATERIALIZER,
)
def _cached_pat_attention_phases(
*, config: KernelConfig, device: torch.device, dtype: torch.dtype, head_dim: int
) -> tuple[torch.Tensor, torch.Tensor]:
"""Return the only geometry-independent live tensors retained across batches."""
stream = int(torch.cuda.current_stream(device).cuda_stream) if device.type == "cuda" else 0
key = (config, device, dtype, int(head_dim), stream)
with _PAT_PHASE_CACHE_LOCK:
cached = _PAT_PHASE_CACHE.get(key)
if cached is not None:
_PAT_PHASE_CACHE.move_to_end(key)
return cached
block_dimension = _validate_pat_head_dim(int(head_dim))
dimensions = torch.arange(block_dimension, device=device, dtype=torch.float32)
even_dimensions = torch.div(dimensions, 2, rounding_mode="floor") * 2
inverse_frequency = torch.exp(-math.log(ROPE_BASE) * even_dimensions / int(head_dim))
deltas = -torch.arange(int(config.chunk_size) + 1, device=device, dtype=torch.float32)
angles = deltas[:, None] * inverse_frequency[None, :]
cached = (
torch.cos(angles).to(dtype=dtype).contiguous(),
torch.sin(angles).to(dtype=dtype).contiguous(),
)
_PAT_PHASE_CACHE[key] = cached
while len(_PAT_PHASE_CACHE) > _PAT_PHASE_CACHE_MAX_ENTRIES:
_PAT_PHASE_CACHE.popitem(last=False)
return cached
def bind_plan(
materialized: _PATMaterializedLayout,
*,
heads: int,
head_dim: int,
dtype: torch.dtype,
config: KernelConfig,
layer_zero: bool = False,
) -> PATPlan:
"""Bind one internal materialization without O(rows) work or GPU validation."""
if not isinstance(materialized, _PATMaterializedLayout):
raise TypeError("materialized must be a PAT fused materialization")
provenance = materialized.provenance
if (
provenance is None
or provenance.storage_identity != id(materialized.storage)
or provenance.device != materialized.storage.device
):
raise ValueError("PAT plan binding requires trusted materializer provenance")
device = materialized.storage.device
current_stream = int(torch.cuda.current_stream(device).cuda_stream)
if provenance.stream != current_stream:
raise ValueError("PAT trusted materialization must be bound on its producing CUDA stream")
if not isinstance(config, KernelConfig):
raise TypeError("config must be KernelConfig")
if (
int(config.block_q) != materialized.block_q
or int(config.block_k_memory) != materialized.block_k_memory
or int(config.block_k_token) != materialized.block_k_token
or (int(config.chunk_size) != int(materialized.layout.planner_cache_key[4]))
or (int(config.max_memory_size) != int(materialized.layout.planner_cache_key[3]))
):
raise ValueError("PAT config disagrees with trusted materialized geometry")
head_count = _required_plain_int("heads", heads, minimum=1)
dimension = _required_plain_int("head_dim", head_dim, minimum=1)
_validate_pat_head_dim(dimension)
if dtype not in _SUPPORTED_DTYPES:
raise ValueError(f"unsupported PAT dtype: {dtype}")
layout = materialized.layout
rows = int(layout.row_count)
token_slots = int(layout.token_count)
expected_storage_pointer = materialized.storage.untyped_storage().data_ptr()
bound_tensors = (
layout.row_offsets,
layout.row_pos_to_flat,
layout.row_lengths,
layout.memory_query_start,
layout.row_memory_start_abs,
layout.row_memory_length,
layout.row_token_memory_length,
layout.row_exact_start_abs,
layout.row_exact_length,
layout.row_exact_query_phase_delta,
layout.row_compressed_eoc_local_key_phase_delta,
materialized.q_tile_rows,
materialized.q_tile_starts,
materialized.token_row_ids,
materialized.canonical_order,
materialized.logical_order,
materialized.memory_tile_union_start,
materialized.memory_tile_union_end,
materialized.memory_tile_interior_start,
materialized.memory_tile_interior_end,
materialized.token_owner_rows,
materialized.token_owner_starts,
materialized.canonical_key_positions,
layout.query_positions,
)
if any(value is None for value in bound_tensors):
raise ValueError("PAT trusted materialization is missing plan metadata")
if any(
tensor.untyped_storage().data_ptr() != expected_storage_pointer
for tensor in bound_tensors
if torch.is_tensor(tensor)
):
raise ValueError("PAT trusted plan metadata escaped its materializer slab")
assert layout.row_token_memory_length is not None
assert layout.row_exact_start_abs is not None
assert layout.row_exact_length is not None
assert layout.row_exact_query_phase_delta is not None
assert layout.row_compressed_eoc_local_key_phase_delta is not None
zero_rows = layout.row_compressed_eoc_local_key_phase_delta
memory_start = zero_rows if layer_zero else layout.row_memory_start_abs
memory_length = zero_rows if layer_zero else layout.row_memory_length
token_memory_length = zero_rows if layer_zero else layout.row_token_memory_length
metadata = (
layout.row_offsets,
layout.row_pos_to_flat,
layout.row_lengths,
layout.row_chunk_indices,
layout.memory_query_start,
memory_start,
memory_length,
token_memory_length,
layout.row_exact_start_abs,
layout.row_exact_length,
layout.row_exact_query_phase_delta,
layout.row_compressed_eoc_local_key_phase_delta,
)
phase_cos, phase_sin = _cached_pat_attention_phases(
config=config, device=device, dtype=dtype, head_dim=dimension
)
memory_slots = 0 if layer_zero else rows * materialized.global_slots
if layer_zero:
empty_memory_tiles = materialized.storage.narrow(0, 0, 0)
memory_tile_union_start = empty_memory_tiles
memory_tile_union_end = empty_memory_tiles
memory_tile_interior_start = empty_memory_tiles
memory_tile_interior_end = empty_memory_tiles
else:
memory_tile_union_start = materialized.memory_tile_union_start
memory_tile_union_end = materialized.memory_tile_union_end
memory_tile_interior_start = materialized.memory_tile_interior_start
memory_tile_interior_end = materialized.memory_tile_interior_end
return PATPlan(
config=config,
row_count=rows,
token_slots=token_slots,
total_lexical_tokens=materialized.total_lexical_tokens,
local_tail_slots=int(layout.memory_tail_slots),
memory_slots=memory_slots,
global_slots=0 if layer_zero else int(materialized.global_slots),
heads=head_count,
head_dim=dimension,
dtype=dtype,
row_offsets=metadata[0],
row_pos_to_flat=metadata[1],
row_lengths=metadata[2],
row_chunk_indices=metadata[3],
memory_query_start=metadata[4],
row_memory_start_abs=metadata[5],
row_memory_length=metadata[6],
row_token_memory_length=metadata[7],
row_exact_start_abs=metadata[8],
row_exact_length=metadata[9],
row_exact_query_phase_delta=metadata[10],
row_compressed_eoc_local_key_phase_delta=metadata[11],
q_tile_rows=materialized.q_tile_rows,
q_tile_starts=materialized.q_tile_starts,
token_row_ids=materialized.token_row_ids,
canonical_order=materialized.canonical_order,
logical_order=materialized.logical_order,
memory_tile_union_start=memory_tile_union_start,
memory_tile_union_end=memory_tile_union_end,
memory_tile_interior_start=memory_tile_interior_start,
memory_tile_interior_end=memory_tile_interior_end,
token_owner_rows=materialized.token_owner_rows,
token_owner_starts=materialized.token_owner_starts,
memory_phase_cos=phase_cos,
memory_phase_sin=phase_sin,
metadata_signature=(),
canonical_metadata=materialized.storage.narrow(0, 0, 0),
metadata_validation_result=materialized.storage.narrow(
0, int(materialized.storage.numel()) - 1, 1
),
metadata_validation_stream=provenance.stream,
_trusted_materialization=provenance,
)
|