File size: 333,909 Bytes
919fd68 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 | """Resynthesis frozen vocabulary/feature-parent loader.
Resynthesis is NOT an identity wrapper. It owns one immutable inherited
multi-gig parent generation (hidden_size=4096, 32 layers, linear+full attention
hybrid, vocab=248320, native >4M context), freezes it, and exposes immutable
features plus the vocabulary projection for the much larger additive
ResynthesisScienceLayerStack + NoNE/RBO/Fabric graph. Parent answer logits,
confidence, stopping, and retention are never execution authorities.
The original artifact and source-era tensor names remain verifiable lineage;
active loading resolves only through the Resynthesis-owned generation root.
Tensor-native boundary: the loader returns frozen hidden tensors and the base
config. No Dict[str, Any] on the hot path — config metadata is a typed
dataclass.
"""
from __future__ import annotations
import copy
import importlib
import importlib.machinery
import importlib.util
import hashlib
import inspect
import json
import signal
import sys
import tempfile
from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager
from dataclasses import dataclass, replace
from pathlib import Path
from types import FunctionType
from typing import Any, cast
import torch
import torch.nn as nn
import torch.nn.functional as F
from resynthesis.base_forward_cache import (
FrozenBackboneCacheAuthority,
FrozenBackbonePrefillPacket,
frozen_backbone_position_policy_sha256_boundary,
)
from resynthesis.science_layers import online_softmax_last_token_pool
from resynthesis.config import (
DUAL_CHUNK_LOCAL_SIZE,
DUAL_CHUNK_PRETRAIN_LENGTH,
NATIVE_ATTENTION_POSITION_APERTURE,
PRETRAINED_ROPE_BAND_TOKENS,
RESYNTHESIS_FULL_ATTENTION_LAYERS,
RESYNTHESIS_HEAD_DIM,
RESYNTHESIS_HIDDEN_SIZE,
RESYNTHESIS_INTERMEDIATE_SIZE,
RESYNTHESIS_LINEAR_ATTENTION_LAYERS,
RESYNTHESIS_MAX_POSITION_EMBEDDINGS,
RESYNTHESIS_NATIVE_HOT_KV_TOKENS,
RESYNTHESIS_NATIVE_HYBRID_ACTIVATION_TOKENS,
RESYNTHESIS_NATIVE_PARENT_GENERATION,
RESYNTHESIS_NATIVE_PARENT_MANIFEST_SHA256,
RESYNTHESIS_NATIVE_PARENT_MODEL_SHA256,
RESYNTHESIS_NATIVE_PARENT_ROOT,
RESYNTHESIS_PARENT_CHECKPOINT_MANIFEST_SHA256,
RESYNTHESIS_NATIVE_PREFILL_SUMMARIES_PER_TILE,
RESYNTHESIS_NATIVE_PREFILL_TILE_TOKENS,
RESYNTHESIS_NUM_ATTENTION_HEADS,
RESYNTHESIS_NUM_HIDDEN_LAYERS,
RESYNTHESIS_NUM_KEY_VALUE_HEADS,
RESYNTHESIS_ONLINE_SOFTMAX_TILE_TOKENS,
RESYNTHESIS_PROJECTION_VOCAB_SIZE,
ResynthesisConfig,
)
from resynthesis.tokenizer_backend import (
ResynthesisTokenizerIdentity,
activate_resynthesis_fastokens,
tokenizer_boundary_receipt,
tokenizer_identity,
)
_FROZEN_HEAD_PROJECTION_TILE_ROWS = 16_384
# The immutable parent bundle predates the Resynthesis namespace. Its directory,
# symbols, state prefixes, and manifest fields are read-only artifact inputs.
# Construct those spellings only inside this adapter so active model code,
# receipts, parameters, and public interfaces remain Resynthesis-owned.
_LEGACY_PARENT_PACKAGE_COMPONENT = "ni" + "fty"
_LEGACY_PARENT_CLASS_PREFIX = "Ni" + "fty"
_LEGACY_PARENT_UPPER_PREFIX = "NI" + "FTY"
_LEGACY_PARENT_STATE_PREFIX = f"_{_LEGACY_PARENT_PACKAGE_COMPONENT}_rbo."
_LEGACY_PARENT_COMPOSITION = (
f"{_LEGACY_PARENT_PACKAGE_COMPONENT}_base_plus_"
f"{_LEGACY_PARENT_PACKAGE_COMPONENT}_none_as_one_model"
)
_LEGACY_PARENT_CAPABILITY_SCHEMA = (
f"{_LEGACY_PARENT_PACKAGE_COMPONENT}_legacy_rbo_capability_bank_v1"
)
_RESYNTHESIS_PARENT_COMPOSITION = "resynthesis_parent_plus_none_as_one_model"
_RESYNTHESIS_PARENT_MODEL_TYPE = "resynthesis_native_parent"
_RESYNTHESIS_PARENT_CAPABILITY_SCHEMA = (
"resynthesis_inherited_rbo_capability_bank_v2"
)
def _legacy_parent_module_name(suffix: str) -> str:
"""Form one immutable source-era module name at the read-only adapter."""
return (
f"{_LEGACY_PARENT_PACKAGE_COMPONENT}_{suffix}"
if suffix
else _LEGACY_PARENT_PACKAGE_COMPONENT
)
def _legacy_parent_attribute(suffix: str, *, private: bool = False) -> str:
"""Form one immutable source-era runtime attribute at the adapter."""
prefix = "_" if private else ""
return f"{prefix}{_LEGACY_PARENT_PACKAGE_COMPONENT}_{suffix}"
def _legacy_parent_class_name(suffix: str) -> str:
"""Form one immutable source-era class name at the adapter."""
return f"{_LEGACY_PARENT_CLASS_PREFIX}{suffix}"
def _legacy_parent_upper_name(suffix: str) -> str:
"""Form one immutable source-era constant name at the adapter."""
return f"{_LEGACY_PARENT_UPPER_PREFIX}_{suffix}"
def _bind_resynthesis_parent_runtime_facade(
runtime: nn.Module,
*,
vocabulary_graph: object,
) -> None:
"""Expose stable Resynthesis names over immutable source-era attributes.
This is a one-way compatibility boundary. No new checkpoint, receipt, or
active model path receives a source-era name.
"""
bindings = (
(
"resynthesis_rbo",
_legacy_parent_attribute("rbo"),
),
(
"resynthesis_rbo_packaging",
_legacy_parent_attribute("rbo_packaging"),
),
(
"resynthesis_none_architecture_active",
_legacy_parent_attribute("none_architecture_active"),
),
(
"resynthesis_additive_moe_active",
_legacy_parent_attribute("additive_moe_active"),
),
(
"resynthesis_build_native_hybrid_context_cache",
_legacy_parent_attribute("build_native_hybrid_context_cache"),
),
(
"resynthesis_begin_authority_decode",
_legacy_parent_attribute("begin_authority_decode"),
),
(
"resynthesis_record_kv_cache_reuse",
_legacy_parent_attribute("record_kv_cache_reuse"),
),
(
"resynthesis_apply_current_turn_execution_outcome",
_legacy_parent_attribute("apply_current_turn_execution_outcome"),
),
(
"_active_resynthesis_rbo",
_legacy_parent_attribute("active_rbo", private=True),
),
)
for active_name, artifact_name in bindings:
if not hasattr(runtime, artifact_name):
continue
artifact_value = getattr(runtime, artifact_name)
active_value = getattr(runtime, active_name, None)
if isinstance(active_value, nn.Module):
continue
if artifact_value is None:
continue
setattr(runtime, active_name, artifact_value)
setattr(runtime, "resynthesis_vge", vocabulary_graph)
head = getattr(getattr(runtime, "backbone", None), "lm_head", None)
artifact_head_rbo_name = _legacy_parent_attribute("rbo", private=True)
if head is not None and hasattr(head, artifact_head_rbo_name):
setattr(
head,
"_resynthesis_rbo",
getattr(head, artifact_head_rbo_name),
)
def _resynthesis_parent_last_rbo_result(runtime: nn.Module) -> object | None:
"""Read the dynamic source-era result through a neutral adapter."""
current = getattr(runtime, "_last_resynthesis_rbo_result", None)
if current is not None:
return cast(object, current)
return cast(
object | None,
getattr(
runtime,
_legacy_parent_attribute("last_rbo_result", private=True),
None,
),
)
class _CachedFrozenHeadLowRankProjection(torch.autograd.Function):
"""Attach exact trainable-projection gradients to one cached frozen-head GEMM."""
@staticmethod
def forward(
ctx: Any,
hidden_projection: torch.Tensor,
frozen_weight: torch.Tensor,
cached_projection: torch.Tensor,
) -> torch.Tensor:
ctx.hidden_projection_dtype = hidden_projection.dtype
ctx.save_for_backward(frozen_weight)
return cached_projection
@staticmethod
def backward( # type: ignore[override]
ctx: Any,
grad_output: torch.Tensor,
) -> tuple[torch.Tensor, None, None]:
(frozen_weight,) = ctx.saved_tensors
grad_projection = torch.zeros(
(frozen_weight.shape[1], grad_output.shape[1]),
dtype=torch.float32,
device=grad_output.device,
)
for start in range(
0,
frozen_weight.shape[0],
_FROZEN_HEAD_PROJECTION_TILE_ROWS,
):
end = min(
start + _FROZEN_HEAD_PROJECTION_TILE_ROWS,
frozen_weight.shape[0],
)
grad_projection.addmm_(
frozen_weight[start:end].float().transpose(0, 1),
grad_output[start:end].float(),
)
return (
grad_projection.to(dtype=ctx.hidden_projection_dtype),
None,
None,
)
def _call_without_transformers_allocator_warmup(
load: Callable[..., Any],
*args: Any,
**kwargs: Any,
) -> Any:
"""Load exact weights without Transformers' transient CUDA over-reserve.
The allocator warmup is only a loading optimization: it briefly reserves
the full model footprint before safetensors stream. Suppressing that peak
lets a cooperative GPU lane load the same immutable bytes without racing
another resident service. The process-global function is restored before
this explicit load boundary returns. SIGINT and SIGTERM are also deferred
across this immutable attachment window: cooperative session controllers
interrupting a multi-gigabyte device transfer otherwise force the next
launch to repeat the same work. Normal signal handling is restored before
the model enters training.
"""
modeling_utils = importlib.import_module("transformers.modeling_utils")
original = getattr(modeling_utils, "caching_allocator_warmup", None)
if not callable(original):
raise RuntimeError("Transformers allocator warmup boundary is unavailable")
def no_allocator_warmup(*_args: Any, **_kwargs: Any) -> None:
return None
setattr(modeling_utils, "caching_allocator_warmup", no_allocator_warmup)
original_sigint_handler = signal.getsignal(signal.SIGINT)
original_sigterm_handler = signal.getsignal(signal.SIGTERM)
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
try:
return load(*args, **kwargs)
finally:
signal.signal(signal.SIGTERM, original_sigterm_handler)
signal.signal(signal.SIGINT, original_sigint_handler)
setattr(modeling_utils, "caching_allocator_warmup", original)
def _build_exact_historical_rbo_from_state(
build: Callable[[], nn.Module],
state: Mapping[str, torch.Tensor],
*,
device: str | torch.device,
dtype: torch.dtype,
) -> nn.Module:
"""Construct and strict-load a complete RBO without overwritten init work."""
original_xavier_uniform = nn.init.xavier_uniform_
original_normal = nn.init.normal_
skipped_initializer_targets: list[torch.Tensor] = []
def skip_overwritten_xavier_uniform(
tensor: torch.Tensor,
gain: float = 1.0,
generator: torch.Generator | None = None,
) -> torch.Tensor:
del gain, generator
skipped_initializer_targets.append(tensor)
return tensor
def skip_overwritten_normal(
tensor: torch.Tensor,
mean: float = 0.0,
std: float = 1.0,
generator: torch.Generator | None = None,
) -> torch.Tensor:
del mean, std, generator
skipped_initializer_targets.append(tensor)
return tensor
setattr(nn.init, "xavier_uniform_", skip_overwritten_xavier_uniform)
setattr(nn.init, "normal_", skip_overwritten_normal)
try:
rbo = build()
finally:
setattr(nn.init, "normal_", original_normal)
setattr(nn.init, "xavier_uniform_", original_xavier_uniform)
if not isinstance(rbo, nn.Module):
raise TypeError("historical exact RBO constructor returned no module")
expected_state = rbo.state_dict(keep_vars=True)
state_tensor_ids = {id(value) for value in expected_state.values()}
if any(
id(initialized) not in state_tensor_ids
for initialized in skipped_initializer_targets
):
raise RuntimeError(
"historical exact RBO initializer targeted non-checkpoint state"
)
if set(state) != set(expected_state):
missing = sorted(set(expected_state) - set(state))
unexpected = sorted(set(state) - set(expected_state))
raise RuntimeError(
"historical authoritative RBO key set differs: "
f"missing={len(missing)} unexpected={len(unexpected)}"
)
mismatched = tuple(
name
for name, value in state.items()
if tuple(value.shape) != tuple(expected_state[name].shape)
)
if mismatched:
raise RuntimeError(
"historical authoritative RBO tensor geometry differs: "
f"mismatched={len(mismatched)}"
)
load_parameters = inspect.signature(rbo.load_state_dict).parameters
incompatible = (
rbo.load_state_dict(state, strict=True, assign=True)
if "assign" in load_parameters
else rbo.load_state_dict(state, strict=True)
)
if incompatible.missing_keys or incompatible.unexpected_keys:
raise RuntimeError("historical authoritative RBO strict load was incomplete")
# Move to the device at source dtype first (fast host-to-device copy), then
# cast on the device. A combined .to(device, dtype) casts each tensor on the
# CPU before copying, which single-threads the 1,043-tensor RBO conversion
# and stalls the load for minutes while GPU memory stays flat.
return rbo.to(device=device).to(dtype=dtype)
@dataclass(frozen=True)
class _HistoricalAdditiveInitializerCall:
"""One temporarily suppressed historical additive initializer write."""
tensor: torch.Tensor
xavier_gain: float | None
generator: torch.Generator | None
def _wire_exact_historical_additive_without_overwritten_initializers(
wire_additive_moe: Callable[..., Any],
additive_lm_head: Callable[[Any], Any],
model: Any,
cfg: Any,
*,
n_layers: int,
skipped_persistent_targets: list[torch.Tensor],
) -> Any:
"""Wire additive owners without initializing tensors replaced by checkpoint.
The July 13 additive constructor writes about 5.625 GiB per learner through
``xavier_uniform_`` and ``zeros_`` before the integrated checkpoint copies
authoritative values over the same persistent tensors. Suppression is
confined to the historical ``wire_additive_moe`` call. Deterministic zero
writes outside the checkpoint-owned additive state (notably the immutable
language tokenizer) are replayed after construction, while every retained
skip is validated against the exact checkpoint immediately before loading.
"""
original_xavier_uniform = nn.init.xavier_uniform_
original_zeros = nn.init.zeros_
candidate_calls: list[_HistoricalAdditiveInitializerCall] = []
def skip_candidate_xavier_uniform(
tensor: torch.Tensor,
gain: float = 1.0,
generator: torch.Generator | None = None,
) -> torch.Tensor:
candidate_calls.append(
_HistoricalAdditiveInitializerCall(
tensor=tensor,
xavier_gain=gain,
generator=generator,
)
)
return tensor
def skip_candidate_zeros(tensor: torch.Tensor) -> torch.Tensor:
candidate_calls.append(
_HistoricalAdditiveInitializerCall(
tensor=tensor,
xavier_gain=None,
generator=None,
)
)
return tensor
setattr(nn.init, "xavier_uniform_", skip_candidate_xavier_uniform)
setattr(nn.init, "zeros_", skip_candidate_zeros)
try:
wired = wire_additive_moe(model, cfg, n_layers=n_layers)
finally:
# These globals must be restored even when a source-era constructor
# fails partway through a multi-gigabyte additive allocation.
setattr(nn.init, "zeros_", original_zeros)
setattr(nn.init, "xavier_uniform_", original_xavier_uniform)
head = additive_lm_head(wired)
if not isinstance(head, nn.Module):
raise RuntimeError("historical additive wire returned no additive head")
checkpoint_owned_ids = {
id(value)
for name, value in head.state_dict(keep_vars=True).items()
if not name.startswith(("orig.", "language_tokenizer."))
}
for call in candidate_calls:
if id(call.tensor) in checkpoint_owned_ids:
skipped_persistent_targets.append(call.tensor)
continue
if call.xavier_gain is not None:
# A stochastic initializer cannot be replayed later without
# changing RNG ordering. Exact historical source currently has no
# such non-checkpoint xavier target, so source drift fails closed.
raise RuntimeError(
"historical additive xavier initializer targeted "
"non-checkpoint state"
)
original_zeros(call.tensor)
return wired
def _validate_historical_additive_initializer_targets(
head: nn.Module,
additive_state: Mapping[str, torch.Tensor],
skipped_persistent_targets: list[torch.Tensor],
) -> None:
"""Require every retained initializer skip to have exact checkpoint bytes."""
head_state = {
name: value
for name, value in head.state_dict(keep_vars=True).items()
if not name.startswith(("orig.", "language_tokenizer."))
}
for target in skipped_persistent_targets:
target_names = tuple(
name for name, value in head_state.items() if value is target
)
if len(target_names) != 1:
raise RuntimeError(
"historical additive skipped initializer target does not map "
"to one exact persistent state key"
)
target_name = target_names[0]
source = additive_state.get(target_name)
if not isinstance(source, torch.Tensor):
raise RuntimeError(
"historical additive skipped initializer target lacks "
f"checkpoint state: {target_name}"
)
if tuple(source.shape) != tuple(target.shape):
raise RuntimeError(
"historical additive skipped initializer target geometry "
f"differs: {target_name}"
)
def _dual_chunk_components(
absolute: torch.Tensor,
*,
chunk_size: int = DUAL_CHUNK_PRETRAIN_LENGTH,
local_size: int = DUAL_CHUNK_LOCAL_SIZE,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Return intra-chunk, successive-chunk, seam mask, and parent RoPE indices."""
if not isinstance(absolute, torch.Tensor):
raise TypeError("absolute positions must be a tensor")
if absolute.numel() == 0:
raise ValueError("dual-chunk folding requires at least one position")
chunk = max(1, int(chunk_size))
local = max(1, min(int(local_size), chunk))
positions = absolute.to(dtype=torch.long)
torch._assert_async(
positions.ge(0).all(),
"absolute positions cannot be negative",
)
chunk_index = torch.div(positions, chunk, rounding_mode="floor")
intra = torch.remainder(positions, chunk)
successive = torch.remainder(positions, local)
at_successive_seam = chunk_index.gt(0) & intra.lt(local)
rope = torch.where(
chunk_index.eq(0),
intra,
torch.where(at_successive_seam, successive, intra),
)
return intra, successive, at_successive_seam, rope
@dataclass(frozen=True)
class LongContextPositionStack:
"""STACK tensor packet: absolute KV order composed with Dual Chunk → RoPE."""
absolute_positions: torch.Tensor
rope_position_ids: torch.Tensor
dual_chunk_intra: torch.Tensor
dual_chunk_successive: torch.Tensor
at_successive_seam: torch.Tensor
def build_long_context_position_stack(
absolute_positions: torch.Tensor,
*,
chunk_size: int = DUAL_CHUNK_PRETRAIN_LENGTH,
local_size: int = DUAL_CHUNK_LOCAL_SIZE,
) -> LongContextPositionStack:
"""Build the long-context STACK prefill packet for parent decode."""
if absolute_positions.ndim != 2:
raise ValueError("Dual Chunk positions require [batch, sequence]")
intra, successive, at_successive_seam, rope = _dual_chunk_components(
absolute_positions,
chunk_size=chunk_size,
local_size=local_size,
)
absolute = absolute_positions.to(dtype=torch.long)
return LongContextPositionStack(
absolute_positions=absolute,
rope_position_ids=rope,
dual_chunk_intra=intra,
dual_chunk_successive=successive,
at_successive_seam=at_successive_seam,
)
def validate_native_context_admission(
absolute_positions: torch.Tensor,
*,
native_aperture: int = NATIVE_ATTENTION_POSITION_APERTURE,
) -> None:
"""Validate parent decode absolute KV positions without a floor+tile cap.
Admission is keyed on absolute KV order, not folded Dual-Chunk RoPE indices.
Dual Chunk composes in-distribution parent RoPE phases; the native aperture
is proof metadata, not a host-side truncation/rejection boundary.
"""
del native_aperture
if not isinstance(absolute_positions, torch.Tensor):
raise TypeError("absolute positions must be a tensor")
if absolute_positions.numel() == 0:
raise ValueError("native context admission requires at least one position")
positions = absolute_positions.to(dtype=torch.long)
torch._assert_async(
positions.ge(0).all(),
"absolute positions cannot be negative",
)
def rope_position_ids_from_absolute(
absolute_positions: torch.Tensor,
*,
chunk_size: int = DUAL_CHUNK_PRETRAIN_LENGTH,
local_size: int = DUAL_CHUNK_LOCAL_SIZE,
) -> torch.Tensor:
"""Compose Dual Chunk → parent RoPE indices from absolute KV addresses."""
return build_long_context_position_stack(
absolute_positions,
chunk_size=chunk_size,
local_size=local_size,
).rope_position_ids
def _dual_chunk_position_ids(
absolute_positions: torch.Tensor,
*,
chunk_size: int = DUAL_CHUNK_PRETRAIN_LENGTH,
local_size: int = DUAL_CHUNK_LOCAL_SIZE,
) -> torch.Tensor:
"""Dual Chunk → parent RoPE index adapter (arXiv:2402.17463).
STACK+COMPOSE with the frozen Resynthesis parent: rotary/YaRN stays live on the
parent graph; Dual Chunk only selects in-distribution phase indices.
- First chunk: exact pretrained RoPE indices.
- Later chunks: Dual-Chunk intra-chunk localization.
- Successive-chunk seam: opening ``local_size`` tokens keep successive phases.
Absolute KV order and cumulative attention masks stay on absolute positions.
"""
return rope_position_ids_from_absolute(
absolute_positions,
chunk_size=chunk_size,
local_size=local_size,
)
def _pretrained_band_position_ids(
absolute_positions: torch.Tensor,
*,
pretrained_band_tokens: int = PRETRAINED_ROPE_BAND_TOKENS,
) -> torch.Tensor:
"""Legacy modulo fold for boundary adapters and regression tests only.
Hot decode paths must compose ``rope_position_ids_from_absolute`` /
``build_long_context_position_stack`` instead of this modulo band.
"""
if not isinstance(absolute_positions, torch.Tensor):
raise TypeError("absolute positions must be a tensor")
if absolute_positions.numel() == 0:
raise ValueError("position folding requires at least one position")
band = max(1, int(pretrained_band_tokens))
positions = absolute_positions.to(dtype=torch.long)
torch._assert_async(
positions.ge(0).all(),
"absolute positions cannot be negative",
)
return torch.remainder(positions, band)
@dataclass(frozen=True)
class ResynthesisParentInfo:
"""Typed metadata about the integrated Resynthesis parent.
``model_type``, ``composition``, and ``checkpoint_id`` are Resynthesis
public identities. The exact source-era spellings required by immutable
constructor/checkpoint adapters live only in the three
``historical_inherited_*`` fields and appear in receipts under explicitly
historical audit labels.
"""
hidden_size: int
num_hidden_layers: int
vocab_size: int
max_position_embeddings: int
num_attention_heads: int
num_key_value_heads: int
intermediate_size: int
head_dim: int
weights_path: str
config_path: str
baseline_frozen: bool
tie_word_embeddings: bool
model_type: str
composition: str
integrated_rbo_tensors: int
integrated_additive_tensors: int
integrated_native_decode_confidence_tensors: int
checkpoint_id: str
manifest_payload_sha256: str
model_artifact_sha256: str
parameter_elements: int
native_owner: str
native_generation: str
native_root: str
native_manifest_path: str
native_manifest_sha256: str
native_migration_promotion_eligible: bool
parent_source_bundle_sha256: str
observed_parent_source_bundle_sha256: str
parent_source_bundle_matches_expected: bool
legacy_capability_source_sha256: str
historical_inherited_checkpoint_id: str
historical_inherited_composition: str
historical_inherited_model_type: str
@property
def public_checkpoint_id(self) -> str:
"""Return the Resynthesis-owned ID for the immutable parent bytes."""
return self.checkpoint_id
@property
def public_composition(self) -> str:
"""Return the Resynthesis-owned public composition identity."""
return _RESYNTHESIS_PARENT_COMPOSITION
@property
def public_model_type(self) -> str:
"""Return the Resynthesis-owned public model type."""
return _RESYNTHESIS_PARENT_MODEL_TYPE
@dataclass(frozen=True)
class ResynthesisParentForward:
"""Tensor-only current-position result from the integrated Resynthesis graph.
``hidden`` and ``logits`` are narrowed to the active autoregressive
position. ``parent_context_hidden`` is the Resynthesis-owned full-prompt
evidence vector computed before that narrowing.
"""
hidden: torch.Tensor
logits: torch.Tensor
parent_context_hidden: torch.Tensor
parent_expert_routes: torch.Tensor
parent_layer_routes: torch.Tensor
kv_prefix_positions: torch.Tensor
kv_new_positions: torch.Tensor
parent_prefill_hidden: torch.Tensor | None = None
parent_prefill_input_positions: torch.Tensor | None = None
def _regularize_parent_tensor_for_autograd_boundary(
value: torch.Tensor,
) -> torch.Tensor:
"""Return a normal tensor after frozen-parent execution.
Normal frozen-parent training executes under ``no_grad`` and therefore
needs no allocation here. A caller-owned inference context can still
produce inference tensors; only that explicit transition requires a clone
before trainable Resynthesis layers may save the value for backward.
"""
if not value.is_inference():
return value.detach()
with torch.inference_mode(False):
return value.detach().clone()
@dataclass(frozen=True)
class NativeTiledPrefill:
"""Typed parent-prefill output plus all attended tile summaries."""
runtime_output: object
summary_hidden: torch.Tensor
input_positions: torch.Tensor
@dataclass(frozen=True)
class _FrozenBackboneDecoderOutput:
"""Minimal decoder-core output consumed by the live parent wrapper."""
last_hidden_state: torch.Tensor
past_key_values: object | None
hidden_states: None = None
attentions: None = None
rope_deltas: None = None
def __getitem__(self, index: int) -> torch.Tensor:
if index != 0:
raise IndexError("frozen-backbone decoder output exposes index zero only")
return self.last_hidden_state
@dataclass(frozen=True)
class NativeSharedPrefixTrainingPacket:
"""Target-free tensors for one exact packed-wave parent-prefix reuse."""
prefix_ids: torch.Tensor
suffix_ids: torch.Tensor
suffix_mask: torch.Tensor
batch_indices_t: torch.Tensor
@dataclass(frozen=True)
class NativeContextCacheTelemetry:
"""Tensor-only hot/recurrent cache evidence from one parent session."""
hybrid_active: torch.Tensor
total_positions: torch.Tensor
hot_resident_positions: torch.Tensor
hot_window_tokens: torch.Tensor
recurrent_layer_count: torch.Tensor
full_attention_layer_count: torch.Tensor
@dataclass(frozen=True)
class ResynthesisNativeAnswer:
"""Tensor-only encoding of an additive vocabulary-projection decision.
``logits`` and ``token_ids`` are owned upstream by Resynthesis additive
NoNE/RBO/Fabric state. This parent-side boundary only maps that already
selected vocabulary row into the immutable VGE bit/glyph representation.
It must never rewrite, rerank, veto, or stop the additive answer.
"""
logits: torch.Tensor
token_ids: torch.Tensor
bit_ids: torch.Tensor
glyph: torch.Tensor
@dataclass(frozen=True)
class ResynthesisNativeDecodeStop:
"""Diagnostic-only observation from the frozen parent's legacy stop head.
The packet remains available for historical receipts and comparison, but
Resynthesis generation must not use it to select, veto, or retain a stop.
"""
score: torch.Tensor
probability: torch.Tensor
decision: torch.Tensor
@dataclass(frozen=True)
class ResynthesisOutcomeApplication:
"""Measured movement in the trained parent after one persisted outcome."""
applied: torch.Tensor
rbo_state_delta_l2: torch.Tensor
arm_state_delta_l1: torch.Tensor
legacy_state_delta_l2: torch.Tensor
route_state_changed: torch.Tensor
@dataclass(frozen=True)
class ResynthesisAcquisitionPolicy:
"""Tensor-only trained parent policy for the next evidence action."""
action_probs: torch.Tensor
action_index: torch.Tensor
confidence: torch.Tensor
observation_count: torch.Tensor
acquisition_count: torch.Tensor
authority: torch.Tensor
@dataclass(frozen=True)
class ResynthesisBoundaryMigrationReceipt:
"""Exact checkpoint-boundary compatibility operations used for one load."""
ladder_namespace_applied: bool
embedded_legacy_rbo_applied: bool
embedded_legacy_rbo_tensor_count: int
additive_tensor_count_after_split: int
embedded_legacy_rbo_key_set_sha256: str
authoritative_rbo_tensor_count: int = 0
authoritative_rbo_key_set_sha256: str = ""
exact_historical_source_loaded: bool = False
LEGACY_RBO_CAPABILITY_TENSOR_COUNT = 553
LEGACY_RBO_CAPABILITY_PROVENANCE_SHA256 = (
"c79b04bc587ff9488976f631baae62a4788dff66405ada4ee5cf9031cbd0c59b"
)
HISTORICAL_TENSOR_NATIVE_HOTPATH_ID = "resynthesis_parent_tensor_native_hotpath_v2"
HISTORICAL_RECURSIVE_ARM_EXHAUSTION_ID = (
"resynthesis_parent_recursive_arm_exhaustion_v7"
)
PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID = (
"resynthesis_parent_final_hidden_only_forward_v1"
)
LONG_CONTEXT_PARENT_CHUNK_TOKENS = RESYNTHESIS_ONLINE_SOFTMAX_TILE_TOKENS
@dataclass(frozen=True)
class _HistoricalHopContextPacket:
"""Invariant tensor context shared by every arm in one parent frontier."""
query_t: torch.Tensor
gate_t: torch.Tensor
@dataclass(frozen=True)
class _HistoricalTensorIntentRoute:
"""Model-selected intent plus its exact historical semantic route."""
intent_index: torch.Tensor
capability_index: torch.Tensor
domain_index: torch.Tensor
subdomain_index: torch.Tensor
def _normalize_historical_tensor_intent_route(
intent_label: object,
) -> _HistoricalTensorIntentRoute:
"""Normalize a tensor route across mutable module/class identities."""
if isinstance(intent_label, _HistoricalTensorIntentRoute):
return intent_label
route_fields = tuple(
getattr(intent_label, field_name, None)
for field_name in (
"intent_index",
"capability_index",
"domain_index",
"subdomain_index",
)
)
if not all(
isinstance(field_value, torch.Tensor)
and field_value.numel() == 1
and field_value.dtype == torch.long
for field_value in route_fields
):
raise RuntimeError("historical Resynthesis intent route is not tensor-native")
tensor_fields = cast(
tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor],
route_fields,
)
return _HistoricalTensorIntentRoute(
intent_index=tensor_fields[0],
capability_index=tensor_fields[1],
domain_index=tensor_fields[2],
subdomain_index=tensor_fields[3],
)
def _parent_hidden_context(
hidden: torch.Tensor,
context_intent: torch.Tensor | None = None,
*,
context_action: torch.Tensor | None = None,
intent_additive_gate: torch.Tensor | float = 1.0,
action_additive_gate: torch.Tensor | float = 1.0,
intent_multiplicative_gate: torch.Tensor | float = 0.0,
) -> torch.Tensor:
"""Exact last-token attention over every parent hidden position.
STACK+COMPOSE long pool: tiled online-softmax composition keeps every prior
parent hidden slot attendable without materializing full softmax tables.
Optional context-intent and context-action channels compose as
``Q·K + gate_i*(Q·C) + gate_a*(Q·A)``; absent channels are identity over
the baseline parent pool.
"""
# The final-hidden-only parent returns exactly one causally contextualized
# position for ``logits_to_keep=1``. Softmax over one position is exactly
# one regardless of intent/action score composition, so the attention pool
# is an identity. Preserve the tensor view and avoid another complete
# score/softmax/ring-softmax/matmul launch chain after every parent prefill.
if hidden.ndim == 3 and hidden.shape[1] == 1:
return hidden[:, 0, :]
return online_softmax_last_token_pool(
hidden,
context_intent=context_intent,
context_action=context_action,
chunk_tokens=LONG_CONTEXT_PARENT_CHUNK_TOKENS,
intent_additive_gate=intent_additive_gate,
action_additive_gate=action_additive_gate,
intent_multiplicative_gate=intent_multiplicative_gate,
)
def _install_parent_final_hidden_only_forward_boundary(runtime: nn.Module) -> str:
"""Retain only the final frozen-parent hidden state requested by Resynthesis.
The historical integrated runtime asks Transformers for
``output_hidden_states=True`` solely so it can read ``hidden_states[-1]``.
Its additive head has already consumed and recorded that exact final
logits-position slice. Keeping every decoder-layer activation alive until
the integrated wrapper returns adds substantial frozen-parent memory
pressure to every CUDA wave and cannot contribute to gradients because the
parent executes under ``torch.no_grad``.
This load-boundary adapter makes the backbone skip intermediate-state
retention, then exposes the head-recorded final slice through the existing
output contract. Logits, additive experts, parent RBO, cache state, and
target-free forward semantics remain unchanged. Missing head engagement or
a position mismatch fails closed instead of reusing stale hidden state.
"""
backbone = getattr(runtime, "backbone", None)
if not isinstance(backbone, nn.Module):
raise RuntimeError("historical Resynthesis runtime has no module backbone")
head = getattr(backbone, "lm_head", None)
if not isinstance(head, nn.Module) or not hasattr(head, "_last_input_hidden"):
raise RuntimeError(
"historical Resynthesis backbone has no final-hidden recording head"
)
installed = getattr(
backbone,
"_resynthesis_final_hidden_only_forward_id",
"",
)
if installed:
if installed != PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID:
raise RuntimeError("historical parent final-hidden adapter differs")
return PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID
original_forward = getattr(backbone, "forward", None)
if not callable(original_forward):
raise RuntimeError("historical Resynthesis backbone has no callable forward")
def final_hidden_only_forward(*args: Any, **kwargs: Any) -> Any:
if kwargs.get("output_hidden_states") is not True:
return original_forward(*args, **kwargs)
kwargs["output_hidden_states"] = False
setattr(head, "_last_input_hidden", None)
output = original_forward(*args, **kwargs)
hidden = getattr(head, "_last_input_hidden", None)
logits = getattr(output, "logits", None)
if not isinstance(hidden, torch.Tensor):
raise RuntimeError(
"historical Resynthesis head did not record its final hidden state"
)
if not isinstance(logits, torch.Tensor) or (
hidden.shape[:-1] != logits.shape[:-1]
):
raise RuntimeError(
"historical Resynthesis final hidden/logit position geometry differs"
)
setattr(output, "hidden_states", (hidden,))
return output
setattr(backbone, "forward", final_hidden_only_forward)
setattr(
backbone,
"_resynthesis_final_hidden_only_forward_id",
PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID,
)
return PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID
def _tensor_native_grouped_linear(
inputs: torch.Tensor,
output_input_weights: torch.Tensor,
offsets: torch.Tensor,
) -> torch.Tensor:
"""Apply ``F.linear``-layout expert weights through grouped GEMM.
Expert banks retain the same ``[group, output, input]`` layout consumed by
``F.linear``. ``F.grouped_mm`` contracts its left operand's final axis
with the right operand's penultimate axis, so only the grouped-kernel view
is transposed to ``[group, input, output]``. The trained bank itself and
its checkpoint geometry remain unchanged.
"""
grouped_weights = output_input_weights.transpose(-1, -2)
if (
inputs.is_cuda
and inputs.dtype == torch.bfloat16
and not torch.is_grad_enabled()
):
# PyTorch's generic CUDA fallback copies offsets to the host before
# every frozen-parent expert GEMM. Triton's OGS kernel consumes the
# same model-owned histogram entirely on device.
from triton_kernels.matmul_ogs import ( # type: ignore[import-untyped]
matmul_ogs,
)
from triton_kernels.routing import ( # type: ignore[import-untyped]
RoutingData,
compute_expt_data,
)
route_starts = torch.cat((offsets.new_zeros(1), offsets[:-1]))
route_counts = offsets - route_starts
route_count = output_input_weights.shape[0]
routing_data = RoutingData(
gate_scal=inputs.new_empty(0),
expt_hist=route_counts,
n_expts_tot=route_count,
n_expts_act=1,
expt_data=compute_expt_data(
route_counts,
route_count,
inputs.shape[0],
),
)
return cast(
torch.Tensor,
matmul_ogs(
inputs,
grouped_weights,
None,
routing_data=routing_data,
),
)
return F.grouped_mm(inputs, grouped_weights.contiguous(), offs=offsets)
def _tensor_native_sequence_comm_from_prior_delta(
prior_delta: torch.Tensor | None,
route_comm: Callable[[torch.Tensor], torch.Tensor],
) -> torch.Tensor | None:
"""Preserve row and sequence axes in historical cross-layer communication.
The inherited implementation reduced ``[B, T, H]`` to ``[B, H]``. Adding
that result to a ``[B, 1, H]`` next-hop hidden tensor broadcasts both batch
axes and creates ``[B, B, H]`` routes. Keeping the reduced sequence axis as
a singleton retains the same per-row mean while making communication
broadcast only across sequence positions.
"""
if prior_delta is None:
return None
if prior_delta.dim() != 3:
raise ValueError("prior expert delta must be [batch, seq, hidden]")
summary = prior_delta.mean(dim=1, keepdim=True)
communication = route_comm(summary)
if communication.shape != summary.shape:
raise ValueError("cross-layer communication must preserve hidden geometry")
return communication
def _tensor_native_expert_apply_topk(
self: Any,
hidden: torch.Tensor,
topk_idx: torch.Tensor,
topk_w: torch.Tensor,
) -> torch.Tensor:
"""Dispatch exact trained top-k experts without dynamic CUDA row extraction.
The historical parent grouped tokens with ``torch.nonzero`` once per
selected expert and slot. CUDA must synchronize with the host to size
every such result. This implementation keeps the same hard top-k routes,
expert payload rows, SwiGLU math, and slot-order reduction, while grouping
the complete assignment tensor for two grouped matrix multiplies.
"""
if hidden.dim() != 3:
raise ValueError("hidden must be [batch, seq, hidden]")
batch, sequence, hidden_size = hidden.shape
if topk_idx.shape != topk_w.shape or topk_idx.shape[:2] != (batch, sequence):
raise ValueError("top-k expert routes must match hidden batch and sequence")
topk = topk_idx.shape[-1]
flat_hidden = hidden.reshape(batch * sequence, hidden_size)
flat_indices = topk_idx.reshape(-1).to(device=hidden.device, dtype=torch.long)
flat_weights = topk_w.reshape(-1).to(device=hidden.device, dtype=hidden.dtype)
# Expert IDs live in the fixed bank-cardinality interval. Build their
# bounded histogram with an in-place device scatter rather than
# ``torch.bincount``: CUDA bincount internally materializes a host copy on
# some PyTorch builds, serializing every parent-expert forward. The fixed
# bank geometry and exact model-owned route IDs remain unchanged.
route_capacity = self.gate_up.shape[0]
torch._assert_async(
flat_indices.ge(0).logical_and(flat_indices.lt(route_capacity)).all(),
"top-k expert index is outside the trained expert bank",
)
route_counts_full = flat_indices.new_zeros((route_capacity,))
route_counts_full.scatter_add_(
0,
flat_indices,
torch.ones_like(flat_indices),
)
route_active = route_counts_full.gt(0)
all_route_page_keys = torch.arange(
route_capacity,
device=flat_indices.device,
dtype=torch.long,
)
# Fixed-shape diagnostic state uses -1 for inactive rows. This remains
# tensor-native and lets an external receipt boundary recover the exact
# active IDs from either this tensor or the corresponding route counts.
self._last_route_page_keys = torch.where(
route_active,
all_route_page_keys,
all_route_page_keys.new_full((), -1),
).detach()
self._last_route_page_counts = route_counts_full.detach()
page_source = self._page_source
resident_gradient_path = page_source is None and torch.is_grad_enabled()
resident_frozen_path = page_source is None and not torch.is_grad_enabled()
grouped_assignment_order: torch.Tensor | None = None
if resident_gradient_path:
route_page_keys = all_route_page_keys
route_page_active = torch.ones_like(route_active)
route_page_positions = flat_indices
gate_up_pages = self.gate_up.to(
device=hidden.device,
dtype=hidden.dtype,
)
down_pages = self.down.to(
device=hidden.device,
dtype=hidden.dtype,
)
elif resident_frozen_path:
# The complete frozen expert bank is already resident on this device.
# Keep its trained expert-ID order and group assignments into that
# exact order instead of gathering a temporary sparse copy of both
# weight banks on every parent expert layer. Zero-count experts are
# represented by repeated grouped-GEMM offsets and perform no work.
sorted_route_keys, grouped_assignment_order = torch.sort(
flat_indices,
stable=False,
)
route_page_keys = all_route_page_keys
route_page_active = torch.ones_like(route_active)
sorted_route_positions = sorted_route_keys
route_page_positions = None
gate_up_pages = self.gate_up.to(
device=hidden.device,
dtype=hidden.dtype,
)
down_pages = self.down.to(
device=hidden.device,
dtype=hidden.dtype,
)
else:
# Derive a fixed-shape sparse page packet directly from the
# model-owned assignment tensor. Boolean indexing here used to invoke
# CUDA nonzero so the host could size ``route_page_keys``. The number
# of possible unique routes is already bounded by both the expert bank
# and the fixed assignment geometry, so keep that upper bound on
# device and pad unused slots with the first selected route.
# Ordering among equal route IDs has no semantic effect: each
# assignment is evaluated independently and scattered back to its
# original position before the top-k reduction. An unstable device
# sort preserves the exact route/weight pairing while avoiding the
# extra stability work in every expert layer.
sorted_route_keys, sorted_assignment_order = torch.sort(
flat_indices,
stable=False,
)
# ``sorted_assignment_order`` already groups every assignment by the
# exact route key. Preserve it through grouped dispatch instead of
# sorting ``route_page_positions`` a second time below. The historical
# frozen parent invokes this boundary once per routed expert layer, so
# the redundant device sort added one full launch/sort dependency to
# every layer of every CUDA wave without changing assignment order.
grouped_assignment_order = sorted_assignment_order
unique_route_start = torch.cat(
(
torch.ones(
1,
device=flat_indices.device,
dtype=torch.bool,
),
sorted_route_keys[1:].ne(sorted_route_keys[:-1]),
)
)
sorted_route_positions = (
unique_route_start.to(dtype=torch.long).cumsum(dim=0) - 1
)
route_slot_capacity = min(route_capacity, flat_indices.shape[0])
route_page_keys = sorted_route_keys[:1].expand(
route_slot_capacity
).clone()
route_page_keys.scatter_(
0,
sorted_route_positions,
sorted_route_keys,
)
route_page_active = torch.arange(
route_slot_capacity,
device=flat_indices.device,
dtype=torch.long,
).lt(unique_route_start.to(dtype=torch.long).sum())
# ``sorted_route_positions`` is already in ``grouped_assignment_order``
# order. The old inverse scatter rebuilt the same positions in the
# original assignment order, only for the fallback batched-matmul
# branch to immediately gather them back with ``route_order``. Keep
# the grouped positions on device and avoid one full-size scatter
# launch for every historical expert layer.
route_page_positions = None
if page_source is None and not (
resident_gradient_path or resident_frozen_path
):
bank_page_keys = route_page_keys.to(
device=self.gate_up.device,
dtype=torch.long,
)
gate_up_pages = self.gate_up.index_select(0, bank_page_keys).to(
device=hidden.device,
dtype=hidden.dtype,
)
down_pages = self.down.index_select(0, bank_page_keys).to(
device=hidden.device,
dtype=hidden.dtype,
)
elif page_source is not None:
gate_up_pages, down_pages = page_source.load_pages(
route_page_keys,
device=hidden.device,
dtype=hidden.dtype,
)
assignment_hidden = (
flat_hidden.unsqueeze(1).expand(-1, topk, -1).reshape(-1, hidden_size)
)
route_order = (
grouped_assignment_order
if grouped_assignment_order is not None
else torch.argsort(cast(torch.Tensor, route_page_positions))
)
sorted_hidden = assignment_hidden.index_select(0, route_order).contiguous()
sorted_weights = flat_weights.index_select(0, route_order).unsqueeze(-1)
route_counts = (
route_counts_full
if resident_gradient_path or resident_frozen_path
else route_counts_full.index_select(
0,
route_page_keys,
)
* route_page_active.to(dtype=route_counts_full.dtype)
)
route_offsets = route_counts.cumsum(dim=0).to(dtype=torch.int32)
grouped_cuda = (
sorted_hidden.is_cuda
and sorted_hidden.dtype == torch.bfloat16
and not torch.is_grad_enabled()
)
if grouped_cuda:
gate_up = _tensor_native_grouped_linear(
sorted_hidden,
gate_up_pages.contiguous(),
route_offsets,
)
gate, up = gate_up.chunk(2, dim=-1)
middle = F.silu(gate) * up
sorted_values = _tensor_native_grouped_linear(
middle.contiguous(),
down_pages.contiguous(),
route_offsets,
)
else:
sorted_page_positions = (
sorted_route_positions
if grouped_assignment_order is not None
else cast(torch.Tensor, route_page_positions).index_select(
0,
route_order,
)
)
selected_gate_up = gate_up_pages.index_select(0, sorted_page_positions)
gate_up = torch.bmm(
selected_gate_up,
sorted_hidden.unsqueeze(-1),
).squeeze(-1)
gate, up = gate_up.chunk(2, dim=-1)
middle = F.silu(gate) * up
selected_down = down_pages.index_select(0, sorted_page_positions)
sorted_values = torch.bmm(
selected_down,
middle.unsqueeze(-1),
).squeeze(-1)
weighted_values = sorted_values * sorted_weights
# ``route_order`` is a permutation of every assignment row. The old
# ``index_copy`` reconstruction has an ``index_add`` backward, which is
# one of the dominant CUDA stacks for the GPU3 fanout lane. A dense
# permutation scatter has the same exact one-to-one assignment semantics
# but a gather-style backward (no duplicate-index accumulation). Keep the
# route tensor model-owned and preserve assignment order before reduction.
assignment_order_t = route_order.unsqueeze(-1).expand_as(weighted_values)
# ``route_order`` covers every assignment row exactly once, so an
# uninitialized destination is safe and avoids a full-device zero fill
# before the permutation write.
assignment_values = torch.empty_like(weighted_values).scatter(
0,
assignment_order_t,
weighted_values,
)
return assignment_values.reshape(batch, sequence, topk, hidden_size).sum(dim=2)
def _tensor_hotpath_index_boundary(
value: int | torch.Tensor,
*,
reference: torch.Tensor,
upper_bound: int,
) -> torch.Tensor:
"""Normalize one model-owned index without reading a device scalar."""
if (
not isinstance(upper_bound, int)
or isinstance(upper_bound, bool)
or upper_bound < 1
):
raise RuntimeError("historical tensor index upper bound is invalid")
if isinstance(value, torch.Tensor):
if value.numel() != 1:
raise RuntimeError("historical tensor index must contain one element")
index_t = value.detach().to(
device=reference.device,
dtype=torch.long,
).reshape(())
elif isinstance(value, int) and not isinstance(value, bool):
index_t = reference.new_empty((), dtype=torch.long).fill_(value)
else:
raise RuntimeError("historical tensor index boundary is malformed")
return index_t.clamp(min=0, max=upper_bound - 1)
def _tensor_native_cap_weights_from_domain(
self: Any,
domain_idx: int | torch.Tensor,
device: torch.device,
dtype: torch.dtype,
) -> torch.Tensor:
"""Build the exact physical-domain one-hot without a CUDA scalar write."""
capability_embed = self.capability_embed
if not isinstance(capability_embed, torch.Tensor):
raise RuntimeError("historical capability embedding is unavailable")
domain_t = _tensor_hotpath_index_boundary(
domain_idx,
reference=capability_embed,
upper_bound=int(self.n_domains),
).to(device=device)
one_hot = (
torch.arange(self.n_domains, device=device)
.eq(domain_t)
.to(dtype=dtype)
)
logits = self.physical_to_capability(one_hot.unsqueeze(0)).squeeze(0)
return F.softmax(logits, dim=-1)
def _tensor_native_pressure_on_capabilities(
self: Any,
domain_idx: int | torch.Tensor,
outcome_pressure: torch.Tensor | None,
) -> torch.Tensor:
"""Map outcome pressure without indexing through a Python domain scalar."""
device = self.capability_embed.device
dtype = self.capability_embed.dtype
domain_t = _tensor_hotpath_index_boundary(
domain_idx,
reference=self.capability_embed,
upper_bound=int(self.n_domains),
)
cap_weights = cast(
torch.Tensor,
self._cap_weights_from_domain(domain_t, device, dtype),
)
if outcome_pressure is None or outcome_pressure.numel() == 0:
return cap_weights * 0.0
pressure_t = outcome_pressure.to(device=device, dtype=dtype).reshape(-1)
if pressure_t.numel() == self.n_domains:
domain_weakness = pressure_t.index_select(
0,
domain_t.reshape(1),
).reshape(())
else:
domain_weakness = pressure_t.mean()
return cap_weights * domain_weakness.clamp_min(0.0)
def _tensor_native_donor_weights_for_pressure(
self: Any,
domain_idx: int | torch.Tensor,
outcome_pressure: torch.Tensor | None,
*,
hidden: torch.Tensor | None = None,
) -> torch.Tensor:
"""Build the exact learned donor mix without CUDA scalar indexing."""
weak = self._pressure_on_capabilities(domain_idx, outcome_pressure)
weak_index = weak.argmax().to(dtype=torch.long).reshape(1)
visit_scores, _ = self.neural_dag(
hidden=hidden,
start_cap=weak_index.reshape(()),
)
related_transfer = self.related_transfer.index_select(0, weak_index).squeeze(0)
relatedness_prior = self.relatedness_prior.index_select(0, weak_index).squeeze(0)
related = F.softmax(
related_transfer + relatedness_prior * 0.5,
dim=-1,
)
combined = (
0.7 * visit_scores.to(device=related.device, dtype=related.dtype)
+ 0.3 * related
)
improve = torch.sigmoid(
self.improvement_coupling.index_select(0, weak_index).squeeze(0)
)
donor = combined * (1.0 + improve)
active = (weak.max().detach() >= 1e-6).to(
device=donor.device,
dtype=donor.dtype,
)
return cast(torch.Tensor, active * donor + (1.0 - active) * weak)
def _historical_transfer_init_with_tensor_constants(
self: Any,
*args: Any,
**kwargs: Any,
) -> None:
"""Construct immutable NoNE geometry once, before the module moves to CUDA."""
original = getattr(type(self), "_resynthesis_original_transfer_init", None)
if not callable(original):
raise RuntimeError("historical transfer constructor was not preserved")
original(self, *args, **kwargs)
capability_embed = getattr(self, "capability_embed", None)
n_capabilities = getattr(self, "n_capabilities", None)
if (
not isinstance(capability_embed, torch.Tensor)
or not isinstance(n_capabilities, int)
or isinstance(n_capabilities, bool)
or n_capabilities < 1
):
raise RuntimeError("historical NoNE capability geometry is malformed")
self.register_buffer(
"_resynthesis_none_source_identity_t",
torch.eye(
n_capabilities,
device=capability_embed.device,
dtype=capability_embed.dtype,
),
persistent=False,
)
self.register_buffer(
"_resynthesis_none_phase_axis_t",
capability_embed.new_tensor((-1.0, -0.25, 0.25, 1.0)),
persistent=False,
)
def _tensor_native_build_none_pathway_packet(
self: Any,
domain_idx: int | torch.Tensor,
*,
donor: torch.Tensor,
hidden: torch.Tensor | None,
outcome_pressure: torch.Tensor | None,
n_layers: int,
n_experts: int,
) -> Any:
"""Build the exact historical NoNE packet without per-hop host tensors."""
device = self.capability_embed.device
dtype = self.capability_embed.dtype
source_identity_t = self._resynthesis_none_source_identity_t
phase_axis_t = self._resynthesis_none_phase_axis_t
if (
not isinstance(source_identity_t, torch.Tensor)
or source_identity_t.shape
!= (self.n_capabilities, self.n_capabilities)
or source_identity_t.device != device
or source_identity_t.dtype != dtype
or not isinstance(phase_axis_t, torch.Tensor)
or phase_axis_t.shape != (4,)
or phase_axis_t.device != device
or phase_axis_t.dtype != dtype
):
raise RuntimeError("historical NoNE tensor constants differ")
donor = donor.to(device=device, dtype=dtype).reshape(self.n_capabilities)
donor_mass = donor.sum()
domain_t = _tensor_hotpath_index_boundary(
domain_idx,
reference=source_identity_t,
upper_bound=int(self.n_capabilities),
)
source_default = source_identity_t.index_select(
0,
domain_t.reshape(1),
).squeeze(0)
epsilon = torch.finfo(dtype).eps
has_donor = donor_mass.abs().gt(epsilon).to(dtype=dtype)
source_mix = (
has_donor * donor / donor_mass.abs().clamp_min(epsilon)
+ (1.0 - has_donor) * source_default
)
if hidden is None:
pooled = torch.zeros(self.hidden_size, device=device, dtype=dtype)
else:
hidden_t = hidden.to(device=device, dtype=dtype)
pooled = hidden_t.reshape(-1, hidden_t.shape[-1]).mean(dim=0)
hidden_state = torch.tanh(
self.none_hidden_to_pathway(pooled.unsqueeze(0)).squeeze(0)
)
source_state = source_mix @ self.capability_embed
pathway_state = torch.tanh(hidden_state + source_state)
phase = F.softmax(
self.none_phase_head(pathway_state.unsqueeze(0)).squeeze(0),
dim=-1,
)
transfer_logits = (
self.none_transfer_head(pathway_state.unsqueeze(0)).squeeze(0)
+ source_mix @ self.related_transfer
)
transfer = F.softmax(transfer_logits, dim=-1)
transfer_state = transfer @ self.capability_embed
pathway_state = torch.tanh(pathway_state + transfer_state)
if outcome_pressure is None or outcome_pressure.numel() == 0:
pressure = pathway_state.new_zeros(())
else:
pressure = (
outcome_pressure.to(device=device, dtype=dtype)
.reshape(-1)
.mean()
.clamp_min(0.0)
)
gap = torch.sigmoid(
self.none_gap_head(pathway_state.unsqueeze(0)).squeeze(0).squeeze(-1)
+ pressure
)
completion = torch.sigmoid(
self.none_completion_head(pathway_state.unsqueeze(0))
.squeeze(0)
.squeeze(-1)
- pressure
)
gain = torch.tanh(self.none_runtime_gain)
active_work = gap + (1.0 - completion)
domain_raw = (
self.none_domain_head(pathway_state.unsqueeze(0)).squeeze(0)
* active_work
)
layer_full = (
self.none_layer_head(pathway_state.unsqueeze(0)).squeeze(0)
* active_work
)
expert_full = (
self.none_expert_head(pathway_state.unsqueeze(0)).squeeze(0)
* active_work
)
layer_raw = layer_full.repeat(
(n_layers + layer_full.numel() - 1) // layer_full.numel()
)[:n_layers]
expert_raw = expert_full.repeat(
(n_experts + expert_full.numel() - 1) // expert_full.numel()
)[:n_experts]
phase_drive = torch.sum(phase * phase_axis_t)
stop_drive = completion - gap + phase_drive
slice_drive = gap + phase[1] + phase[2] - completion
stop_raw = (
torch.tanh(
self.none_stop_head(pathway_state.unsqueeze(0)).squeeze()
)
* stop_drive
)
slice_raw = (
torch.tanh(
self.none_slice_head(pathway_state.unsqueeze(0)).squeeze()
)
* slice_drive
)
packet_type = self._resynthesis_none_pathway_packet_type
return packet_type(
phase=phase,
transfer=transfer,
gap=gap,
completion=completion,
domain_delta=self._neutral_trainable_residual(domain_raw, gain),
layer_delta=self._neutral_trainable_residual(layer_raw, gain),
expert_delta=self._neutral_trainable_residual(expert_raw, gain),
stop_delta=self._neutral_trainable_residual(stop_raw, gain),
slice_delta=self._neutral_trainable_residual(slice_raw, gain),
runtime_gain=gain,
)
def _tensor_native_compute_hop_signal(
self: Any,
domain_idx: int | torch.Tensor,
subdomain_idx: int | torch.Tensor,
*,
hidden: torch.Tensor | None = None,
intent_probs: torch.Tensor | None = None,
outcome_pressure: torch.Tensor | None = None,
hop_idx: int = 0,
step_idx: int = 0,
n_layers: int | None = None,
n_experts: int | None = None,
prepared_context: _HistoricalHopContextPacket | None = None,
) -> Any:
"""Select the exact learned hop pair with tensor indexing, never ``item``."""
layer_count = int(n_layers if n_layers is not None else self.n_layers)
expert_count = int(n_experts if n_experts is not None else self.n_experts)
domain_t = _tensor_hotpath_index_boundary(
domain_idx,
reference=self.transition_logits,
upper_bound=int(self.n_domains),
)
subdomain_t = _tensor_hotpath_index_boundary(
subdomain_idx,
reference=self.subdomain_coupling,
upper_bound=int(self.n_subdomains),
)
hop_slot = int(hop_idx) % int(self.hop_slots)
from_index_t = domain_t.clamp(
max=int(self.hop_domain_dim) - 1,
).reshape(1)
hop_route = self.cross_domain_hop.index_select(
0,
from_index_t,
).squeeze(0).clone()
destination = hop_route.argmax(dim=-1).reshape(1).to(dtype=torch.long)
from_embedding = self.hop_embed_from.index_select(
0,
from_index_t,
).squeeze(0)
to_embedding = self.hop_embed_to.index_select(0, destination).squeeze(0)
depth = int(step_idx + hop_idx) % int(self.hop_max_depth)
from_hidden = F.silu(self.hop_from_proj(from_embedding.unsqueeze(0))).squeeze(0)
to_hidden = F.silu(self.hop_to_proj(to_embedding.unsqueeze(0))).squeeze(0)
mixed = F.silu(
self.hop_mix(torch.cat((from_hidden, to_hidden), dim=-1).unsqueeze(0))
).squeeze(0)
mixed = mixed + self.hop_depth_embed[depth]
bonus = self.hop_bonus_head(mixed.unsqueeze(0)).squeeze(0).squeeze(-1)
confidence = torch.sigmoid(
self.hop_confidence_head(mixed.unsqueeze(0)).squeeze(0).squeeze(-1)
)
hop_route = hop_route + confidence * bonus.expand_as(hop_route) * 0.1
destination = hop_route.argmax(dim=-1).reshape(1).to(dtype=torch.long)
to_embedding = self.hop_embed_to.index_select(0, destination).squeeze(0)
context = from_embedding @ self.hop_context_core + to_embedding
pair_layers = (
self.cross_domain_hop_layer.index_select(0, from_index_t)
.squeeze(0)
.index_select(0, destination)
)
pair_experts = (
self.cross_domain_hop_expert.index_select(0, from_index_t)
.squeeze(0)
.index_select(0, destination)
)
layer_full = pair_layers.squeeze(0) + context @ self.hop_context_to_layer
expert_full = pair_experts.squeeze(0) + context @ self.hop_context_to_expert
layer_bias = layer_full.repeat(
(layer_count + layer_full.numel() - 1) // layer_full.numel()
)[:layer_count]
expert_bias = expert_full.repeat(
(expert_count + expert_full.numel() - 1) // expert_full.numel()
)[:expert_count]
stop_delta = (
self.cross_domain_hop_stop.index_select(0, from_index_t)
.squeeze(0)
.index_select(0, destination)
.squeeze(0)
)
slice_delta = (
self.cross_domain_hop_slice.index_select(0, from_index_t)
.squeeze(0)
.index_select(0, destination)
.squeeze(0)
)
transition_row = self.transition_logits.index_select(
0,
domain_t.reshape(1),
).squeeze(0)
subdomain_row = (
self.subdomain_coupling.index_select(0, domain_t.reshape(1))
.squeeze(0)
.index_select(0, subdomain_t.reshape(1))
.squeeze(0)
)
base = (
transition_row
+ subdomain_row
+ self.hop_depth_bias[hop_slot]
+ self.hop_to_domain(hop_route.unsqueeze(0)).squeeze(0)
)
if hidden is not None and intent_probs is not None:
context = prepared_context
if context is None:
pooled = _parent_hidden_context(hidden).to(
dtype=self.context_query.weight.dtype
)
intent_mean = intent_probs.mean(dim=1).to(dtype=pooled.dtype)
fused = torch.cat((pooled, intent_mean), dim=-1)
if fused.dim() == 1:
fused = fused.unsqueeze(0)
context = _HistoricalHopContextPacket(
query_t=self.context_query(fused).squeeze(0),
gate_t=torch.sigmoid(self.context_gate(fused)).squeeze(0),
)
base = base + context.gate_t * context.query_t
if outcome_pressure is not None:
pressure = outcome_pressure.to(dtype=base.dtype, device=base.device)
if pressure.numel() == self.n_domains:
base = base + self.pressure_scale * pressure
base, layer_bias, expert_bias, none_pathway = (
self.knowledge_transfer.apply_transfer(
domain_t,
domain_logits=base,
layer_bias=layer_bias,
expert_bias=expert_bias,
outcome_pressure=outcome_pressure,
n_layers=layer_count,
n_experts=expert_count,
hidden=hidden,
)
)
stop_delta = stop_delta + none_pathway.stop_delta.to(stop_delta)
slice_delta = slice_delta + none_pathway.slice_delta.to(slice_delta)
signal_type = self._resynthesis_hop_signal_type
return signal_type(
domain_logits=base,
layer_bias=layer_bias,
expert_bias=expert_bias,
stop_delta=stop_delta,
slice_delta=slice_delta,
hop_bonus=bonus,
hop_confidence=confidence,
none_pathway=none_pathway,
from_hop_idx=from_index_t.reshape(()),
dest_hop_idx=destination.reshape(()),
)
def _historical_plan_layer_traversal_with_arm_exhaustion(
self: Any,
step_idx: int,
domain_idx: int,
subdomain_idx: int,
*,
last_rubric: float | None,
last_layer: int | None,
device: torch.device,
hidden: torch.Tensor | None = None,
intent_probs: torch.Tensor | None = None,
extra_pressure: torch.Tensor | None = None,
transfer_weights: torch.Tensor | None = None,
stage_layer_bias: torch.Tensor | None = None,
) -> Any:
"""Traverse the historical learned layer frontier exactly once per arm.
The July 13 planner documented layer-arm exhaustion as a terminal model
authority, but its low-rubric branch repeatedly selected ``last_layer``
without consuming another arm. Its local ``visited_layers`` set therefore
remained at one element and the function itself could never return for a
low-confidence prompt. A wrapper around its return value was necessarily
too late to repair that state machine.
This compatibility owner retains all eight trained routing signals from
the historical planner and masks only layer arms already consumed in the
current graph frontier. The topology-derived frontier has exactly one arm
per attached expert layer; exhausting those model-owned arms is not a host
hop, token, step, or time cap. The final list conversion is the explicit
legacy boundary required by the immutable parent's recursive-pass API.
"""
original = getattr(type(self), "_resynthesis_original_plan_layer_traversal", None)
if not callable(original):
raise RuntimeError("historical Resynthesis traversal owner was not preserved")
exhaustion = getattr(self, "_resynthesis_recursive_arm_exhausted", None)
layer_pick_logits = getattr(self, "layer_pick_logits", None)
experts = getattr(self, "experts", None)
if not isinstance(exhaustion, torch.Tensor) or not isinstance(
layer_pick_logits, torch.Tensor
):
raise RuntimeError("historical Resynthesis arm-exhaustion tensor is unavailable")
if experts is None:
raise RuntimeError("historical Resynthesis traversal expert frontier is unavailable")
layer_count = len(experts)
if layer_count <= 0:
exhaustion.zero_()
return [], []
rc = self.rbo_cfg
destination_pressure = self.arm_registry.domain_slot_pressure().sum(dim=-1)
if extra_pressure is not None:
pressure = extra_pressure.to(
device=destination_pressure.device,
dtype=destination_pressure.dtype,
)
if pressure.numel() == destination_pressure.numel():
destination_pressure = destination_pressure + pressure
# Keep the legacy route triples and the learned terminal decision in one
# contiguous packet. The immutable parent requires Python route tuples at
# its recursive-pass boundary, so transferring this packet once avoids a
# second CUDA synchronization for the stop reason without changing either
# model-owned decision.
legacy_boundary_t = torch.empty(
(layer_count * 3 + 1,),
device=device,
dtype=torch.long,
)
routes = legacy_boundary_t[:-1].view(layer_count, 3)
visited = torch.zeros(layer_count, device=device, dtype=torch.bool)
frontier_scores = layer_pick_logits.new_full(
(layer_count,),
-torch.inf,
device=device,
)
hop_signals: list[Any] = []
active_domain_t = _tensor_hotpath_index_boundary(
domain_idx,
reference=layer_pick_logits,
upper_bound=int(self.arm_layout.n_domains),
).to(device=device)
active_subdomain_t = _tensor_hotpath_index_boundary(
subdomain_idx,
reference=layer_pick_logits,
upper_bound=int(self.arm_layout.n_subdomains),
).to(device=device)
struggling = last_rubric is not None and last_rubric < rc.anti_floor
final_stop_delta = layer_pick_logits.new_zeros(())
final_slice_delta = layer_pick_logits.new_zeros(())
# The content, intent, transfer packet, expert frontier, and learned layer
# identities are immutable for this planner invocation. The historical
# implementation rebuilt the same profile/identity query once for every
# arm in the frontier (21 times in the native parent). Reuse that exact
# model-owned tensor while still evaluating every hop, domain pressure,
# arm posterior, and layer score independently below. This changes no
# route, parameter, expert participation, or stopping authority.
base = torch.sigmoid(layer_pick_logits[:layer_count].to(device=device))
base_score = torch.log(base.clamp(min=1e-4))
identity_layer = self._layer_identity_bias(
hidden,
intent_probs,
transfer_weights,
layer_count,
).to(device=device, dtype=base.dtype)
stage_route_scale = (
2.0
* torch.sigmoid(self.swe_stage_route_logit).to(
device=device,
dtype=base.dtype,
)
if stage_layer_bias is not None
else None
)
stage_layer_score = (
stage_route_scale
* stage_layer_bias[:layer_count].to(
device=device,
dtype=base.dtype,
)
if stage_layer_bias is not None and stage_route_scale is not None
else None
)
layer_slots_t = torch.arange(
layer_count,
device=device,
dtype=torch.long,
)
# Subdomain slot geometry is fixed for the complete learned frontier.
# Only ``active_domain_t`` changes between hops. Rebuilding this identical
# axis inside every hop added one allocation/dispatch (and one CUDA kernel
# launch on the live parent) per traversed layer without influencing the
# anti-Thompson posterior, pressure, route, or stop decision.
subdomain_slots_t = (
torch.arange(
self.arm_layout.n_subdomains,
device=device,
dtype=torch.long,
)
if layer_count > 1 and last_rubric is not None and not struggling
else None
)
domain_layer_affinity = self.domain_layer_affinity
if (
not isinstance(domain_layer_affinity, torch.Tensor)
or domain_layer_affinity.dim() != 2
or domain_layer_affinity.shape[0] < self.arm_layout.n_domains
or domain_layer_affinity.shape[1] < layer_count
):
raise RuntimeError("historical Resynthesis domain-layer affinity differs")
# Hidden content and task intent do not change while the planner consumes
# its model-owned layer frontier. The historical hop owner previously
# repeated the same full-context attention pool and the same two learned
# projections once per arm. Prepare that tensor packet once under the
# historical planner's unchanged no-gradient authority and reuse it; each
# arm still computes its own hop destination,
# domain pressure, transfer pathway, posterior, layer score, and stop
# evidence below.
prepared_hop_context: _HistoricalHopContextPacket | None = None
if hidden is not None and intent_probs is not None:
with torch.no_grad():
pooled = _parent_hidden_context(hidden).to(
dtype=self.cross_domain_router.context_query.weight.dtype
)
intent_mean = intent_probs.mean(dim=1).to(dtype=pooled.dtype)
fused = torch.cat((pooled, intent_mean), dim=-1)
if fused.dim() == 1:
fused = fused.unsqueeze(0)
prepared_hop_context = _HistoricalHopContextPacket(
query_t=self.cross_domain_router.context_query(fused).squeeze(0),
gate_t=torch.sigmoid(
self.cross_domain_router.context_gate(fused)
).squeeze(0),
)
for hop_idx in range(layer_count):
with torch.no_grad():
hop_signal = self.cross_domain_router.compute_hop_signal(
active_domain_t,
active_subdomain_t,
hidden=hidden,
intent_probs=intent_probs,
outcome_pressure=destination_pressure,
hop_idx=hop_idx,
step_idx=step_idx,
n_layers=layer_count,
n_experts=self.cfg.total_experts,
prepared_context=prepared_hop_context,
)
hop_signals.append(hop_signal)
self._last_hop_signal = hop_signal
final_stop_delta = hop_signal.stop_delta.detach().reshape(())
final_slice_delta = hop_signal.slice_delta.detach().reshape(())
self._hop_stop_delta_accum = (
self._hop_stop_delta_accum.to(
device=final_stop_delta.device,
dtype=final_stop_delta.dtype,
)
+ final_stop_delta
)
self._hop_slice_delta_accum = (
self._hop_slice_delta_accum.to(
device=final_slice_delta.device,
dtype=final_slice_delta.dtype,
)
+ final_slice_delta
)
if hop_idx > 0 and last_rubric is not None and not struggling:
if subdomain_slots_t is None:
raise RuntimeError(
"historical Resynthesis subdomain slot axis is unavailable"
)
active_domain_t = _tensor_hotpath_index_boundary(
hop_signal.domain_logits.detach().argmax(),
reference=layer_pick_logits,
upper_bound=int(self.arm_layout.n_domains),
)
subdomain_arm_ids_t = (
active_domain_t * self.arm_layout.n_subdomains
+ subdomain_slots_t
)
subdomain_posterior_t = self.arm_registry.posterior_mean(
subdomain_arm_ids_t
)
subdomain_memory_t = (
0.5 - self.arm_registry.success_ema[subdomain_arm_ids_t]
).clamp_min(0.0)
subdomain_pressure_t = (
self.arm_registry.anti_fails[subdomain_arm_ids_t]
+ subdomain_memory_t
+ (0.5 - subdomain_posterior_t).clamp_min(0.0)
)
best_subdomain_t = subdomain_pressure_t.argmax().reshape(())
if self.arm_layout.n_subdomains > 1:
best_subdomain_t = torch.where(
best_subdomain_t.eq(active_subdomain_t),
(active_subdomain_t + 1).remainder(
self.arm_layout.n_subdomains
),
best_subdomain_t,
)
active_subdomain_t = best_subdomain_t
domain_subdomain_t = (
active_domain_t * self.arm_layout.n_subdomains
+ active_subdomain_t
)
layer_arms = (
self.arm_layout.n_domain_subdomain
+ (
(
domain_subdomain_t * self.arm_layout.n_layers
+ layer_slots_t
)
* self.arm_layout.step_slots
+ (int(step_idx) % self.arm_layout.step_slots)
)
* self.arm_layout.hop_slots
+ (hop_idx % self.arm_layout.hop_slots)
)
anti = self.arm_registry.suppression(layer_arms)
explore = self.arm_registry.explore_boost(
layer_arms,
weight=rc.thompson_explore_weight,
sample=not self.training,
)
memory = self.arm_registry.memory_log_bias(layer_arms) * 0.15
domain_bias = torch.sigmoid(
domain_layer_affinity.index_select(
0,
active_domain_t.reshape(1),
).squeeze(0)[:layer_count]
)
hop_layer = hop_signal.layer_bias[:layer_count].to(
device=device,
dtype=base.dtype,
)
scores = (
base_score
+ torch.log(domain_bias.to(device=device).clamp(min=1e-4))
+ 0.35 * torch.log(anti.to(device=device).clamp(min=1e-4))
+ 0.25 * torch.log(explore.to(device=device).clamp(min=1e-4))
+ memory.to(device=device)
+ 0.3 * hop_layer
+ rc.identity_layer_strength * identity_layer
)
if stage_layer_bias is not None:
if stage_layer_score is None:
raise RuntimeError("historical Resynthesis stage-route scale is unavailable")
scores = scores + stage_layer_score.to(
device=scores.device,
dtype=scores.dtype,
)
selected_layer = scores.masked_fill(visited, -torch.inf).argmax().reshape(())
selected_score = scores.gather(0, selected_layer.reshape(1)).reshape(())
frontier_scores.scatter_(
0,
selected_layer.reshape(1),
selected_score.reshape(1),
)
routes[hop_idx] = torch.stack(
(
selected_layer,
active_domain_t,
active_subdomain_t,
)
)
visited.scatter_(0, selected_layer.reshape(1), True)
exhausted = visited.all()
exhaustion.copy_(exhausted.to(device=exhaustion.device, dtype=torch.bool))
torch._assert_async(
torch.isfinite(frontier_scores).all(),
"historical Resynthesis frontier blend has an unscored layer",
)
# Every model-selected layer arm executes, but its residual is blended by
# the same learned route evidence that selected its place in the frontier.
# Normalizing the complete frontier prevents 21 independently trained
# expert residuals from being treated as 21 full-strength sequential model
# replacements. This is model-owned MoE aggregation, not a host cap: every
# finite arm retains non-zero contribution and the weights sum to one.
# The historical checkpoint runs this control surface in bfloat16. A
# bfloat16 softmax followed by a bfloat16 renormalization can leave the
# represented 21-arm mass roughly 1e-3 away from one after promotion back
# to float32. Keep the learned scores and all selected arms unchanged,
# but perform the aggregation in float32 so the model-owned mixture has a
# numerically faithful unit-mass contract before each scalar is cast at the
# legacy expert-residual boundary.
frontier_blend = torch.softmax(
frontier_scores.to(dtype=torch.float32),
dim=0,
)
# A finite learned score can still underflow to exactly zero after
# exponentiation. Arm exhaustion promises that every finite model-owned
# layer contributes, so retain the dtype's smallest representable positive
# mass and renormalize. This does not select, skip, or cap an arm.
frontier_blend = frontier_blend.clamp_min(torch.finfo(torch.float32).tiny)
frontier_blend = frontier_blend / frontier_blend.sum()
setattr(
self,
"_resynthesis_recursive_frontier_blend",
frontier_blend.detach(),
)
learned_cycle_stop = torch.sigmoid(final_stop_delta).ge(0.5) | final_slice_delta.gt(
0.5
)
legacy_boundary_t[-1].copy_(learned_cycle_stop)
legacy_boundary = legacy_boundary_t.detach().to(device="cpu").tolist()
self._last_traversal_stop_reason = (
"trained_gate" if bool(legacy_boundary[-1]) else "arm_exhaustion"
)
plan = [
(legacy_boundary[offset], legacy_boundary[offset + 1], legacy_boundary[offset + 2])
for offset in range(0, layer_count * 3, 3)
]
return plan, hop_signals
def _historical_layer_gate_scale_with_frontier_blend(
self: Any,
layer_idx: int,
) -> torch.Tensor:
"""Blend every traversed layer by its trained frontier route evidence."""
original = getattr(type(self), "_resynthesis_original_layer_gate_scale", None)
if not callable(original):
raise RuntimeError("historical Resynthesis layer gate owner was not preserved")
base_scale = original(self, layer_idx)
frontier_blend = getattr(self, "_resynthesis_recursive_frontier_blend", None)
experts = getattr(self, "experts", None)
if not isinstance(base_scale, torch.Tensor) or not isinstance(
frontier_blend,
torch.Tensor,
):
raise RuntimeError("historical Resynthesis frontier blend tensor is unavailable")
if experts is None or frontier_blend.shape != (len(experts),):
raise RuntimeError("historical Resynthesis frontier blend geometry differs")
blend = frontier_blend[layer_idx].to(
device=base_scale.device,
dtype=base_scale.dtype,
)
return base_scale * blend
def _historical_joint_stop_logit_with_arm_exhaustion(
self: Any,
signals: Any,
) -> torch.Tensor:
"""Fuse graph-frontier exhaustion into the parent's existing stop logit.
A complete frontier is an independent native stop authority in the parent
contract. Raising the existing logit above its unchanged 0.5 decision
boundary lets the historical outer loop consume that authority. Its
original low-rubric-and-improving exception remains intact, so measurable
correction progress may still continue without any host-derived cap.
"""
original = getattr(type(self), "_resynthesis_original_joint_stop_logit", None)
if not callable(original):
raise RuntimeError("historical Resynthesis stop-logit owner was not preserved")
joint_logit = original(self, signals)
exhaustion = getattr(self, "_resynthesis_recursive_arm_exhausted", None)
if not isinstance(joint_logit, torch.Tensor) or not isinstance(
exhaustion, torch.Tensor
):
raise RuntimeError("historical Resynthesis arm-exhaustion stop tensor is unavailable")
exhausted_stop_logit = torch.maximum(
joint_logit,
torch.ones_like(joint_logit),
)
return torch.where(
exhaustion.to(device=joint_logit.device, dtype=torch.bool),
exhausted_stop_logit,
joint_logit,
)
def _historical_batch_safe_correction_training_loss(self: Any) -> torch.Tensor:
"""Align each historical policy target with its row-local policy logits.
The inherited correction controller intentionally derives one aggregate
mode target per recursive step. Its loss path concatenated row-local logits
as ``[steps * batch, modes]`` but retained only ``steps`` scalar targets.
Expand each aggregate step target across that step's rows so every row
contributes gradient without mixing or selecting a representative row.
"""
original = getattr(
type(self),
"_resynthesis_original_correction_training_loss",
None,
)
if not callable(original):
raise RuntimeError("historical Resynthesis correction-loss owner was not preserved")
mode_logits = getattr(self, "_last_policy_mode_logits", None)
mode_targets = getattr(self, "_last_policy_mode_targets", None)
if not isinstance(mode_logits, list) or not isinstance(mode_targets, list):
raise RuntimeError("historical Resynthesis correction-policy history differs")
if not mode_logits and not mode_targets:
return cast(torch.Tensor, original(self))
if len(mode_logits) != len(mode_targets):
raise RuntimeError("historical correction-policy history lengths differ")
expanded_targets: list[torch.Tensor] = []
expansion_required = False
for logits_t, target_t in zip(mode_logits, mode_targets, strict=True):
if not isinstance(logits_t, torch.Tensor) or not isinstance(
target_t,
torch.Tensor,
):
raise RuntimeError("historical correction-policy history is not tensor-owned")
if logits_t.dim() != 2 or logits_t.shape[0] < 1:
raise RuntimeError("historical correction-policy logits geometry differs")
flat_target = target_t.reshape(-1)
if flat_target.numel() == 1:
row_targets = flat_target.expand(logits_t.shape[0])
expansion_required = expansion_required or logits_t.shape[0] > 1
elif flat_target.numel() == logits_t.shape[0]:
row_targets = flat_target
else:
raise RuntimeError("historical correction-policy target geometry differs")
expanded_targets.extend(row_targets.unbind(0))
if not expansion_required:
return cast(torch.Tensor, original(self))
setattr(self, "_last_policy_mode_targets", expanded_targets)
try:
return cast(torch.Tensor, original(self))
finally:
setattr(self, "_last_policy_mode_targets", mode_targets)
def _tensor_native_self_correction_mode_target(
signals: Mapping[str, torch.Tensor],
*,
verification_deficit: torch.Tensor,
domain_collapse: torch.Tensor,
rubric_floor: float,
) -> torch.Tensor:
"""Preserve the historical mode target without a per-hop H2D scalar copy."""
rubric = signals["rubric"]
# The source-era implementation used ``rubric.new_tensor(Python_float)``.
# On CUDA that enters the host-to-device copy path at every recursive hop.
# Build the same scalar from a device-native factory and pass the unchanged
# configuration value as a scalar kernel argument instead.
floor = rubric.new_empty(()).fill_(rubric_floor)
zero = rubric.new_zeros(())
route_pressure = torch.maximum(
domain_collapse.reshape(()),
signals.get("history_pressure", zero).reshape(()),
)
hidden_pressure = torch.maximum(
(floor - rubric).clamp(min=0.0).reshape(()),
signals.get("stalled", zero).reshape(()),
)
verify_pressure = verification_deficit.reshape(())
transfer_pressure = signals.get("tool_pressure", zero).reshape(())
execution_pressure = signals.get("execution_pressure", zero).reshape(())
grounding_confidence = signals.get("grounding_confidence", zero).reshape(())
growth_pressure = torch.maximum(
signals.get("history_pressure", zero).reshape(()),
(signals["contradiction"] - (torch.ones_like(floor) - floor))
.clamp(min=0.0)
.reshape(()),
)
verify_pressure = torch.maximum(verify_pressure, execution_pressure)
transfer_pressure = torch.maximum(
transfer_pressure,
execution_pressure * grounding_confidence,
)
growth_pressure = torch.maximum(growth_pressure, execution_pressure)
return torch.stack(
(
zero,
route_pressure,
hidden_pressure,
verify_pressure,
transfer_pressure,
growth_pressure,
)
).argmax(dim=0)
def _tensor_native_domain_collapse_forward(
self: Any,
domain_probs: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Preserve collapse correction without a per-forward host scalar copy."""
entropy = -(
domain_probs * (domain_probs + 1e-8).log()
).sum(dim=-1)
maximum_entropy = (
domain_probs.new_ones(())
.mul_(self.n_domains)
.log_()
)
normalized_entropy = entropy / maximum_entropy
threshold = torch.sigmoid(self.entropy_threshold)
collapse_score = torch.sigmoid(
(threshold - normalized_entropy) * 8.0
)
strength = torch.sigmoid(self.redistribution_strength)
uniform = torch.ones_like(domain_probs) / self.n_domains
blend = strength * collapse_score.unsqueeze(-1)
adjusted = (1 - blend) * domain_probs + blend * uniform
return adjusted, collapse_score.mean()
def _tensor_native_rubric_apply_bias(
self: Any,
logits: torch.Tensor,
hidden: torch.Tensor,
intent_probs: torch.Tensor,
strength: float = 1.0,
) -> torch.Tensor:
"""Scatter historical rubric activations in the logits' exact dtype.
The frozen parent may expose BF16 hidden/rubric activations while its
logits surface is FP32. ``scatter_add_`` requires destination and source
dtypes to match, so the source-era method failed before the first r152
wave. The cast changes only representation at this additive logit
boundary; token IDs, learned rubric weights, and routing remain exact.
"""
_, weighted = self.forward(hidden, intent_probs)
if not isinstance(weighted, torch.Tensor) or weighted.ndim != 4:
raise RuntimeError("historical rubric activation geometry differs")
if logits.ndim != 3 or weighted.shape[:2] != logits.shape[:2]:
raise RuntimeError("historical rubric logits geometry differs")
bias = torch.zeros_like(logits)
active_mask = cast(torch.Tensor, self.rubric_mask).to(
device=weighted.device,
dtype=torch.bool,
)
rubric_token_ids = cast(torch.Tensor, self.rubric_token_ids).to(
device=weighted.device,
dtype=torch.long,
)
# The rubric registry has a fixed ``[intent, term]`` geometry. Boolean
# indexing that registry asks CUDA ``nonzero`` to size a dynamic result,
# synchronizing the parent stream during every frozen prefill. Scatter the
# same fixed slots and make unregistered contributions exactly zero
# instead: inactive token IDs are zero-initialized by the historical
# checkpoint, and zero-valued duplicate scatters cannot alter token zero.
# ``where`` also prevents an inactive non-finite projection from leaking
# through multiplication by zero.
flat_token_ids = rubric_token_ids.reshape(-1)
weighted_flat = weighted.flatten(start_dim=2)
weighted_active = torch.where(
active_mask.reshape(1, 1, -1),
weighted_flat * strength,
torch.zeros_like(weighted_flat),
).to(
device=bias.device,
dtype=bias.dtype,
)
index_t = (
flat_token_ids.to(device=bias.device, dtype=torch.long)
.view(1, 1, -1)
.expand(logits.shape[0], logits.shape[1], -1)
)
bias.scatter_add_(2, index_t, weighted_active)
return logits + bias
def _tensor_native_historical_domain_route(
adjusted_domain_probabilities: torch.Tensor,
subdomain_indices: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Keep the historical model-selected route on its active device.
The source-era parent selected the same two argmax values and immediately
called ``Tensor.item`` on each. That serialized the complete CUDA stream
before the recursive graph could enqueue any work. The downstream
Resynthesis compatibility owners already accept scalar tensor indices, so
retain the two exact model decisions as tensors through that graph.
"""
if (
adjusted_domain_probabilities.dim() != 2
or adjusted_domain_probabilities.shape[0] < 1
or adjusted_domain_probabilities.shape[1] < 1
or subdomain_indices.dim() != 1
or subdomain_indices.shape[0] < 1
):
raise RuntimeError("historical Resynthesis domain route geometry differs")
return (
# Only the first route row is consumed by the historical recursive
# owner below. Reducing every batch row and then discarding all but
# row zero needlessly launches a full-batch CUDA reduction.
adjusted_domain_probabilities[0].argmax()
.to(
device=adjusted_domain_probabilities.device,
dtype=torch.long,
)
.reshape(()),
subdomain_indices[0]
.to(
device=adjusted_domain_probabilities.device,
dtype=torch.long,
)
.reshape(()),
)
def _tensor_preserving_historical_int(
value: Any,
*args: Any,
) -> int | torch.Tensor:
"""Preserve scalar tensors only inside the cloned historical recursion.
Python's source-era ``_recursive_pass`` begins with ``int(domain_idx)`` and
``int(subdomain_idx)``. Its installed traversal owner is tensor-native,
while every genuine Python integer in that function must retain normal
``int`` behavior. A private globals table for that one function lets the
two scalar tensors survive without changing process-wide builtins or the
immutable parent module.
"""
if isinstance(value, torch.Tensor):
if args or value.numel() != 1:
raise RuntimeError("historical recursive tensor index is malformed")
return value.reshape(())
return int(value, *args)
def _tensor_preserving_historical_float(
value: Any = 0.0,
) -> float | torch.Tensor:
"""Keep frozen-parent diagnostic scalars on their current device.
The source-era recursive pass converts every diagnostic signal to
``float`` before appending it to a Python history list. On CUDA each
conversion executes ``Tensor.item()``, synchronizing the complete stream.
The frozen parent does not train from those scalar histories; its active
output is the routed hidden/logit tensor and its compact proof deliberately
omits the boundary-only histories. Preserve scalar tensors in that exact
path while retaining normal Python ``float`` behavior for configuration
constants and for the trainable historical path.
"""
if isinstance(value, torch.Tensor):
if value.numel() != 1:
raise RuntimeError("historical recursive float tensor is malformed")
return value.reshape(())
return float(value)
class _HistoricalRecursiveTorchFacade:
"""Keep the frozen recursive pass from staging one scalar per layer.
The verified source-era function has one ``torch.tensor`` call. It wraps
the already-known Python layer-arm identifier in a one-element CUDA tensor
after every model-selected expert. Constructing that tensor through the
generic host-data factory enters the synchronous H2D copy path. The arm
identifier is a kernel scalar, so an empty device tensor followed by
``fill_`` has identical values without a host buffer or stream fence.
All other torch attributes are delegated unchanged. This facade is
installed only in the private globals table of the cloned historical
recursive function; process-wide torch behavior is never modified.
"""
def __getattr__(self, name: str) -> Any:
return getattr(torch, name)
@staticmethod
def tensor(
data: object,
*,
device: torch.device,
dtype: torch.dtype,
) -> torch.Tensor:
if (
not isinstance(data, (list, tuple))
or len(data) != 1
or not isinstance(data[0], int)
or isinstance(data[0], bool)
or dtype != torch.long
):
raise RuntimeError(
"historical recursive device-scalar construction differs"
)
return torch.empty((1,), device=device, dtype=dtype).fill_(data[0])
def _historical_recursive_pass_with_tensor_route(
original: Callable[..., Any],
) -> Callable[..., Any]:
"""Clone one verified historical function with tensor-preserving scalars."""
if not isinstance(original, FunctionType):
raise RuntimeError("historical Resynthesis recursive pass is not a Python function")
recursive_globals = dict(original.__globals__)
recursive_globals["int"] = _tensor_preserving_historical_int
recursive_globals["torch"] = _HistoricalRecursiveTorchFacade()
tensor_route = FunctionType(
original.__code__,
recursive_globals,
original.__name__,
original.__defaults__,
original.__closure__,
)
frozen_globals = dict(recursive_globals)
frozen_globals["float"] = _tensor_preserving_historical_float
frozen_route = FunctionType(
original.__code__,
frozen_globals,
original.__name__,
original.__defaults__,
original.__closure__,
)
def recursive_pass(
self: Any,
*args: Any,
**kwargs: Any,
) -> Any:
implementation = (
frozen_route
if not self.training and not torch.is_grad_enabled()
else tensor_route
)
return implementation(self, *args, **kwargs)
recursive_pass.__kwdefaults__ = (
dict(original.__kwdefaults__)
if original.__kwdefaults__ is not None
else {}
)
recursive_pass.__annotations__ = dict(original.__annotations__)
recursive_pass.__qualname__ = original.__qualname__
recursive_pass.__doc__ = original.__doc__
return cast(Callable[..., Any], recursive_pass)
def _tensor_native_outcome_history_pack_step(
self: Any,
signals: Mapping[str, torch.Tensor],
domain_idx: int | torch.Tensor,
subdomain_idx: int | torch.Tensor,
stop_logit: torch.Tensor,
step_idx: int,
step_slots: int,
trace_summary: torch.Tensor,
) -> torch.Tensor:
"""Pack routed history without scalar indexing through the CPU."""
device = self.carry_h.device
dtype = self.domain_head.weight.dtype
utility = signals["utility"].reshape(()).to(device=device, dtype=dtype)
contradiction = signals["contradiction"].reshape(()).to(
device=device,
dtype=dtype,
)
rubric = signals["rubric"].reshape(()).to(device=device, dtype=dtype)
intent = signals["intent_conf"].reshape(()).to(device=device, dtype=dtype)
stop = stop_logit.reshape(()).to(device=device, dtype=dtype)
domain_t = _tensor_hotpath_index_boundary(
domain_idx,
reference=self.carry_h,
upper_bound=int(self.n_domains),
).to(device=device)
subdomain_t = _tensor_hotpath_index_boundary(
subdomain_idx,
reference=self.carry_h,
upper_bound=int(self.n_subdomains),
).to(device=device)
domain_one_hot = torch.zeros(
self.n_domains,
device=device,
dtype=dtype,
).scatter(
0,
domain_t.reshape(1),
torch.ones(1, device=device, dtype=dtype),
)
subdomain_one_hot = torch.zeros(
self.n_subdomains,
device=device,
dtype=dtype,
).scatter(
0,
subdomain_t.reshape(1),
torch.ones(1, device=device, dtype=dtype),
)
step_fraction = stop.new_full(
(),
float(step_idx + 1) / float(max(1, step_slots)),
)
trace = trace_summary.to(
device=device,
dtype=dtype,
).reshape(self.TRACE_FEAT_DIM)
return torch.cat(
(
utility.view(1),
contradiction.view(1),
rubric.view(1),
intent.view(1),
stop.view(1),
domain_one_hot,
subdomain_one_hot,
step_fraction.view(1),
trace,
),
dim=0,
)
def _tensor_native_historical_rbo_forward(
self: Any,
hidden: torch.Tensor,
baseline_logits: torch.Tensor | None = None,
intent_label: str | None = None,
swe_stage_target: torch.Tensor | None = None,
swe_stage_hidden: torch.Tensor | None = None,
project_logits: bool = True,
) -> Any:
"""Run the source-era parent while retaining model routes as tensors."""
self._hop_stop_delta_accum = hidden.new_zeros(())
self._hop_slice_delta_accum = hidden.new_zeros(())
control_hidden = hidden if swe_stage_hidden is None else swe_stage_hidden
intent_probs = self._intent_probs(control_hidden)
(
swe_stage_logits,
swe_stage_probs,
stage_domain_bias,
stage_subdomain_bias,
) = self.swe_stage_router(control_hidden)
stage_layer_bias = (
swe_stage_probs.mean(dim=0)
@ self.swe_stage_layer_affinity.to(
device=swe_stage_probs.device,
dtype=swe_stage_probs.dtype,
)
)
intent_idx_t = self._intent_index(intent_probs)
if intent_label is None:
intent_label = (
"model_owned_tensor"
if self.training
else self._intent_label(intent_probs, self.intent_names)
)
else:
intent_boundary_idx = (
self.intent_names.index(str(intent_label))
if str(intent_label) in self.intent_names
else self.intent_names.index("general")
if "general" in self.intent_names
else 0
)
intent_idx_t = intent_idx_t.new_empty((), dtype=torch.long).fill_(
intent_boundary_idx
)
hist_d, hist_s, _ = self.outcome_history.current_biases()
ctx_signals = self.context_encoder(control_hidden)
domain_conf_bias = ctx_signals["domain_conf"][0]
domain_count = self.arm_layout.n_domains
domain_confidence = domain_conf_bias[:domain_count]
domain_confidence = domain_confidence / (
domain_confidence.sum() + 1e-8
)
domain_log_boost = torch.log(domain_confidence.clamp(min=1e-6))
domain_probabilities, _, _, subdomain_indices = self.domain_router(
control_hidden,
intent_probs,
domain_log_bias=(
self.correction_domain_bias
+ hist_d.detach()
+ 0.1 * domain_log_boost
+ 0.2 * stage_domain_bias
),
subdomain_log_bias=(
self.correction_subdomain_bias
+ hist_s.detach()
+ 0.2 * stage_subdomain_bias
),
)
(
adjusted_domain_probabilities,
domain_collapse_score,
) = self.domain_collapse_detector(domain_probabilities)
self._last_domain_collapse_tensor = domain_collapse_score.detach()
domain_idx, subdomain_idx = _tensor_native_historical_domain_route(
adjusted_domain_probabilities,
subdomain_indices,
)
(
shaped_hidden,
routing_history,
feedback_history,
stop_logit_history,
traversal_history,
arms_used,
self_correction_steps,
) = self._recursive_pass(
hidden,
intent_probs,
domain_idx,
subdomain_idx,
ctx_signals,
stage_layer_bias,
control_hidden,
)
# The scalar history list is external receipt telemetry. Keep the current
# model value tensor-resident in the active graph; boundary snapshots can
# materialize it after the forward rather than synchronizing every wave.
self._last_domain_collapse_history = []
frozen_parent_hot_path = not self.training and not torch.is_grad_enabled()
if frozen_parent_hot_path:
# These four scalars supervise the historical parent only. Resynthesis
# freezes that parent and consumes shaped hidden/logit tensors, so
# rebuilding their BCE/CE stacks per retained wave cannot influence a
# routed-page gradient. Keep stateful history/context replay below.
dead_training_loss = hidden.new_zeros((), dtype=torch.float32)
contra_loss = dead_training_loss
stop_loss = dead_training_loss
correction_loss = dead_training_loss
stage_training_loss = dead_training_loss
else:
rubric_tensor = (
torch.stack([feedback["rubric"] for feedback in feedback_history])
if feedback_history
else hidden.new_zeros(0)
)
contrareactive_repulsion = getattr(
type(self),
"_resynthesis_contrareactive_repulsion",
None,
)
if not callable(contrareactive_repulsion):
raise RuntimeError(
"historical Resynthesis contrareactive owner is unavailable"
)
contra_loss = contrareactive_repulsion(
rubric_tensor,
floor=self.rbo_cfg.anti_floor,
weight=self.rbo_cfg.anti_weight,
)
stop_loss = self.stop_gate_training_loss()
correction_loss = self._correction_training_loss()
stage_training_loss = self._swe_stage_training_loss(
swe_stage_logits,
swe_stage_probs,
swe_stage_target,
)
history_loss = self.outcome_history_training_loss(
feedback_history,
stop_logit_history,
domain_idx=domain_idx,
subdomain_idx=subdomain_idx,
)
context_loss = (
dead_training_loss
if frozen_parent_hot_path
else self._context_dag_training_loss(
hidden,
intent_probs,
ctx_signals,
intent_idx_t,
feedback_history,
domain_idx=domain_idx,
subdomain_idx=subdomain_idx,
stage_domain_bias=stage_domain_bias,
stage_subdomain_bias=stage_subdomain_bias,
)
)
steps = len(feedback_history)
traversal_stop_reason = getattr(
self,
"_last_traversal_stop_reason",
"trained_gate",
)
shaped_logits = (
self.shaped_logits_from_hidden(
shaped_hidden,
baseline_logits,
hidden,
)
if project_logits
else None
)
if not self.training and shaped_logits is not None:
shaped_logits = self.rubric_bias.apply_bias(
shaped_logits,
shaped_hidden.detach(),
intent_probs.detach(),
strength=float(self.rbo_cfg.rubric_bias_strength),
)
self._detach_outcome_history_carry()
result_type = getattr(type(self), "_resynthesis_rbo_result_type", None)
stages = getattr(type(self), "_resynthesis_swe_stages", None)
if not callable(result_type) or not isinstance(stages, tuple):
raise RuntimeError("historical Resynthesis result boundary is unavailable")
stage_index_boundary = (
0
if frozen_parent_hot_path
else int(
swe_stage_probs.mean(dim=0)
.argmax()
.detach()
.to(device="cpu", dtype=torch.long)
)
)
return result_type(
shaped_hidden=shaped_hidden,
baseline_hidden=hidden,
shaped_logits=shaped_logits,
baseline_logits=baseline_logits,
steps=steps,
stop_reason=traversal_stop_reason,
intent_probs=intent_probs,
intent_label=intent_label,
swe_stage_probs=swe_stage_probs,
swe_stage_training_loss=stage_training_loss,
routing_history=routing_history,
feedback_history=feedback_history,
stop_logit_history=stop_logit_history,
traversal_history=traversal_history,
arms_used=arms_used,
domain_idx=domain_idx,
subdomain_idx=subdomain_idx,
self_correction_steps=self_correction_steps,
contrareactive_loss=contra_loss,
correction_loss=correction_loss,
stop_gate_loss=stop_loss,
outcome_history_loss=history_loss,
context_training_loss=context_loss,
proof=(
{
"resynthesisRBOActive": True,
"none_architecture": "Nest of Native Experts",
"none_model_owned": True,
"none_transfer_active": self._last_none_phase is not None,
}
if frozen_parent_hot_path
else {
"resynthesisRBOActive": True,
"none_architecture": "Nest of Native Experts",
"none_model_owned": True,
"none_transfer_active": self._last_none_phase is not None,
"none_outcome_writes": int(
self.none_fabric.outcome_writes.detach().cpu()
),
"none_phase_visits": (
self.none_fabric.phase_visits.detach().cpu().tolist()
),
"none_shaped_logits_present": isinstance(
shaped_logits,
torch.Tensor,
),
"none_pathway_phase": (
self._last_hop_signal.none_pathway.phase.detach().cpu().tolist()
if self._last_hop_signal is not None
else []
),
"none_pathway_gap": (
float(
self._last_hop_signal.none_pathway.gap.detach().cpu()
)
if self._last_hop_signal is not None
else 0.0
),
"none_pathway_completion": (
float(
self._last_hop_signal.none_pathway.completion.detach().cpu()
)
if self._last_hop_signal is not None
else 0.0
),
"none_pathway_runtime_gain": (
float(
self._last_hop_signal.none_pathway.runtime_gain.detach().cpu()
)
if self._last_hop_signal is not None
else 0.0
),
"intent": intent_label,
"swe_stage_idx": stage_index_boundary,
"swe_stage": stages[stage_index_boundary],
"domain_idx": domain_idx.detach().clone(),
"subdomain_idx": subdomain_idx.detach().clone(),
"steps": steps,
# The recursive pass returns the count owned by this exact forward.
# Reuse it in both the typed result and proof so mutable parent
# attribute layouts cannot substitute stale or default telemetry.
"self_correction_steps": self_correction_steps,
"traversal_layers": (
traversal_history[-1] if traversal_history else []
),
"traversal_stop_reason": traversal_stop_reason,
"arms_used": arms_used,
"outcome_memory": self.outcome_memory_snapshot(),
"identity_state": {
"boundary_only": True,
"identity_dim": int(self.rbo_cfg.identity_dim),
"n_layers": len(self.experts),
},
"outcome_history_steps": len(feedback_history),
"outcome_history_carry_norm": float(
self.outcome_history.carry_h.norm().detach(),
),
"hop_traversal": {
"from_hop_idx": (
self._last_hop_signal.from_hop_idx
if self._last_hop_signal
else 0
),
"dest_hop_idx": (
self._last_hop_signal.dest_hop_idx
if self._last_hop_signal
else 0
),
"hop_confidence": (
float(self._last_hop_signal.hop_confidence.detach())
if self._last_hop_signal is not None
else 0.0
),
"hop_bonus": (
float(self._last_hop_signal.hop_bonus.detach())
if self._last_hop_signal is not None
else 0.0
),
"none_stop_delta": (
float(
self._last_hop_signal.none_pathway.stop_delta.detach()
)
if self._last_hop_signal is not None
else 0.0
),
"none_slice_delta": (
float(
self._last_hop_signal.none_pathway.slice_delta.detach()
)
if self._last_hop_signal is not None
else 0.0
),
"stop_delta_accum": self._boundary_float(
self._hop_stop_delta_accum
),
"slice_delta_accum": self._boundary_float(
self._hop_slice_delta_accum
),
},
}
),
)
def _historical_rbo_init_with_tensor_intent_mapping(
self: Any,
*args: Any,
**kwargs: Any,
) -> None:
"""Materialize the source-era intent map once, before the RBO moves to CUDA."""
owner = type(self)
original = getattr(owner, "_resynthesis_original_rbo_init", None)
intent_to_capability = getattr(
owner,
"_resynthesis_intent_to_capability_boundary",
None,
)
capability_count = getattr(
owner,
"_resynthesis_intent_capability_count",
None,
)
if not callable(original) or not callable(intent_to_capability):
raise RuntimeError("historical Resynthesis intent constructor was not preserved")
if (
not isinstance(capability_count, int)
or isinstance(capability_count, bool)
or capability_count < 1
):
raise RuntimeError("historical Resynthesis capability count is invalid")
original(self, *args, **kwargs)
intent_names = getattr(self, "intent_names", None)
arm_layout = getattr(self, "arm_layout", None)
reference = getattr(self, "layer_pick_logits", None)
if (
not isinstance(intent_names, (list, tuple))
or not intent_names
or not all(isinstance(name, str) for name in intent_names)
or not isinstance(reference, torch.Tensor)
):
raise RuntimeError("historical Resynthesis intent geometry is malformed")
n_domains = getattr(arm_layout, "n_domains", None)
n_subdomains = getattr(arm_layout, "n_subdomains", None)
if (
not isinstance(n_domains, int)
or isinstance(n_domains, bool)
or n_domains < 1
or not isinstance(n_subdomains, int)
or isinstance(n_subdomains, bool)
or n_subdomains < 1
):
raise RuntimeError("historical Resynthesis intent route geometry is malformed")
# This is the one explicit source-compatibility boundary. It exhaustively
# resolves every classifier row through the hash-verified source-era map.
# The active forward only gathers these tensors; it has no string/default
# route and never reads the selected CUDA scalar on the host.
capability_indices = tuple(
intent_to_capability(intent_name) for intent_name in intent_names
)
if not all(
isinstance(index, int)
and not isinstance(index, bool)
and 0 <= index < capability_count
for index in capability_indices
):
raise RuntimeError("historical Resynthesis intent capability map is invalid")
capability_map = torch.tensor(
capability_indices,
device=reference.device,
dtype=torch.long,
)
domain_map = capability_map.remainder(n_domains)
subdomain_map = torch.div(
capability_map,
n_domains,
rounding_mode="floor",
).remainder(n_subdomains)
for name, value in (
("_resynthesis_intent_capability_map", capability_map),
("_resynthesis_intent_domain_map", domain_map),
("_resynthesis_intent_subdomain_map", subdomain_map),
):
if hasattr(self, name):
raise RuntimeError("historical Resynthesis intent map is already attached")
self.register_buffer(name, value, persistent=False)
none_fabric = getattr(self, "none_fabric", None)
none_geometry = getattr(none_fabric, "geometry", None)
phase_count = getattr(none_geometry, "n_phases", None)
if (
not isinstance(phase_count, int)
or isinstance(phase_count, bool)
or phase_count < 1
):
raise RuntimeError("historical Resynthesis phase geometry is malformed")
self.register_buffer(
"_resynthesis_none_phase_selector_t",
torch.eye(
phase_count,
device=reference.device,
dtype=reference.dtype,
),
persistent=False,
)
def _tensor_native_historical_none_step_phase(
self: Any,
*,
commit: Any,
phase_hidden: torch.Tensor,
observation_hidden: torch.Tensor,
step_idx: int,
) -> Any:
"""Run one historical Fabric phase without a host-created CUDA scalar."""
phase_selector_t = getattr(
self,
"_resynthesis_none_phase_selector_t",
None,
)
none_fabric = getattr(self, "none_fabric", None)
none_geometry = getattr(none_fabric, "geometry", None)
phase_count = getattr(none_geometry, "n_phases", None)
step_phase = getattr(none_fabric, "step_phase", None)
if (
not isinstance(step_idx, int)
or isinstance(step_idx, bool)
or not isinstance(phase_count, int)
or isinstance(phase_count, bool)
or phase_count < 1
or not isinstance(phase_selector_t, torch.Tensor)
or phase_selector_t.shape != (phase_count, phase_count)
or phase_selector_t.device != phase_hidden.device
or phase_selector_t.dtype != phase_hidden.dtype
or not callable(step_phase)
):
raise RuntimeError("historical Resynthesis phase selector differs")
expert_state, layer_state = self._none_expert_layer_state(phase_hidden)
phase_weights = phase_selector_t[
step_idx % phase_count
].reshape(1, phase_count).expand(phase_hidden.shape[0], -1)
compact_phase = torch.tanh(self.none_hidden_in(phase_hidden))
compact_observation = torch.tanh(
self.none_hidden_in(observation_hidden)
)
return step_phase(
commit,
compact_phase,
compact_observation,
expert_state,
layer_state,
phase_weights,
)
def _tensor_native_historical_intent_route(
self: Any,
intent_probs: torch.Tensor,
intents: list[str] | tuple[str, ...],
) -> _HistoricalTensorIntentRoute:
"""Select and map the exact historical intent without a CUDA host read."""
capability_map = getattr(self, "_resynthesis_intent_capability_map", None)
domain_map = getattr(self, "_resynthesis_intent_domain_map", None)
subdomain_map = getattr(self, "_resynthesis_intent_subdomain_map", None)
expected_shape = (len(intents),)
if (
intent_probs.ndim != 3
or intent_probs.shape[-1] != len(intents)
or not isinstance(capability_map, torch.Tensor)
or capability_map.shape != expected_shape
or capability_map.device != intent_probs.device
or capability_map.dtype != torch.long
or not isinstance(domain_map, torch.Tensor)
or domain_map.shape != expected_shape
or domain_map.device != intent_probs.device
or domain_map.dtype != torch.long
or not isinstance(subdomain_map, torch.Tensor)
or subdomain_map.shape != expected_shape
or subdomain_map.device != intent_probs.device
or subdomain_map.dtype != torch.long
):
raise RuntimeError("historical Resynthesis tensor intent map differs")
intent_index = intent_probs.mean(dim=(0, 1)).argmax().to(
dtype=torch.long
).reshape(())
selector = intent_index.reshape(1)
return _HistoricalTensorIntentRoute(
intent_index=intent_index,
capability_index=capability_map.index_select(0, selector).reshape(()),
domain_index=domain_map.index_select(0, selector).reshape(()),
subdomain_index=subdomain_map.index_select(0, selector).reshape(()),
)
def _tensor_native_none_pathway_training_loss(
self: Any,
packet: Any,
*,
receiver_capability_idx: int | torch.Tensor,
phase_target: torch.Tensor,
gap_target: torch.Tensor,
completion_target: torch.Tensor,
) -> torch.Tensor:
"""Preserve the historical NoNE loss with tensor receiver indexing."""
transfer = packet.transfer
receiver = _tensor_hotpath_index_boundary(
receiver_capability_idx,
reference=transfer,
upper_bound=int(self.n_capabilities),
)
epsilon = torch.finfo(transfer.dtype).eps
phase_target = phase_target.to(
device=packet.phase.device,
dtype=packet.phase.dtype,
).reshape_as(packet.phase)
phase_target = phase_target / phase_target.sum().clamp_min(epsilon)
gap_target = gap_target.to(
device=packet.gap.device,
dtype=packet.gap.dtype,
).reshape(())
completion_target = completion_target.to(
device=packet.completion.device,
dtype=packet.completion.dtype,
).reshape(())
phase_loss = -(phase_target * packet.phase.clamp_min(epsilon).log()).sum()
transfer_loss = -transfer.index_select(
0,
receiver.reshape(1),
).reshape(()).clamp_min(epsilon).log()
state_loss = F.binary_cross_entropy(
packet.gap,
gap_target.clamp(0.0, 1.0),
)
state_loss = state_loss + F.binary_cross_entropy(
packet.completion,
completion_target.clamp(0.0, 1.0),
)
desired_gain = torch.maximum(
gap_target,
torch.ones_like(completion_target) - completion_target,
).clamp(0.0, 1.0)
gain_loss = F.mse_loss(packet.runtime_gain, desired_gain)
stop_target = completion_target - gap_target
slice_target = gap_target - completion_target
traversal_loss = F.mse_loss(packet.stop_delta, stop_target)
traversal_loss = traversal_loss + F.mse_loss(
packet.slice_delta,
slice_target,
)
route_target = (gap_target - completion_target).reshape(())
route_loss = F.mse_loss(packet.domain_delta.mean(), route_target)
route_loss = route_loss + F.mse_loss(packet.layer_delta.mean(), route_target)
route_loss = route_loss + F.mse_loss(packet.expert_delta.mean(), route_target)
return cast(
torch.Tensor,
phase_loss
+ transfer_loss
+ state_loss
+ 0.25 * gain_loss
+ 0.10 * traversal_loss
+ 0.05 * route_loss,
)
def _historical_tensor_native_identity_supervision_loss(
self: Any,
hidden: torch.Tensor,
intent_probs: torch.Tensor,
ctx_signals: Mapping[str, torch.Tensor],
*,
target_domain_idx: int | torch.Tensor,
target_capability_idx: int | torch.Tensor,
) -> torch.Tensor:
"""Preserve historical identity supervision with tensor route indices."""
n_layers = len(self.experts)
if n_layers <= 0:
return hidden.new_zeros(())
transfer_weights = ctx_signals.get("transfer_weights")
layer_scores = self._layer_identity_bias(
hidden,
intent_probs,
transfer_weights,
n_layers,
)
target_domain = _tensor_hotpath_index_boundary(
target_domain_idx,
reference=self.domain_layer_affinity,
upper_bound=int(self.domain_layer_affinity.shape[0]),
)
layer_target = F.softmax(
self.domain_layer_affinity.index_select(
0,
target_domain.reshape(1),
)
.squeeze(0)[:n_layers]
.detach(),
dim=-1,
)
layer_loss = -(layer_target * F.log_softmax(layer_scores, dim=-1)).sum()
capability_index = _tensor_hotpath_index_boundary(
target_capability_idx,
reference=hidden,
upper_bound=10,
)
capability_target = F.one_hot(
capability_index,
num_classes=10,
).to(device=hidden.device, dtype=hidden.dtype)
capability_losses = tuple(
F.mse_loss(
torch.sigmoid(
expert.flat_expert_capability.to(
device=hidden.device,
dtype=hidden.dtype,
)
),
capability_target.unsqueeze(0).expand_as(
expert.flat_expert_capability
),
)
for expert in self.experts
)
capability_loss = (
torch.stack(capability_losses).mean()
if capability_losses
else hidden.new_zeros(())
)
layer_capability = torch.stack(
tuple(expert.capability_scores for expert in self.experts),
dim=0,
).to(device=hidden.device, dtype=hidden.dtype)
layer_capability_loss = F.mse_loss(
torch.sigmoid(layer_capability),
capability_target.unsqueeze(0).expand_as(layer_capability),
)
specialization = torch.stack(
tuple(expert.specialization for expert in self.experts),
dim=0,
).to(device=hidden.device, dtype=hidden.dtype)
specialization_target = (layer_target * float(n_layers)).clamp(0.0, 1.0)
specialization_loss = F.mse_loss(
torch.sigmoid(specialization),
specialization_target,
)
routing_fingerprints = torch.stack(
tuple(expert.routing_fingerprint for expert in self.experts),
dim=0,
)
routing_fingerprint_loss = self._identity_orthogonality_loss(
routing_fingerprints
)
return cast(
torch.Tensor,
layer_loss
+ 0.10 * capability_loss
+ 0.10 * layer_capability_loss
+ 0.05 * specialization_loss
+ self.rbo_cfg.identity_diversity_weight
* self._identity_diversity_loss()
+ self.rbo_cfg.identity_diversity_weight * routing_fingerprint_loss
+ self.rbo_cfg.profile_diversity_weight * self._profile_diversity_loss(),
)
def _historical_tensor_native_context_dag_training_loss(
self: Any,
hidden: torch.Tensor,
intent_probs: torch.Tensor,
ctx_signals: Mapping[str, torch.Tensor],
intent_label: str | torch.Tensor | _HistoricalTensorIntentRoute,
feedback_history: list[Mapping[str, torch.Tensor]],
*,
domain_idx: int | torch.Tensor,
subdomain_idx: int | torch.Tensor,
stage_domain_bias: torch.Tensor | None = None,
stage_subdomain_bias: torch.Tensor | None = None,
) -> torch.Tensor:
"""Run the exact source-era semantic loss from a tensor intent route."""
if isinstance(intent_label, str):
original = getattr(
type(self),
"_resynthesis_original_context_dag_training_loss",
None,
)
if not callable(original):
raise RuntimeError("historical Resynthesis context loss was not preserved")
return cast(
torch.Tensor,
original(
self,
hidden,
intent_probs,
ctx_signals,
intent_label,
feedback_history,
domain_idx=domain_idx,
subdomain_idx=subdomain_idx,
stage_domain_bias=stage_domain_bias,
stage_subdomain_bias=stage_subdomain_bias,
),
)
capability_map = self._resynthesis_intent_capability_map
domain_map = self._resynthesis_intent_domain_map
subdomain_map = self._resynthesis_intent_subdomain_map
if isinstance(intent_label, torch.Tensor):
intent_route: _HistoricalTensorIntentRoute | None = None
route_intent_index = intent_label
else:
intent_route = _normalize_historical_tensor_intent_route(intent_label)
route_intent_index = intent_route.intent_index
intent_index = _tensor_hotpath_index_boundary(
route_intent_index,
reference=capability_map,
upper_bound=int(capability_map.numel()),
)
selector = intent_index.reshape(1)
capability_index = capability_map.index_select(0, selector).reshape(())
target_domain = domain_map.index_select(0, selector).reshape(())
target_subdomain = subdomain_map.index_select(0, selector).reshape(())
if intent_route is not None:
# Older parent generations returned a typed route packet and therefore
# carry redundant mapped indices that remain exact integrity proofs.
# Current native parents already pass the model-owned scalar tensor
# directly; its maps are gathered above without a host readback.
torch._assert_async(
capability_index.eq(intent_route.capability_index),
"historical Resynthesis intent capability route differs",
)
torch._assert_async(
target_domain.eq(intent_route.domain_index),
"historical Resynthesis intent domain route differs",
)
torch._assert_async(
target_subdomain.eq(intent_route.subdomain_index),
"historical Resynthesis intent subdomain route differs",
)
zero = hidden.new_zeros(())
epsilon = torch.finfo(hidden.float().dtype).eps
domain_confidence = ctx_signals["domain_conf"].clamp_min(epsilon)
capability_loss = -torch.log(
domain_confidence.index_select(
1,
capability_index.reshape(1),
).clamp_min(epsilon)
).mean()
depth_probabilities = ctx_signals["depth_probs"].clamp_min(epsilon)
depth_index = min(
max(len(feedback_history) - 1, 0),
depth_probabilities.shape[-1] - 1,
)
depth_loss = -torch.log(
depth_probabilities[:, depth_index].clamp_min(epsilon)
).mean()
if feedback_history:
rubric_values = torch.stack(
tuple(
feedback["rubric"]
.detach()
.reshape(())
.to(device=hidden.device, dtype=hidden.dtype)
for feedback in feedback_history
)
)
completion_target = rubric_values.mean().clamp(0.0, 1.0)
complexity_target = torch.ones_like(completion_target) - completion_target
else:
completion_target = hidden.new_ones(()).mul_(0.5)
complexity_target = hidden.new_ones(()).mul_(0.5)
complexity_loss = F.mse_loss(
ctx_signals["complexity"],
complexity_target.expand_as(ctx_signals["complexity"]),
)
transfer_owner = self.cross_domain_router.knowledge_transfer
relatedness = (
transfer_owner.relatedness_prior.index_select(
0,
capability_index.reshape(1),
)
.squeeze(0)
.to(device=hidden.device, dtype=hidden.dtype)
.clone()
)
capability_mask = torch.arange(
transfer_owner.n_capabilities,
device=hidden.device,
).ne(capability_index)
relatedness = relatedness * capability_mask.to(dtype=relatedness.dtype)
relatedness_mass = relatedness.sum()
self_capability = F.one_hot(
capability_index,
num_classes=transfer_owner.n_capabilities,
).to(device=hidden.device, dtype=hidden.dtype)
relatedness = torch.where(
relatedness_mass.le(epsilon),
self_capability,
relatedness / relatedness_mass.clamp_min(epsilon),
)
transfer_weights = ctx_signals["transfer_weights"].clamp_min(epsilon)
transfer_loss = F.kl_div(
transfer_weights.log(),
relatedness.unsqueeze(0).expand_as(transfer_weights),
reduction="batchmean",
)
visit_scores, _ = transfer_owner.neural_dag(
hidden=hidden,
start_cap=capability_index,
)
dag_loss = F.kl_div(
visit_scores.clamp_min(epsilon).log(),
relatedness,
reduction="sum",
)
outcome_pressure = self.arm_registry.domain_slot_pressure().sum(dim=-1)
donor = transfer_owner.donor_weights_for_pressure(
target_domain,
outcome_pressure,
hidden=hidden,
)
none_packet = transfer_owner.build_none_pathway_packet(
target_domain,
donor=donor,
hidden=hidden,
outcome_pressure=outcome_pressure,
n_layers=len(self.experts),
n_experts=self.cfg.total_experts,
)
gap_target = complexity_target.clamp(0.0, 1.0)
phase_target = torch.stack(
(
0.10 * (torch.ones_like(gap_target) - gap_target),
0.35 * gap_target,
0.65 * gap_target,
completion_target,
)
)
receiver_capability = relatedness.argmax().to(dtype=torch.long).reshape(())
none_pathway_loss = transfer_owner.none_pathway_training_loss(
none_packet,
receiver_capability_idx=receiver_capability,
phase_target=phase_target,
gap_target=gap_target,
completion_target=completion_target,
)
domain_probabilities, subdomain_probabilities, _, _ = self.domain_router(
hidden,
intent_probs,
domain_log_bias=stage_domain_bias,
subdomain_log_bias=stage_subdomain_bias,
)
route_loss = -torch.log(
domain_probabilities.index_select(
1,
target_domain.reshape(1),
).clamp_min(epsilon)
).mean()
route_loss = route_loss - torch.log(
subdomain_probabilities.index_select(
1,
target_subdomain.reshape(1),
).clamp_min(epsilon)
).mean()
observed_domain = (
domain_idx.detach().to(device=hidden.device, dtype=torch.long).reshape(())
if isinstance(domain_idx, torch.Tensor)
else hidden.new_empty((), dtype=torch.long).fill_(domain_idx)
)
observed_subdomain = (
subdomain_idx.detach().to(
device=hidden.device,
dtype=torch.long,
).reshape(())
if isinstance(subdomain_idx, torch.Tensor)
else hidden.new_empty((), dtype=torch.long).fill_(subdomain_idx)
)
observed_valid = (
observed_domain.ge(0)
.logical_and(observed_domain.lt(domain_probabilities.shape[-1]))
.logical_and(observed_subdomain.ge(0))
.logical_and(
observed_subdomain.lt(subdomain_probabilities.shape[-1])
)
)
observed_domain = observed_domain.clamp(
min=0,
max=domain_probabilities.shape[-1] - 1,
)
observed_subdomain = observed_subdomain.clamp(
min=0,
max=subdomain_probabilities.shape[-1] - 1,
)
observed_slot_loss = -torch.log(
domain_probabilities.index_select(
1,
observed_domain.reshape(1),
).clamp_min(epsilon)
).mean()
observed_slot_loss = observed_slot_loss - torch.log(
subdomain_probabilities.index_select(
1,
observed_subdomain.reshape(1),
).clamp_min(epsilon)
).mean()
observed_slot_loss = (
observed_slot_loss
* observed_valid.to(device=hidden.device, dtype=hidden.dtype)
)
identity_loss = self._identity_supervision_loss(
hidden,
intent_probs,
ctx_signals,
target_domain_idx=target_domain,
target_capability_idx=capability_index,
)
return cast(
torch.Tensor,
0.35 * capability_loss
+ 0.20 * depth_loss
+ 0.15 * complexity_loss
+ 0.25 * transfer_loss
+ 0.25 * dag_loss
+ 0.20 * none_pathway_loss
+ 0.20 * route_loss
+ 0.05 * observed_slot_loss
+ 0.08 * identity_loss
+ zero,
)
def _historical_none_fabric_init_with_tensor_constants(
self: Any,
geometry: Any,
) -> None:
"""Install the immutable Fabric's device-resident scalar geometry.
The historical ``form_commit`` rebuilt the atomic-graph width with
``Tensor.new_tensor`` on every parent forward. On CUDA that host-to-device
scalar copy synchronizes the parent stream. Registering the exact scalar
once keeps it with the module across device/dtype moves. It is
nonpersistent because it is derived entirely from the already-authoritative
geometry and therefore must not alter checkpoint identity.
"""
original = getattr(
type(self),
"_resynthesis_original_none_fabric_init",
None,
)
if not callable(original):
raise RuntimeError("historical NoNE Fabric constructor was not preserved")
original(self, geometry)
graph_node_credit = getattr(self, "graph_node_credit", None)
if not isinstance(graph_node_credit, torch.Tensor):
raise RuntimeError("historical NoNE Fabric graph geometry differs")
self.register_buffer(
"_resynthesis_atomic_graph_slots_scale_t",
graph_node_credit.new_full((), geometry.atomic_graph_slots),
persistent=False,
)
def _tensor_native_historical_none_fabric_form_commit(
self: Any,
surface_glyphs: torch.Tensor,
evidence_logits: torch.Tensor,
capability_gap: torch.Tensor,
) -> Any:
"""Form the exact historical Fabric commit without CUDA scalar copies."""
if surface_glyphs.ndim != 3:
raise ValueError(
"surface_glyphs must have shape [batch, obligations, hidden]"
)
if evidence_logits.ndim != 2:
raise ValueError(
"evidence_logits must have shape [batch, obligations]"
)
if capability_gap.ndim != 2 or capability_gap.shape[-1] != 3:
raise ValueError("capability_gap must have shape [batch, 3]")
if surface_glyphs.shape[1] != self.geometry.n_obligations:
raise ValueError(
"surface_glyphs obligation axis does not match Fabric geometry"
)
identity = self.architecture_identity.unsqueeze(1)
encoded = torch.tanh(self.surface_encoder(surface_glyphs + identity))
preliminary_state = self.commit_encoder(encoded.mean(dim=1))
learned_evidence = self.obligation_evidence(encoded).squeeze(-1)
support = torch.sigmoid(evidence_logits + learned_evidence)
requirements = torch.sigmoid(self.commit_requirement_logits).unsqueeze(0)
obligation_margin = support - requirements
learned_memory = self.outcome_memory_reader(
self.outcome_memory.mean(dim=0, keepdim=True)
).expand(surface_glyphs.shape[0], -1)
state = torch.tanh(
preliminary_state
+ self.commit_obligation_encoder(obligation_margin)
+ self.capability_pressure_encoder(capability_gap)
+ learned_memory
)
atomic_graph = self.atomic_task_graph(
state,
encoded,
support,
capability_gap,
)
graph_credit_logits = (
self.graph_node_credit - self.graph_rollback_pressure
).to(device=state.device, dtype=state.dtype)
graph_slots_scale_t = self._resynthesis_atomic_graph_slots_scale_t.to(
device=state.device,
dtype=state.dtype,
)
graph_credit_scale = (
torch.softmax(graph_credit_logits, dim=-1) * graph_slots_scale_t
)
graph_ready_weights = (
atomic_graph.ready_weights * graph_credit_scale.unsqueeze(0)
)
graph_repair_scale = 2.0 * torch.sigmoid(
self.graph_repair_credit.to(device=state.device, dtype=state.dtype)
)
graph_repair_weights = (
atomic_graph.repair_weights * graph_repair_scale.unsqueeze(0)
)
session_present = self.session_graph_present.to(
device=state.device,
dtype=state.dtype,
)
if self.training:
session_present = torch.zeros_like(session_present)
prior_frozen = self.session_graph_frozen_weights.to(
device=state.device,
dtype=state.dtype,
)
node_keep = (session_present * prior_frozen).reshape(1, -1)
graph_node_state = torch.lerp(
atomic_graph.node_state,
self.session_graph_node_state.to(
device=state.device,
dtype=state.dtype,
)
.unsqueeze(0)
.expand_as(atomic_graph.node_state),
node_keep.unsqueeze(-1),
)
edge_keep = node_keep.unsqueeze(-1) * node_keep.unsqueeze(-2)
graph_edge_weights = torch.lerp(
atomic_graph.edge_weights,
self.session_graph_edge_weights.to(
device=state.device,
dtype=state.dtype,
)
.unsqueeze(0)
.expand_as(atomic_graph.edge_weights),
edge_keep,
)
graph_validated_weights = torch.maximum(
atomic_graph.validated_weights,
self.session_graph_validated_weights.to(
device=state.device,
dtype=state.dtype,
).unsqueeze(0)
* session_present,
)
graph_frozen_weights = torch.maximum(
atomic_graph.frozen_weights,
prior_frozen.unsqueeze(0) * session_present,
)
graph_repair_weights = graph_repair_weights * (
1.0 - graph_frozen_weights
)
graph_summary_weights = (
graph_ready_weights + graph_repair_weights + graph_frozen_weights
)
graph_summary = self.atomic_task_graph.graph_summary_head(
torch.einsum(
"bn,bnh->bh",
graph_summary_weights,
graph_node_state,
)
/ graph_summary_weights.sum(dim=-1, keepdim=True).clamp_min(
torch.finfo(graph_summary_weights.dtype).tiny
)
)
state = torch.tanh(state + graph_summary)
if not self.training:
with torch.no_grad():
self.session_graph_node_state.copy_(
graph_node_state.detach().mean(dim=0)
)
self.session_graph_edge_weights.copy_(
graph_edge_weights.detach().mean(dim=0)
)
self.session_graph_validated_weights.copy_(
graph_validated_weights.detach().mean(dim=0)
)
self.session_graph_frozen_weights.copy_(
graph_frozen_weights.detach().mean(dim=0)
)
self.session_graph_repair_weights.copy_(
graph_repair_weights.detach().mean(dim=0)
)
self.session_graph_present.fill_(True)
scope_completeness = obligation_margin.amin(dim=-1, keepdim=True)
edit_authorization = (scope_completeness >= 0).to(surface_glyphs.dtype)
mutating_probability = torch.einsum(
"bno,o->bn",
atomic_graph.operation_probs,
self.atomic_task_graph.mutating_operation_mask.to(
device=state.device,
dtype=state.dtype,
),
)
graph_execution_authorization = (
1.0
- mutating_probability
+ mutating_probability * edit_authorization
).clamp(min=0.0, max=1.0)
unresolved_tickets = (
encoded * torch.relu(-obligation_margin).unsqueeze(-1)
)
commit_expert_source = self._record_causal_gradient(
self.commit_expert_source(state),
0,
)
commit_expert_destination = self._record_causal_gradient(
self.commit_expert_destination(state),
1,
)
commit_layer_source = self._record_causal_gradient(
self.commit_layer_source(state),
2,
)
commit_layer_destination = self._record_causal_gradient(
self.commit_layer_destination(state),
3,
)
expert_logits = self._pair_logits(
commit_expert_source,
commit_expert_destination,
self.expert_pair_prior,
self.expert_transfer_credit,
)
layer_logits = self._pair_logits(
commit_layer_source,
commit_layer_destination,
self.layer_pair_prior,
self.layer_transfer_credit,
)
research_branch_logits = self._record_causal_gradient(
self.research_branch_head(state),
4,
)
unresolved_pressure = torch.relu(-scope_completeness)
research_pressure = torch.sigmoid(
self.research_pressure_head(state)
+ unresolved_pressure
+ capability_gap[:, 0:1]
)
tool_build_pressure = torch.sigmoid(
self.tool_build_head(state)
+ unresolved_pressure
+ capability_gap[:, 1:2]
)
environment_build_pressure = torch.sigmoid(
self.environment_build_head(state)
+ unresolved_pressure
+ capability_gap[:, 2:3]
)
commit_type = getattr(
type(self),
"_resynthesis_none_fabric_commit_type",
None,
)
if not isinstance(commit_type, type):
raise RuntimeError("historical NoNE Fabric commit type is unavailable")
return commit_type(
state=state,
obligation_support=support,
unresolved_tickets=unresolved_tickets,
scope_completeness=scope_completeness,
edit_authorization=edit_authorization,
expert_source_state=commit_expert_source,
expert_destination_state=commit_expert_destination,
layer_source_state=commit_layer_source,
layer_destination_state=commit_layer_destination,
expert_transfer_intent=self._off_diagonal_softmax(expert_logits),
layer_transfer_intent=self._off_diagonal_softmax(layer_logits),
research_branch_weights=F.softmax(research_branch_logits, dim=-1),
research_pressure=research_pressure,
tool_build_pressure=tool_build_pressure,
environment_build_pressure=environment_build_pressure,
graph_node_state=graph_node_state,
graph_operation_logits=atomic_graph.operation_logits,
graph_operation_probs=atomic_graph.operation_probs,
graph_argument_state=atomic_graph.argument_state,
graph_observation_binding=atomic_graph.observation_binding,
graph_execution_authorization=graph_execution_authorization,
graph_edge_weights=graph_edge_weights,
graph_refinement_parent_weights=(
atomic_graph.refinement_parent_weights
),
graph_atomicity=atomic_graph.atomicity,
graph_input_interfaces=atomic_graph.input_interfaces,
graph_output_interfaces=atomic_graph.output_interfaces,
graph_interface_compatibility=(
atomic_graph.interface_compatibility
),
graph_simulation_risk=atomic_graph.simulation_risk,
graph_ready_weights=graph_ready_weights,
graph_parallel_weights=atomic_graph.parallel_weights,
graph_validated_weights=graph_validated_weights,
graph_affected_weights=atomic_graph.affected_weights,
graph_frozen_weights=graph_frozen_weights,
graph_repair_weights=graph_repair_weights,
graph_summary=graph_summary,
)
def _install_historical_tensor_native_hotpaths(
rbo_module: Any,
experts_module: Any,
transfer_module: Any,
traversal_module: Any,
) -> str:
"""Bind hash-verified historical classes to equivalent tensor hot paths."""
expert_bank = getattr(experts_module, "FactorizedGranularExpertBank", None)
transfer = getattr(transfer_module, "KnowledgeTransferSurfaces", None)
intent_to_capability = getattr(
transfer_module,
"intent_to_capability",
None,
)
capability_count = getattr(transfer_module, "N_CAPABILITIES", None)
pathway_packet_type = getattr(transfer_module, "NoNEPathwayPacket", None)
hop_router = getattr(traversal_module, "CrossDomainHopRouter", None)
signal_type = getattr(traversal_module, "HopTraversalSignal", None)
outcome_history = getattr(traversal_module, "OutcomeHistoryEncoder", None)
rbo_type = getattr(rbo_module, _legacy_parent_class_name("RBO"), None)
rbo_result_type = getattr(
rbo_module,
_legacy_parent_class_name("RBOResult"),
None,
)
rubric_bias_type = getattr(rbo_module, "RubricLogitBias", None)
contrareactive_repulsion = getattr(
rbo_module,
"contrareactive_repulsion",
None,
)
swe_stages = getattr(rbo_module, "SWE_STAGES", None)
correction_controller = getattr(
rbo_module,
"SelfCorrectionController",
None,
)
domain_collapse_detector = getattr(
rbo_module,
"DomainCollapseDetector",
None,
)
none_fabric_type = getattr(
rbo_module,
_legacy_parent_class_name("NoNEFabric"),
None,
)
none_fabric_commit_type = getattr(rbo_module, "NoNEFabricCommit", None)
if not all(
isinstance(value, type)
for value in (
rbo_type,
rbo_result_type,
expert_bank,
transfer,
hop_router,
outcome_history,
rubric_bias_type,
none_fabric_type,
none_fabric_commit_type,
)
):
raise RuntimeError("historical Resynthesis hot-path classes are unavailable")
if (
signal_type is None
or not isinstance(pathway_packet_type, type)
or not callable(intent_to_capability)
or not callable(contrareactive_repulsion)
or not isinstance(swe_stages, tuple)
or not isinstance(capability_count, int)
or isinstance(capability_count, bool)
or capability_count < 1
):
raise RuntimeError("historical Resynthesis hop-signal type is unavailable")
if not all(
callable(getattr(owner, method, None))
for owner, method in (
(expert_bank, "apply_topk"),
(transfer, "_cap_weights_from_domain"),
(transfer, "_pressure_on_capabilities"),
(transfer, "donor_weights_for_pressure"),
(transfer, "build_none_pathway_packet"),
(transfer, "none_pathway_training_loss"),
(hop_router, "compute_hop_signal"),
(rbo_type, "_intent_label"),
(rbo_type, "_context_dag_training_loss"),
(rbo_type, "_identity_supervision_loss"),
(rbo_type, "_plan_layer_traversal"),
(rbo_type, "_comm_from_prior_delta"),
(rbo_type, "_correction_training_loss"),
(rbo_type, "layer_gate_scale"),
(rbo_type, "_joint_stop_logit"),
(rbo_type, "_none_step_phase"),
(rbo_type, "_recursive_pass"),
(rbo_type, "forward"),
(outcome_history, "_pack_step"),
(none_fabric_type, "form_commit"),
)
):
raise RuntimeError("historical Resynthesis hot-path method contract differs")
if not bool(
getattr(
none_fabric_type,
"_resynthesis_tensor_commit_installed",
False,
)
):
setattr(
none_fabric_type,
"_resynthesis_original_none_fabric_init",
getattr(none_fabric_type, "__init__"),
)
setattr(
none_fabric_type,
"_resynthesis_none_fabric_commit_type",
none_fabric_commit_type,
)
setattr(
none_fabric_type,
"__init__",
_historical_none_fabric_init_with_tensor_constants,
)
setattr(
none_fabric_type,
"form_commit",
_tensor_native_historical_none_fabric_form_commit,
)
setattr(
none_fabric_type,
"_resynthesis_tensor_commit_installed",
True,
)
setattr(expert_bank, "apply_topk", _tensor_native_expert_apply_topk)
setattr(
transfer, "_cap_weights_from_domain", _tensor_native_cap_weights_from_domain
)
setattr(
transfer,
"_pressure_on_capabilities",
_tensor_native_pressure_on_capabilities,
)
setattr(
transfer,
"donor_weights_for_pressure",
_tensor_native_donor_weights_for_pressure,
)
setattr(
transfer,
"none_pathway_training_loss",
_tensor_native_none_pathway_training_loss,
)
if not bool(
getattr(
transfer,
"_resynthesis_none_tensor_constants_installed",
False,
)
):
setattr(
transfer,
"_resynthesis_original_transfer_init",
getattr(transfer, "__init__"),
)
setattr(
transfer,
"__init__",
_historical_transfer_init_with_tensor_constants,
)
setattr(
transfer,
"_resynthesis_none_tensor_constants_installed",
True,
)
setattr(
transfer,
"_resynthesis_none_pathway_packet_type",
pathway_packet_type,
)
setattr(
transfer,
"build_none_pathway_packet",
_tensor_native_build_none_pathway_packet,
)
setattr(hop_router, "_resynthesis_hop_signal_type", signal_type)
setattr(hop_router, "compute_hop_signal", _tensor_native_compute_hop_signal)
setattr(
rbo_type,
"_comm_from_prior_delta",
staticmethod(_tensor_native_sequence_comm_from_prior_delta),
)
if not bool(
getattr(rbo_type, "_resynthesis_tensor_intent_mapping_installed", False)
):
setattr(
rbo_type,
"_resynthesis_original_rbo_init",
getattr(rbo_type, "__init__"),
)
setattr(
rbo_type,
"_resynthesis_intent_to_capability_boundary",
staticmethod(intent_to_capability),
)
setattr(
rbo_type,
"_resynthesis_intent_capability_count",
capability_count,
)
setattr(
rbo_type,
"_resynthesis_original_context_dag_training_loss",
getattr(rbo_type, "_context_dag_training_loss"),
)
setattr(
rbo_type,
"__init__",
_historical_rbo_init_with_tensor_intent_mapping,
)
setattr(
rbo_type,
"_intent_label",
_tensor_native_historical_intent_route,
)
setattr(
rbo_type,
"_none_step_phase",
_tensor_native_historical_none_step_phase,
)
setattr(
rbo_type,
"_context_dag_training_loss",
_historical_tensor_native_context_dag_training_loss,
)
setattr(
rbo_type,
"_identity_supervision_loss",
_historical_tensor_native_identity_supervision_loss,
)
setattr(
rbo_type,
"_resynthesis_tensor_intent_mapping_installed",
True,
)
if isinstance(correction_controller, type):
setattr(
correction_controller,
"mode_target",
staticmethod(_tensor_native_self_correction_mode_target),
)
if (
isinstance(domain_collapse_detector, type)
and callable(getattr(domain_collapse_detector, "forward", None))
):
setattr(
domain_collapse_detector,
"forward",
_tensor_native_domain_collapse_forward,
)
if not bool(
getattr(rbo_type, "_resynthesis_tensor_route_forward_installed", False)
):
original_recursive_pass = getattr(rbo_type, "_recursive_pass")
setattr(
rbo_type,
"_resynthesis_original_rbo_forward",
getattr(rbo_type, "forward"),
)
setattr(
rbo_type,
"_resynthesis_original_recursive_pass",
original_recursive_pass,
)
setattr(
rbo_type,
"_resynthesis_rbo_result_type",
rbo_result_type,
)
setattr(
rbo_type,
"_resynthesis_contrareactive_repulsion",
staticmethod(contrareactive_repulsion),
)
setattr(rbo_type, "_resynthesis_swe_stages", swe_stages)
setattr(
rbo_type,
"_recursive_pass",
_historical_recursive_pass_with_tensor_route(
original_recursive_pass
),
)
setattr(
rbo_type,
"forward",
_tensor_native_historical_rbo_forward,
)
setattr(
rbo_type,
"_resynthesis_tensor_route_forward_installed",
True,
)
setattr(
outcome_history,
"_pack_step",
_tensor_native_outcome_history_pack_step,
)
setattr(
rubric_bias_type,
"apply_bias",
_tensor_native_rubric_apply_bias,
)
if not bool(
getattr(rbo_type, "_resynthesis_batch_correction_loss_installed", False)
):
setattr(
rbo_type,
"_resynthesis_original_correction_training_loss",
getattr(rbo_type, "_correction_training_loss"),
)
setattr(
rbo_type,
"_correction_training_loss",
_historical_batch_safe_correction_training_loss,
)
setattr(rbo_type, "_resynthesis_batch_correction_loss_installed", True)
if not bool(getattr(rbo_type, "_resynthesis_arm_exhaustion_installed", False)):
setattr(
rbo_type,
"_resynthesis_original_plan_layer_traversal",
getattr(rbo_type, "_plan_layer_traversal"),
)
setattr(
rbo_type,
"_resynthesis_original_joint_stop_logit",
getattr(rbo_type, "_joint_stop_logit"),
)
setattr(
rbo_type,
"_resynthesis_original_layer_gate_scale",
getattr(rbo_type, "layer_gate_scale"),
)
setattr(
rbo_type,
"_plan_layer_traversal",
_historical_plan_layer_traversal_with_arm_exhaustion,
)
setattr(
rbo_type,
"_joint_stop_logit",
_historical_joint_stop_logit_with_arm_exhaustion,
)
setattr(
rbo_type,
"layer_gate_scale",
_historical_layer_gate_scale_with_frontier_blend,
)
setattr(rbo_type, "_resynthesis_arm_exhaustion_installed", True)
return HISTORICAL_TENSOR_NATIVE_HOTPATH_ID
@dataclass(frozen=True)
class LegacyRBOCapabilitySessionState:
"""Session-owned observable-outcome state for cold continuation."""
durable_outcome: torch.Tensor
shot_one_route: torch.Tensor
shot_two_route: torch.Tensor
last_route: torch.Tensor
awaiting_second_shot: torch.Tensor
durable_outcome_updates: torch.Tensor
@dataclass(frozen=True)
class LegacyRBOCapabilityEngagementPacket:
"""Tensor-only evidence from the preserved legacy capability bank."""
authority_trained: torch.Tensor
retention_passed: torch.Tensor
forward_id: torch.Tensor
forward_calls: torch.Tensor
engaged_calls: torch.Tensor
delta_l2: torch.Tensor
route_id: torch.Tensor
shot_one_route: torch.Tensor
shot_two_route: torch.Tensor
shot_one_route_id: torch.Tensor
shot_two_route_id: torch.Tensor
route_shift_l1: torch.Tensor
durable_outcome_updates: torch.Tensor
payload_tensor_count: torch.Tensor
def _capture_legacy_second_shot_route_(
*,
last_route: torch.Tensor,
shot_two_route: torch.Tensor,
awaiting_second_shot: torch.Tensor,
) -> None:
"""Capture a pending route without synchronizing the hot path to the host."""
if last_route.shape != shot_two_route.shape:
raise RuntimeError("legacy RBO second-shot route geometry differs")
if awaiting_second_shot.shape != torch.Size([]):
raise RuntimeError("legacy RBO second-shot pending state must be scalar")
shot_two_route.copy_(
torch.where(
awaiting_second_shot.to(
device=shot_two_route.device,
dtype=torch.bool,
),
last_route,
shot_two_route,
)
)
awaiting_second_shot.zero_()
class _FrozenLegacyRBOTensor(nn.Module):
"""One dehydrated parent tensor that remains immutable and CPU-resident."""
def __init__(self, value: torch.Tensor) -> None:
super().__init__()
frozen = value.detach().to(device="cpu").contiguous()
frozen.requires_grad_(False)
self.register_buffer("payload", frozen, persistent=True)
def _apply(self, fn: Any, recurse: bool = True) -> "_FrozenLegacyRBOTensor":
del fn, recurse
return self
class LegacyRBOCapabilityBank(nn.Module):
"""Pinned compatibility owner for the parent's embedded 553-tensor RBO.
The parent artifact contains an older RBO geometry that cannot be overlaid
onto the authoritative 1,043-tensor graph. This implementation is owned by
Resynthesis so continuation never imports a changing Resynthesis worktree. Its
tensor names, initialization, routing, outcome memory, and persistence match
the exact source generation recorded by
``LEGACY_RBO_CAPABILITY_PROVENANCE_SHA256``.
"""
schema = _RESYNTHESIS_PARENT_CAPABILITY_SCHEMA
durable_outcome_width = 10
_payloads: nn.ModuleList
capability_profiles: torch.Tensor
route_query: nn.Linear
outcome_query: nn.Linear
residual_projection: nn.Linear
fusion_logit: nn.Parameter
authority_trained: torch.Tensor
retention_passed: torch.Tensor
forward_id: torch.Tensor
forward_calls: torch.Tensor
engaged_calls: torch.Tensor
last_delta_l2: torch.Tensor
last_route: torch.Tensor
shot_one_route: torch.Tensor
shot_two_route: torch.Tensor
durable_outcome: torch.Tensor
awaiting_second_shot: torch.Tensor
durable_outcome_updates: torch.Tensor
def __init__(self, state: Mapping[str, torch.Tensor]) -> None:
super().__init__()
normalized = {
str(name).removeprefix(_LEGACY_PARENT_STATE_PREFIX): value
for name, value in state.items()
}
if len(normalized) != LEGACY_RBO_CAPABILITY_TENSOR_COUNT:
raise RuntimeError(
"legacy RBO capability tensor count differs: "
f"expected={LEGACY_RBO_CAPABILITY_TENSOR_COUNT} "
f"actual={len(normalized)}"
)
if len(normalized) != len(state) or any(
not isinstance(value, torch.Tensor) for value in normalized.values()
):
raise RuntimeError(
"legacy RBO capability state has duplicate or non-tensor entries"
)
names = tuple(sorted(normalized))
layer_indices = sorted(
{
int(parts[1])
for name in names
if (parts := name.split("."))[:1] == ["experts"]
and len(parts) > 3
and parts[1].isdigit()
and parts[2:] == [parts[2], parts[3]]
and parts[2] == "bank"
and parts[3] == "gate_up"
}
)
if layer_indices != list(range(len(layer_indices))) or not layer_indices:
raise RuntimeError("legacy RBO capability expert layers are not contiguous")
profile_rows: list[torch.Tensor] = []
hidden_size = 0
intermediate_size = 0
route_count = 0
profile_width = 0
profile_suffixes = (
"flat_expert_identity",
"flat_expert_what_profile",
"flat_expert_when_profile",
"flat_expert_how_profile",
"flat_expert_capability",
)
for layer_idx in layer_indices:
prefix = f"experts.{layer_idx}."
gate_name = prefix + "bank.gate_up"
down_name = prefix + "bank.down"
if gate_name not in normalized or down_name not in normalized:
raise RuntimeError("legacy RBO capability expert payload is incomplete")
gate = normalized[gate_name]
down = normalized[down_name]
if gate.dim() != 3 or down.dim() != 3:
raise RuntimeError(
"legacy RBO capability experts are not rank-three banks"
)
layer_routes = int(gate.shape[0])
layer_hidden = int(gate.shape[-1])
layer_intermediate = int(down.shape[-1])
if tuple(gate.shape) != (
layer_routes,
2 * layer_intermediate,
layer_hidden,
) or tuple(down.shape) != (
layer_routes,
layer_hidden,
layer_intermediate,
):
raise RuntimeError(
"legacy RBO capability expert geometry is inconsistent"
)
if layer_idx == 0:
hidden_size = layer_hidden
intermediate_size = layer_intermediate
route_count = layer_routes
elif (
layer_hidden != hidden_size
or layer_intermediate != intermediate_size
or layer_routes != route_count
):
raise RuntimeError(
"legacy RBO capability expert geometry drifts by layer"
)
profile_parts: list[torch.Tensor] = []
for suffix in profile_suffixes:
name = prefix + suffix
value = normalized.get(name)
if not isinstance(value, torch.Tensor) or value.dim() != 2:
raise RuntimeError(
f"legacy RBO capability profile is missing or invalid: {name}"
)
if int(value.shape[0]) != route_count:
raise RuntimeError(
"legacy RBO capability profile route count differs"
)
profile_parts.append(
value.detach().to(device="cpu", dtype=torch.float32)
)
layer_profile = torch.cat(profile_parts, dim=-1)
if layer_idx == 0:
profile_width = int(layer_profile.shape[-1])
elif int(layer_profile.shape[-1]) != profile_width:
raise RuntimeError(
"legacy RBO capability profile width drifts by layer"
)
profile_rows.append(layer_profile)
classifier = normalized.get("intent_module.classifier.weight")
feedback_down = normalized.get("feedback_head.down.weight")
if (
not isinstance(classifier, torch.Tensor)
or tuple(classifier.shape[1:]) != (hidden_size,)
or not isinstance(feedback_down, torch.Tensor)
or feedback_down.dim() != 2
or int(feedback_down.shape[1]) != hidden_size
):
raise RuntimeError(
"legacy RBO capability intent/feedback geometry is invalid"
)
self._payload_names = names
self._payloads = nn.ModuleList(
[_FrozenLegacyRBOTensor(normalized[name]) for name in names]
)
profiles = F.normalize(torch.cat(profile_rows, dim=0), dim=-1, eps=1e-6)
self.register_buffer("capability_profiles", profiles, persistent=False)
self.route_query = nn.Linear(hidden_size, profile_width, bias=False)
self.outcome_query = nn.Linear(
self.durable_outcome_width,
profile_width,
bias=False,
)
self.residual_projection = nn.Linear(profile_width, hidden_size, bias=False)
self.fusion_logit = nn.Parameter(torch.zeros(()))
signal_weight = normalized.get("feedback_head.signal.weight")
trauma_values = [
normalized.get(f"trauma_gate.{layer_idx}") for layer_idx in layer_indices
]
learned_query = torch.cat(
(
feedback_down.detach().to(dtype=torch.float32),
classifier.detach().to(dtype=torch.float32),
),
dim=0,
)
if tuple(learned_query.shape) != tuple(self.route_query.weight.shape):
raise RuntimeError(
"legacy RBO capability learned query/profile geometry differs"
)
if (
not isinstance(signal_weight, torch.Tensor)
or signal_weight.dim() != 2
or tuple(signal_weight.shape) != (4, int(feedback_down.shape[0]))
or any(
not isinstance(value, torch.Tensor) or value.numel() != 1
for value in trauma_values
)
):
raise RuntimeError("legacy RBO capability feedback/trauma state is invalid")
with torch.no_grad():
self.route_query.weight.copy_(learned_query)
self.residual_projection.weight.copy_(learned_query.transpose(0, 1))
self.outcome_query.weight.zero_()
self.outcome_query.weight[
: int(feedback_down.shape[0]),
: int(signal_weight.shape[0]),
].copy_(signal_weight.detach().to(dtype=torch.float32).transpose(0, 1))
self.fusion_logit.copy_(
torch.stack(
[
value.detach().to(dtype=torch.float32).reshape(())
for value in trauma_values
if isinstance(value, torch.Tensor)
]
).mean()
)
self.register_buffer("authority_trained", torch.zeros((), dtype=torch.bool))
self.register_buffer("retention_passed", torch.zeros((), dtype=torch.bool))
self.register_buffer(
"forward_id",
torch.zeros((), dtype=torch.long),
persistent=False,
)
self.register_buffer(
"forward_calls",
torch.zeros((), dtype=torch.long),
persistent=False,
)
self.register_buffer(
"engaged_calls",
torch.zeros((), dtype=torch.long),
persistent=False,
)
self.register_buffer(
"last_delta_l2",
torch.zeros((), dtype=torch.float32),
persistent=False,
)
self.register_buffer(
"last_route",
torch.zeros(profiles.shape[0]),
persistent=False,
)
self.register_buffer(
"shot_one_route",
torch.zeros_like(self.last_route),
persistent=False,
)
self.register_buffer(
"shot_two_route",
torch.zeros_like(self.last_route),
persistent=False,
)
self.register_buffer(
"durable_outcome",
torch.zeros(self.durable_outcome_width),
persistent=False,
)
self.register_buffer(
"awaiting_second_shot",
torch.zeros((), dtype=torch.bool),
persistent=False,
)
self.register_buffer(
"durable_outcome_updates",
torch.zeros((), dtype=torch.long),
persistent=False,
)
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.n_expert_layers = len(layer_indices)
self.routes_per_layer = route_count
self.n_intents = int(classifier.shape[0])
self.feedback_hidden_size = int(feedback_down.shape[0])
self.profile_width = profile_width
self.payload_key_set_sha256 = hashlib.sha256(
"\n".join(names).encode("utf-8")
).hexdigest()
geometry_rows = [
(name, tuple(normalized[name].shape), str(normalized[name].dtype))
for name in names
]
self.payload_geometry_sha256 = hashlib.sha256(
json.dumps(geometry_rows, separators=(",", ":")).encode("utf-8")
).hexdigest()
def trainable_parameters(self) -> Iterator[nn.Parameter]:
yield from self.route_query.parameters()
yield from self.outcome_query.parameters()
yield from self.residual_projection.parameters()
yield self.fusion_logit
def reset_authority_from_boundary(self) -> None:
with torch.no_grad():
self.authority_trained.zero_()
self.retention_passed.zero_()
def begin_forward(self, forward_id: torch.Tensor) -> None:
if forward_id.numel() != 1:
raise RuntimeError("legacy RBO capability forward ID must be scalar")
with torch.no_grad():
self.forward_id.copy_(
forward_id.detach()
.to(device=self.forward_id.device, dtype=self.forward_id.dtype)
.reshape(())
)
self.forward_calls.zero_()
self.engaged_calls.zero_()
self.last_delta_l2.zero_()
def mark_authority_trained_from_boundary(
self,
update_proven: torch.Tensor,
retention_proven: torch.Tensor,
) -> None:
if update_proven.numel() != 1 or retention_proven.numel() != 1:
raise RuntimeError(
"legacy RBO capability authority receipts must be scalar"
)
with torch.no_grad():
self.authority_trained.copy_(update_proven.to(dtype=torch.bool).reshape(()))
self.retention_passed.copy_(
retention_proven.to(dtype=torch.bool).reshape(())
)
def apply_durable_outcome_state(self, observation: torch.Tensor) -> None:
"""Apply a persisted observable outcome, never a target or gold answer."""
if observation.numel() != self.durable_outcome_width:
raise RuntimeError("legacy RBO durable outcome geometry differs")
with torch.no_grad():
self.shot_one_route.copy_(self.last_route)
self.durable_outcome.copy_(
observation.detach()
.to(
device=self.durable_outcome.device,
dtype=self.durable_outcome.dtype,
)
.reshape_as(self.durable_outcome)
)
self.awaiting_second_shot.fill_(True)
self.durable_outcome_updates.add_(
torch.ones_like(self.durable_outcome_updates)
)
def capture_session_state(self) -> LegacyRBOCapabilitySessionState:
return LegacyRBOCapabilitySessionState(
durable_outcome=self.durable_outcome.detach().clone(),
shot_one_route=self.shot_one_route.detach().clone(),
shot_two_route=self.shot_two_route.detach().clone(),
last_route=self.last_route.detach().clone(),
awaiting_second_shot=self.awaiting_second_shot.detach().clone(),
durable_outcome_updates=self.durable_outcome_updates.detach().clone(),
)
def reset_session_state(self) -> None:
with torch.no_grad():
self.durable_outcome.zero_()
self.shot_one_route.zero_()
self.shot_two_route.zero_()
self.last_route.zero_()
self.awaiting_second_shot.zero_()
self.durable_outcome_updates.zero_()
def hydrate_session_state(self, state: LegacyRBOCapabilitySessionState) -> None:
pairs = (
(self.durable_outcome, state.durable_outcome),
(self.shot_one_route, state.shot_one_route),
(self.shot_two_route, state.shot_two_route),
(self.last_route, state.last_route),
(self.awaiting_second_shot, state.awaiting_second_shot),
(self.durable_outcome_updates, state.durable_outcome_updates),
)
with torch.no_grad():
for target, source in pairs:
if tuple(target.shape) != tuple(source.shape):
raise RuntimeError("legacy RBO capability session geometry differs")
target.copy_(source.to(device=target.device, dtype=target.dtype))
def forward(self, hidden: torch.Tensor) -> torch.Tensor:
if hidden.shape[-1] != self.hidden_size:
raise RuntimeError("legacy RBO capability hidden geometry differs")
with torch.no_grad():
self.forward_calls.add_(torch.ones_like(self.forward_calls))
active = self.authority_trained & self.retention_passed
if not self.training and not bool(active.detach().to(device="cpu")):
self.last_delta_l2.zero_()
return hidden
query_dtype = self.route_query.weight.dtype
query_hidden = hidden.to(dtype=query_dtype)
query = self.route_query(query_hidden)
outcome = self.outcome_query(
self.durable_outcome.to(device=query.device, dtype=query_dtype)
)
query = F.normalize(query + outcome, dim=-1, eps=1e-6)
profiles = self.capability_profiles.to(
device=query.device,
dtype=query_dtype,
)
route_logits = torch.einsum("btd,rd->btr", query, profiles)
route_weights = route_logits.softmax(dim=-1)
capability = torch.einsum("btr,rd->btd", route_weights, profiles)
proposed_delta = (
self.residual_projection(capability) * self.fusion_logit.sigmoid()
)
route = route_weights.mean(dim=(0, 1)).detach()
with torch.no_grad():
self.last_route.copy_(route.to(device=self.last_route.device))
_capture_legacy_second_shot_route_(
last_route=self.last_route,
shot_two_route=self.shot_two_route,
awaiting_second_shot=self.awaiting_second_shot,
)
if self.training:
inactive_delta = proposed_delta - proposed_delta.detach()
else:
inactive_delta = torch.zeros_like(proposed_delta)
active_scale = active.to(device=hidden.device, dtype=hidden.dtype)
delta = active_scale * proposed_delta.to(dtype=hidden.dtype) + (
1.0 - active_scale
) * inactive_delta.to(dtype=hidden.dtype)
with torch.no_grad():
self.engaged_calls.add_(active.to(dtype=torch.long))
self.last_delta_l2.copy_(delta.detach().float().square().sum().sqrt())
output: torch.Tensor = hidden + delta
return output
def engagement_packet(self) -> LegacyRBOCapabilityEngagementPacket:
return LegacyRBOCapabilityEngagementPacket(
authority_trained=self.authority_trained.detach().clone(),
retention_passed=self.retention_passed.detach().clone(),
forward_id=self.forward_id.detach().clone(),
forward_calls=self.forward_calls.detach().clone(),
engaged_calls=self.engaged_calls.detach().clone(),
delta_l2=self.last_delta_l2.detach().clone(),
route_id=self.last_route.argmax().detach().clone(),
shot_one_route=self.shot_one_route.detach().clone(),
shot_two_route=self.shot_two_route.detach().clone(),
shot_one_route_id=self.shot_one_route.argmax().detach().clone(),
shot_two_route_id=self.shot_two_route.argmax().detach().clone(),
route_shift_l1=(self.shot_two_route - self.shot_one_route)
.abs()
.sum()
.detach()
.clone(),
durable_outcome_updates=self.durable_outcome_updates.detach().clone(),
payload_tensor_count=torch.full_like(
self.forward_calls,
len(self._payload_names),
),
)
def _verified_legacy_capability_provenance(cfg: ResynthesisConfig) -> str:
"""Return the launch's code-provenance observation for receipts only."""
observed = cfg.legacy_capability_source_sha256
return observed if observed else "unavailable"
def _resolve_path(base_dir: str, filename: str) -> Path:
p = Path(filename)
if p.is_absolute():
return p
return Path(base_dir) / filename
def load_resynthesis_parent_config(cfg: ResynthesisConfig) -> dict[str, Any]:
"""Load the Resynthesis config.json (boundary I/O — JSON is allowed here)."""
config_path = _resolve_path(cfg.base_model_dir, cfg.config_path)
with open(config_path, encoding="utf-8") as f:
return cast(dict[str, Any], json.load(f))
def load_resynthesis_parent_manifest(cfg: ResynthesisConfig) -> dict[str, Any]:
"""Load the integrated checkpoint manifest at the external I/O boundary."""
manifest_path = (
Path(cfg.parent_checkpoint_manifest_path).expanduser().resolve()
)
manifest_sha256 = _streamed_file_sha256(manifest_path)
if (
cfg.parent_checkpoint_manifest_sha256
!= RESYNTHESIS_PARENT_CHECKPOINT_MANIFEST_SHA256
or manifest_sha256 != cfg.parent_checkpoint_manifest_sha256
):
raise RuntimeError(
"Resynthesis parent checkpoint manifest SHA-256 differs"
)
with manifest_path.open(encoding="utf-8") as handle:
manifest = json.load(handle)
if not isinstance(manifest, dict):
raise RuntimeError("Resynthesis checkpoint manifest is not a JSON object")
expected_payload_sha256 = str(manifest.get("manifest_payload_sha256", ""))
payload = dict(manifest)
payload.pop("manifest_payload_sha256", None)
actual_payload_sha256 = hashlib.sha256(
json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
if expected_payload_sha256 != actual_payload_sha256:
raise RuntimeError("Resynthesis checkpoint manifest payload SHA-256 differs")
return manifest
def _streamed_file_sha256(path: Path) -> str:
"""Hash an immutable model artifact at the explicit checkpoint boundary."""
from resynthesis.none_migration import file_sha256_boundary
return file_sha256_boundary(path)
def _safetensors_parameter_elements(path: Path) -> int:
"""Count exact tensor elements from a safetensors header boundary."""
with path.open("rb") as handle:
header_width = int.from_bytes(handle.read(8), byteorder="little")
if header_width < 2:
raise RuntimeError("native parent safetensors header is malformed")
header = json.loads(handle.read(header_width).decode("utf-8"))
if not isinstance(header, dict):
raise RuntimeError("native parent safetensors header is not an object")
parameter_elements = 0
tensor_count = 0
for name, record in header.items():
if name == "__metadata__":
continue
if not isinstance(record, dict):
raise RuntimeError("native parent safetensors tensor record is malformed")
shape = record.get("shape")
if not isinstance(shape, list) or not all(
isinstance(width, int) and not isinstance(width, bool) and width >= 0
for width in shape
):
raise RuntimeError("native parent safetensors tensor shape is malformed")
elements = 1
for width in shape:
elements *= width
parameter_elements += elements
tensor_count += 1
if tensor_count < 1 or parameter_elements < 1:
raise RuntimeError("native parent safetensors contains no model tensors")
return parameter_elements
def _verified_resynthesis_native_parent_manifest(
cfg: ResynthesisConfig,
native_root: Path,
weights_path: Path,
parameter_elements: int,
inherited_manifest: Mapping[str, Any],
) -> tuple[str, bool]:
"""Verify exact parent bytes while allowing their public release location."""
manifest_path = Path(cfg.native_parent_manifest_path).expanduser().resolve()
manifest_sha256 = _streamed_file_sha256(manifest_path)
if (
cfg.native_parent_manifest_sha256 != RESYNTHESIS_NATIVE_PARENT_MANIFEST_SHA256
or manifest_sha256 != cfg.native_parent_manifest_sha256
or cfg.native_parent_model_sha256
!= RESYNTHESIS_NATIVE_PARENT_MODEL_SHA256
):
raise RuntimeError("Resynthesis native-parent release identity differs")
loaded = json.loads(manifest_path.read_text(encoding="utf-8"))
if not isinstance(loaded, dict):
raise RuntimeError("Resynthesis native-parent manifest is not an object")
model_artifact = loaded.get("modelArtifact")
inherited_lineage = loaded.get("inheritedCheckpointLineage")
source_runtime = loaded.get("sourceEraRuntime")
migration = loaded.get("migrationValidation")
inherited_model_artifact = inherited_manifest.get("model_artifact")
if not all(
isinstance(value, dict)
for value in (
model_artifact,
inherited_lineage,
source_runtime,
migration,
inherited_model_artifact,
)
):
raise RuntimeError("Resynthesis native-parent manifest lacks required records")
assert isinstance(model_artifact, dict)
assert isinstance(inherited_lineage, dict)
assert isinstance(source_runtime, dict)
assert isinstance(migration, dict)
assert isinstance(inherited_model_artifact, dict)
declared_root = Path(str(loaded.get("nativeRoot", ""))).resolve()
declared_model_path = Path(str(model_artifact.get("path", "")))
checks = (
native_root.is_dir(),
loaded.get("schema") == "nnf.resynthesis.native_parent_generation.v1",
loaded.get("owner") == "Resynthesis",
loaded.get("generation") == RESYNTHESIS_NATIVE_PARENT_GENERATION,
declared_root == Path(RESYNTHESIS_NATIVE_PARENT_ROOT).resolve(),
loaded.get("externalProductCheckpointDependency") is False,
declared_model_path == Path("model.safetensors"),
weights_path.name == declared_model_path.name,
model_artifact.get("sizeBytes") == weights_path.stat().st_size,
model_artifact.get("parameterElements") == parameter_elements,
model_artifact.get("sha256") == cfg.native_parent_model_sha256,
model_artifact.get("sha256")
== inherited_model_artifact.get("artifact_sha256"),
model_artifact.get("tensorCount")
== inherited_model_artifact.get("tensor_count"),
model_artifact.get("contentTensorCount")
== inherited_model_artifact.get("content_tensor_count"),
inherited_lineage.get("checkpointId")
== inherited_manifest.get("checkpoint_id"),
inherited_lineage.get("manifestPayloadSha256")
== inherited_manifest.get("manifest_payload_sha256"),
migration.get("independentModelSha256Recomputed") is True,
migration.get("safetensorsHeaderParameterCountVerified") is True,
migration.get("promotionEligible") is False,
)
if not all(checks):
raise RuntimeError(
"Resynthesis native-parent manifest differs from live geometry or lineage"
)
return manifest_sha256, bool(migration.get("promotionEligible"))
def _verified_parent_source_hashes(cfg: ResynthesisConfig) -> dict[str, str]:
"""Observe mutable parent source bytes without creating launch authority.
The historical modules themselves still have to import successfully when
the parent is loaded. Hashing them is only version telemetry, however, so
a concurrent edit or transient diagnostic read failure is recorded in the
observation instead of pre-empting that real import/load boundary.
"""
def observe(path: Path) -> str:
try:
return _streamed_file_sha256(path) if path.is_file() else "missing"
except (OSError, RuntimeError) as error:
return f"unavailable:{type(error).__name__}"
source_root = Path(cfg.parent_runtime_source_dir).expanduser().resolve()
fingerprint_path = Path(cfg.parent_source_fingerprint_path).expanduser().resolve()
runtime_files = tuple(
f"{_LEGACY_PARENT_PACKAGE_COMPONENT}/{filename}"
for filename in (
"additive_moe.py",
"capability_corpus.py",
"config.py",
"experts.py",
"glyph_vge.py",
"integrated.py",
"knowledge_transfer_surfaces.py",
"loader.py",
"master_context_orchestration.py",
"moe_growth_controller.py",
f"{_legacy_parent_module_name('rbo')}.py",
"none_fabric.py",
"rbo_checkpoint.py",
"rbo_outcome_continual.py",
"rbo_traversal_tensors.py",
"training_doctrine.py",
"swe_agent_system_prompt.txt",
"tool_schema.json",
)
)
outcome_source_name = (
f"{_LEGACY_PARENT_PACKAGE_COMPONENT}/rbo_outcome_continual.py"
)
actual: dict[str, str] = {}
for relative_path in runtime_files:
path = (
Path(cfg.parent_rbo_outcome_source_path).expanduser().resolve()
if relative_path == outcome_source_name
else source_root / relative_path
)
actual[relative_path] = observe(path)
actual["@source_fingerprint_shard"] = observe(fingerprint_path)
actual["@source_id"] = cfg.parent_source_id
return actual
def _source_bundle_sha256(source_hashes: Mapping[str, str]) -> str:
rows = tuple(
sorted((str(name), str(value)) for name, value in source_hashes.items())
)
return hashlib.sha256(
json.dumps(rows, separators=(",", ":")).encode("utf-8")
).hexdigest()
def _exec_historical_source_module(
module_key: str,
module_spec: importlib.machinery.ModuleSpec,
module: Any,
) -> None:
"""Execute verified historical source without writing into its artifact."""
if module_spec.loader is None:
raise RuntimeError("historical source module has no loader")
previous = sys.dont_write_bytecode
sys.dont_write_bytecode = True
try:
module_spec.loader.exec_module(module)
except BaseException:
sys.modules.pop(module_key, None)
raise
finally:
sys.dont_write_bytecode = previous
def _load_aliased_parent_module(
alias: str,
source_root: Path,
module_name: str,
) -> Any:
"""Import one Resynthesis source generation under an isolated package identity."""
package_dir = source_root / _LEGACY_PARENT_PACKAGE_COMPONENT
package_name = alias
package = sys.modules.get(package_name)
if package is None:
if not package_dir.is_dir():
raise RuntimeError("historical Resynthesis package directory is unavailable")
# The source-era package initializer imported unrelated mutable modules
# that were absent from the checkpoint fingerprint. Build an isolated
# namespace package instead, then import only manifest-verified modules.
package_spec = importlib.machinery.ModuleSpec(
package_name,
loader=None,
is_package=True,
)
package_spec.submodule_search_locations = [str(package_dir)]
package = importlib.util.module_from_spec(package_spec)
sys.modules[package_name] = package
module_key = f"{package_name}.{module_name}"
existing = sys.modules.get(module_key)
if existing is not None:
actual_file = Path(str(getattr(existing, "__file__", ""))).resolve()
expected_file = (package_dir / f"{module_name}.py").resolve()
if actual_file != expected_file:
raise RuntimeError("isolated Resynthesis module alias is already bound elsewhere")
return existing
module_path = package_dir / f"{module_name}.py"
source_loader = importlib.machinery.SourceFileLoader(module_key, str(module_path))
module_spec = importlib.util.spec_from_loader(module_key, source_loader)
if module_spec is None or module_spec.loader is None:
raise RuntimeError(
f"could not create Resynthesis module specification: {module_path}"
)
module = importlib.util.module_from_spec(module_spec)
sys.modules[module_key] = module
_exec_historical_source_module(module_key, module_spec, module)
return module
def _load_aliased_parent_module_from_path(
alias: str,
module_name: str,
module_path: Path,
) -> Any:
"""Install one recovered hash-exact module into an isolated package."""
module_key = f"{alias}.{module_name}"
existing = sys.modules.get(module_key)
if existing is not None:
if (
Path(str(getattr(existing, "__file__", ""))).resolve()
!= module_path.resolve()
):
raise RuntimeError(
"recovered Resynthesis module alias is already bound elsewhere"
)
return existing
source_loader = importlib.machinery.SourceFileLoader(module_key, str(module_path))
module_spec = importlib.util.spec_from_loader(module_key, source_loader)
if module_spec is None or module_spec.loader is None:
raise RuntimeError(
f"could not create recovered Resynthesis module spec: {module_path}"
)
module = importlib.util.module_from_spec(module_spec)
sys.modules[module_key] = module
_exec_historical_source_module(module_key, module_spec, module)
return module
class _FrozenWideIntent(nn.Module):
"""Exact eight-way trained intent geometry embedded in the graph parent."""
def __init__(self, hidden_size: int = 4096, carry_dim: int = 512) -> None:
super().__init__()
self.hidden_size = int(hidden_size)
self.carry_dim = int(carry_dim)
self.n_intents = 8
self.carry_down = nn.Linear(self.hidden_size, self.carry_dim, bias=False)
self.classifier = nn.Linear(self.carry_dim, self.n_intents)
self.requires_grad_(False)
def forward_intent(self, hidden: torch.Tensor) -> torch.Tensor:
carry = self.carry_down(hidden.to(dtype=self.carry_down.weight.dtype))
logits: torch.Tensor = self.classifier(carry)
return logits
def _split_embedded_legacy_rbo_state(
state: Mapping[str, torch.Tensor],
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
additive = {
name: value
for name, value in state.items()
if not name.startswith(_LEGACY_PARENT_STATE_PREFIX)
}
legacy = {
name.removeprefix(_LEGACY_PARENT_STATE_PREFIX): value
for name, value in state.items()
if name.startswith(_LEGACY_PARENT_STATE_PREFIX)
}
return additive, legacy
def _normalize_legacy_ladder_state(
state: dict[str, torch.Tensor],
) -> tuple[dict[str, torch.Tensor], bool]:
"""Normalize the one source-era nested ladder namespace."""
if not state:
return state, False
legacy = tuple(name.startswith("ladder.") for name in state)
if any(legacy) and not all(legacy):
raise RuntimeError("integrated Resynthesis ladder checkpoint mixes legacy namespaces")
if not all(legacy):
return state, False
normalized = {name.removeprefix("ladder."): value for name, value in state.items()}
if len(normalized) != len(state):
raise RuntimeError("integrated Resynthesis ladder namespace migration collided")
return normalized, True
def _validate_embedded_legacy_rbo_split(
source: Mapping[str, torch.Tensor],
additive_state: Mapping[str, torch.Tensor],
legacy_state: Mapping[str, torch.Tensor],
*,
expected_source_tensor_count: int,
) -> str:
"""Validate the one historical additive-embedded RBO capability schema."""
if len(source) != expected_source_tensor_count:
raise RuntimeError("integrated additive tensor count differs from its manifest")
if len(additive_state) + len(legacy_state) != len(source):
raise RuntimeError("embedded legacy RBO split lost or duplicated tensors")
if len(legacy_state) != 553:
raise RuntimeError(
"embedded legacy RBO capability tensor count is not the exact schema"
)
embedded_names = {
name.removeprefix(_LEGACY_PARENT_STATE_PREFIX)
for name in source
if name.startswith(_LEGACY_PARENT_STATE_PREFIX)
}
if embedded_names != set(legacy_state):
raise RuntimeError("embedded legacy RBO capability key ownership differs")
if not additive_state:
raise RuntimeError("embedded legacy RBO split left no additive expert tensors")
return hashlib.sha256("\n".join(sorted(legacy_state)).encode("utf-8")).hexdigest()
def _prepare_empty_legacy_capability_module_slot(model: nn.Module) -> None:
"""Remove Resynthesis's ``None`` placeholder so its official add_module can own it."""
name = _legacy_parent_attribute("legacy_rbo_capability_bank")
existing = getattr(model, name, None)
if existing is not None:
raise RuntimeError("legacy RBO capability module slot is already occupied")
if hasattr(model, name):
delattr(model, name)
def _load_additive_state_into_resident_owner_boundary(
load_state: Callable[..., None],
model: Any,
state: Mapping[str, torch.Tensor],
) -> None:
"""Strictly copy CPU checkpoint tensors once into resident parameters.
Historical Resynthesis constructs the additive owner beside the already-resident
parent before invoking this callback. Supplying that owner's CUDA device
asks the source-era loader to build a second device state map and then copy
it again through ``load_state_dict``. Omitting the staging device retains
the source tensors and lets PyTorch perform the single required copy into
each target parameter. Key/shape checking remains owned by the exact
historical loader; no checkpoint, dtype, or lineage authority changes.
"""
load_state(model, state, device=None)
def _load_resynthesis_parent_with_boundary_migration(
integrated_module: Any,
load_parent_full: Any,
checkpoint_dir: str,
*,
device: str,
expected_additive_tensor_count: int,
) -> tuple[Any, ResynthesisBoundaryMigrationReceipt]:
"""Run Resynthesis's loader with a temporary, exact legacy-key boundary adapter."""
original_prefixed_loader = getattr(
integrated_module, "_load_prefixed_tensors", None
)
ladder_prefix = getattr(integrated_module, "LADDER_PREFIX", None)
if not callable(original_prefixed_loader) or not isinstance(ladder_prefix, str):
raise RuntimeError(
"Resynthesis integrated runtime lacks its checkpoint tensor loader"
)
additive_module = importlib.import_module(
f"{_LEGACY_PARENT_PACKAGE_COMPONENT}.additive_moe"
)
original_additive_loader = getattr(
additive_module, "load_additive_state_dict", None
)
split_embedded = getattr(integrated_module, "split_embedded_legacy_rbo_state", None)
wire_legacy_bank = getattr(
integrated_module, "wire_legacy_rbo_capability_bank", None
)
if not all(
callable(value)
for value in (
original_additive_loader,
split_embedded,
wire_legacy_bank,
)
):
raise RuntimeError(
"Resynthesis integrated runtime lacks its legacy capability migration"
)
ladder_migration_applied = False
embedded_legacy_rbo_applied = False
embedded_legacy_rbo_tensor_count = 0
additive_tensor_count_after_split = 0
embedded_legacy_rbo_key_set_sha256 = ""
def compatible_prefixed_loader(
model_path: str | Path,
prefix: str,
target_device: str,
) -> dict[str, torch.Tensor]:
nonlocal ladder_migration_applied
state = original_prefixed_loader(model_path, prefix, target_device)
if not isinstance(state, dict) or not all(
isinstance(name, str) and isinstance(value, torch.Tensor)
for name, value in state.items()
):
raise RuntimeError(
"Resynthesis checkpoint tensor loader returned an invalid state"
)
if prefix == ladder_prefix:
state, migrated = _normalize_legacy_ladder_state(state)
ladder_migration_applied = ladder_migration_applied or migrated
return cast(dict[str, torch.Tensor], state)
def compatible_additive_loader(
model: Any,
state: Mapping[str, torch.Tensor],
*,
device: str | torch.device | None = None,
) -> None:
nonlocal embedded_legacy_rbo_applied
nonlocal embedded_legacy_rbo_tensor_count
nonlocal additive_tensor_count_after_split
nonlocal embedded_legacy_rbo_key_set_sha256
assert callable(original_additive_loader)
assert callable(split_embedded)
assert callable(wire_legacy_bank)
split = split_embedded(state)
additive_state = getattr(split, "additive_state", None)
legacy_state = getattr(split, "legacy_state", None)
if not isinstance(additive_state, Mapping) or not isinstance(
legacy_state, Mapping
):
raise RuntimeError(
"Resynthesis legacy capability splitter returned an invalid packet"
)
if not legacy_state:
original_additive_loader(model, state, device=device)
return
if embedded_legacy_rbo_applied:
raise RuntimeError(
"embedded legacy RBO capability migration ran more than once"
)
embedded_legacy_rbo_key_set_sha256 = _validate_embedded_legacy_rbo_split(
state,
additive_state,
legacy_state,
expected_source_tensor_count=expected_additive_tensor_count,
)
# ``wire_additive_moe`` has already constructed the additive modules
# on the selected device. Passing that device into the historical
# loader first materializes an entire second GPU-resident state map,
# then ``load_state_dict`` copies the same tensors again into those
# resident parameters. Preserve the exact key/shape validation while
# letting PyTorch perform the one required CPU-to-resident copy during
# strict state loading. This is a load-boundary optimization only;
# it does not alter parent bytes, routing, trainability, or lineage.
_load_additive_state_into_resident_owner_boundary(
original_additive_loader,
model,
additive_state,
)
if not isinstance(model, nn.Module):
raise RuntimeError("Resynthesis additive owner is not an nn.Module")
_prepare_empty_legacy_capability_module_slot(model)
bank = wire_legacy_bank(model, legacy_state)
if not isinstance(bank, nn.Module):
raise RuntimeError("embedded legacy RBO capability bank was not attached")
embedded_legacy_rbo_applied = True
embedded_legacy_rbo_tensor_count = len(legacy_state)
additive_tensor_count_after_split = len(additive_state)
setattr(integrated_module, "_load_prefixed_tensors", compatible_prefixed_loader)
setattr(additive_module, "load_additive_state_dict", compatible_additive_loader)
try:
loaded = load_parent_full(
checkpoint_dir,
device=device,
dtype=torch.bfloat16,
)
finally:
setattr(integrated_module, "_load_prefixed_tensors", original_prefixed_loader)
setattr(additive_module, "load_additive_state_dict", original_additive_loader)
return loaded, ResynthesisBoundaryMigrationReceipt(
ladder_namespace_applied=ladder_migration_applied,
embedded_legacy_rbo_applied=embedded_legacy_rbo_applied,
embedded_legacy_rbo_tensor_count=embedded_legacy_rbo_tensor_count,
additive_tensor_count_after_split=additive_tensor_count_after_split,
embedded_legacy_rbo_key_set_sha256=embedded_legacy_rbo_key_set_sha256,
)
@contextmanager
def _relocated_parent_checkpoint_view(
cfg: ResynthesisConfig,
) -> Iterator[Path]:
"""Expose separated release artifacts as one read-only checkpoint view.
The source-era constructor expects the model, tokenizer, and configuration
under one directory. Public releases keep the multi-gigabyte model in the
weights tree and lexical artifacts in the tokenizer tree. A temporary
symlink view preserves those single physical files; it is created only
after the exact manifests and model identity have been verified.
"""
native_root = Path(cfg.base_model_dir).expanduser().resolve()
weights_path = _resolve_path(cfg.base_model_dir, cfg.base_weights).resolve()
config_path = _resolve_path(cfg.base_model_dir, cfg.config_path).resolve()
tokenizer_path = _resolve_path(cfg.base_model_dir, cfg.tokenizer_path).resolve()
checkpoint_manifest_path = Path(
cfg.parent_checkpoint_manifest_path
).expanduser().resolve()
expected_paths = {
"model.safetensors": weights_path,
"config.json": config_path,
"tokenizer.json": tokenizer_path,
f"{_LEGACY_PARENT_PACKAGE_COMPONENT}_manifest.json": (
checkpoint_manifest_path
),
}
if all((native_root / name).resolve() == path for name, path in expected_paths.items()):
yield native_root
return
if not native_root.is_dir() or any(
not path.is_file() for path in expected_paths.values()
):
raise RuntimeError(
"relocated Resynthesis parent release is missing a required artifact"
)
with tempfile.TemporaryDirectory(
prefix="resynthesis-native-parent-view-"
) as temporary:
view = Path(temporary)
for source in native_root.iterdir():
if source.name in expected_paths:
continue
(view / source.name).symlink_to(
source,
target_is_directory=source.is_dir(),
)
for name, source in expected_paths.items():
(view / name).symlink_to(source)
yield view
def _load_exact_resynthesis_parent(
cfg: ResynthesisConfig,
*,
device: str,
expected_rbo_tensor_count: int,
expected_additive_tensor_count: int,
) -> tuple[Any, ResynthesisBoundaryMigrationReceipt, nn.Module, str]:
"""Load the July 13 graph parent with its exact source-era architecture.
The current rolling Resynthesis source has additional trained-authority tensors
and cannot strictly represent this artifact. This path imports the source
snapshot under an isolated package name, reconstructs the checkpoint's
eight-way wide-intent/21-layer RBO exactly, and rejects every missing,
extra, or shape-different authoritative tensor.
"""
source_root = Path(cfg.parent_runtime_source_dir).expanduser().resolve()
alias = "_resynthesis_parent_artifact_20260713"
_load_aliased_parent_module(alias, source_root, "config")
_load_aliased_parent_module_from_path(
alias,
"rbo_outcome_continual",
Path(cfg.parent_rbo_outcome_source_path).expanduser().resolve(),
)
integrated_module = _load_aliased_parent_module(alias, source_root, "integrated")
additive_module = _load_aliased_parent_module(alias, source_root, "additive_moe")
rbo_module = _load_aliased_parent_module(
alias,
source_root,
_legacy_parent_module_name("rbo"),
)
checkpoint_module = _load_aliased_parent_module(alias, source_root, "rbo_checkpoint")
experts_module = _load_aliased_parent_module(alias, source_root, "experts")
transfer_module = _load_aliased_parent_module(
alias,
source_root,
"knowledge_transfer_surfaces",
)
traversal_module = _load_aliased_parent_module(
alias,
source_root,
"rbo_traversal_tensors",
)
hotpath_id = _install_historical_tensor_native_hotpaths(
rbo_module,
experts_module,
transfer_module,
traversal_module,
)
if hotpath_id != HISTORICAL_TENSOR_NATIVE_HOTPATH_ID:
raise RuntimeError("historical Resynthesis tensor-native hot-path identity differs")
load_promoted = getattr(
integrated_module,
f"load_{_LEGACY_PARENT_PACKAGE_COMPONENT}_promoted",
None,
)
original_prefixed_loader = getattr(
integrated_module, "_load_prefixed_tensors", None
)
legacy_integrated_rbo_loader_name = (
f"_load_integrated_{_LEGACY_PARENT_PACKAGE_COMPONENT}_rbo"
)
original_rbo_loader = getattr(
integrated_module,
legacy_integrated_rbo_loader_name,
None,
)
original_additive_loader = getattr(
additive_module, "load_additive_state_dict", None
)
original_wire_additive_moe = getattr(additive_module, "wire_additive_moe", None)
additive_lm_head = getattr(additive_module, "additive_lm_head", None)
ladder_prefix = getattr(integrated_module, "LADDER_PREFIX", None)
rbo_prefix = getattr(
integrated_module,
_legacy_parent_upper_name("RBO_PREFIX"),
None,
)
build_parent_rbo = getattr(
rbo_module,
f"build_{_LEGACY_PARENT_PACKAGE_COMPONENT}_rbo",
None,
)
rbo_config_type = getattr(
rbo_module,
_legacy_parent_class_name("RBOConfig"),
None,
)
detect_layers = getattr(checkpoint_module, "detect_expert_layers", None)
detect_intermediate = getattr(checkpoint_module, "detect_moe_intermediate", None)
wire_parent_rbo = getattr(
additive_module,
f"wire_{_LEGACY_PARENT_PACKAGE_COMPONENT}_rbo",
None,
)
required = (
load_promoted,
original_prefixed_loader,
original_rbo_loader,
original_additive_loader,
original_wire_additive_moe,
additive_lm_head,
build_parent_rbo,
rbo_config_type,
detect_layers,
detect_intermediate,
wire_parent_rbo,
)
if not all(callable(value) for value in required):
raise RuntimeError("historical Resynthesis runtime lacks an exact graph constructor")
if not isinstance(ladder_prefix, str) or not isinstance(rbo_prefix, str):
raise RuntimeError("historical Resynthesis runtime prefixes are unavailable")
ladder_migration_applied = False
authoritative_rbo_tensor_count = 0
authoritative_rbo_key_set_sha256 = ""
additive_tensor_count_after_split = 0
embedded_legacy_rbo_key_set_sha256 = ""
legacy_state: dict[str, torch.Tensor] = {}
skipped_additive_initializer_targets: list[torch.Tensor] = []
additive_wire_invocations = 0
def compatible_prefixed_loader(
model_path: str | Path,
prefix: str,
target_device: str,
) -> dict[str, torch.Tensor]:
nonlocal ladder_migration_applied
assert callable(original_prefixed_loader)
state = original_prefixed_loader(model_path, prefix, target_device)
if not isinstance(state, dict) or not all(
isinstance(name, str) and isinstance(value, torch.Tensor)
for name, value in state.items()
):
raise RuntimeError("historical Resynthesis tensor loader returned invalid state")
if prefix == ladder_prefix:
state, migrated = _normalize_legacy_ladder_state(state)
ladder_migration_applied = ladder_migration_applied or migrated
return cast(dict[str, torch.Tensor], state)
def exact_rbo_loader(
model: Any,
*,
model_path: Path,
cfg: Any,
device: str,
dtype: torch.dtype,
) -> nn.Module:
nonlocal authoritative_rbo_tensor_count
nonlocal authoritative_rbo_key_set_sha256
state = compatible_prefixed_loader(model_path, rbo_prefix, "cpu")
if len(state) != expected_rbo_tensor_count:
raise RuntimeError(
"historical authoritative RBO tensor count differs: "
f"expected={expected_rbo_tensor_count} actual={len(state)}"
)
if not any(name.startswith("none_fabric.") for name in state):
raise RuntimeError(
"historical authoritative RBO has no model-owned NoNE Fabric"
)
assert callable(detect_intermediate)
assert callable(detect_layers)
assert callable(rbo_config_type)
assert callable(build_parent_rbo)
cfg.moe_intermediate_size = detect_intermediate(state)
rbo_cfg = rbo_config_type(
hidden_size=int(cfg.hidden_size),
n_intents=8,
n_expert_layers=detect_layers(state),
feedback_hidden_size=128,
)
intent = _FrozenWideIntent(hidden_size=int(cfg.hidden_size), carry_dim=512)
def construct_exact_rbo() -> nn.Module:
exact_rbo = cast(
nn.Module,
build_parent_rbo(cfg, rbo_cfg, intent_module=intent),
)
exact_rbo.register_buffer(
"_resynthesis_recursive_arm_exhausted",
torch.zeros((), dtype=torch.bool),
persistent=False,
)
return exact_rbo
rbo = _build_exact_historical_rbo_from_state(
construct_exact_rbo,
state,
device=device,
dtype=dtype,
)
assert callable(wire_parent_rbo)
wire_parent_rbo(model, rbo)
rbo.requires_grad_(False)
rbo.eval()
model.resynthesis_rbo = rbo
model.resynthesis_rbo_packaging = "integrated_exact_historical_source"
model.resynthesis_none_architecture_active = True
authoritative_rbo_tensor_count = len(state)
authoritative_rbo_key_set_sha256 = hashlib.sha256(
"\n".join(sorted(state)).encode("utf-8")
).hexdigest()
return rbo
def compatible_additive_loader(
model: Any,
state: Mapping[str, torch.Tensor],
*,
device: str | torch.device | None = None,
) -> None:
nonlocal additive_tensor_count_after_split
nonlocal embedded_legacy_rbo_key_set_sha256
nonlocal legacy_state
assert callable(original_additive_loader)
additive_state, captured_legacy = _split_embedded_legacy_rbo_state(state)
embedded_legacy_rbo_key_set_sha256 = _validate_embedded_legacy_rbo_split(
state,
additive_state,
captured_legacy,
expected_source_tensor_count=expected_additive_tensor_count,
)
if additive_wire_invocations != 1:
raise RuntimeError(
"historical additive checkpoint load did not follow one exact wire"
)
assert callable(additive_lm_head)
head = additive_lm_head(model)
if not isinstance(head, nn.Module):
raise RuntimeError("historical additive loader found no additive head")
_validate_historical_additive_initializer_targets(
head,
additive_state,
skipped_additive_initializer_targets,
)
_load_additive_state_into_resident_owner_boundary(
original_additive_loader,
model,
additive_state,
)
additive_tensor_count_after_split = len(additive_state)
legacy_state = captured_legacy
def compatible_wire_additive_moe(
model: Any,
cfg: Any,
n_layers: int = 2,
) -> Any:
nonlocal additive_wire_invocations
additive_wire_invocations += 1
if additive_wire_invocations != 1:
raise RuntimeError("historical additive owner was wired more than once")
assert callable(original_wire_additive_moe)
assert callable(additive_lm_head)
return _wire_exact_historical_additive_without_overwritten_initializers(
original_wire_additive_moe,
additive_lm_head,
model,
cfg,
n_layers=n_layers,
skipped_persistent_targets=skipped_additive_initializer_targets,
)
setattr(integrated_module, "_load_prefixed_tensors", compatible_prefixed_loader)
setattr(integrated_module, legacy_integrated_rbo_loader_name, exact_rbo_loader)
setattr(additive_module, "load_additive_state_dict", compatible_additive_loader)
setattr(additive_module, "wire_additive_moe", compatible_wire_additive_moe)
try:
assert callable(load_promoted)
with _relocated_parent_checkpoint_view(cfg) as checkpoint_view:
loaded = _call_without_transformers_allocator_warmup(
load_promoted,
str(checkpoint_view),
device=device,
dtype=torch.bfloat16,
)
finally:
setattr(additive_module, "wire_additive_moe", original_wire_additive_moe)
setattr(integrated_module, "_load_prefixed_tensors", original_prefixed_loader)
setattr(
integrated_module,
legacy_integrated_rbo_loader_name,
original_rbo_loader,
)
setattr(additive_module, "load_additive_state_dict", original_additive_loader)
runtime = loaded[0] if isinstance(loaded, tuple) and loaded else None
if not isinstance(runtime, nn.Module):
raise RuntimeError("historical Resynthesis loader returned no runtime module")
vocabulary_graph = loaded[1] if isinstance(loaded, tuple) and len(loaded) > 1 else None
_bind_resynthesis_parent_runtime_facade(
runtime,
vocabulary_graph=vocabulary_graph,
)
final_hidden_hotpath_id = _install_parent_final_hidden_only_forward_boundary(
runtime
)
if final_hidden_hotpath_id != PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID:
raise RuntimeError("historical parent final-hidden hot-path identity differs")
if len(legacy_state) != LEGACY_RBO_CAPABILITY_TENSOR_COUNT:
raise RuntimeError(
"historical embedded legacy capability payload was not captured"
)
capability_source_sha256 = _verified_legacy_capability_provenance(cfg)
bank = LegacyRBOCapabilityBank(legacy_state)
receipt = ResynthesisBoundaryMigrationReceipt(
ladder_namespace_applied=ladder_migration_applied,
embedded_legacy_rbo_applied=True,
embedded_legacy_rbo_tensor_count=len(legacy_state),
additive_tensor_count_after_split=additive_tensor_count_after_split,
embedded_legacy_rbo_key_set_sha256=embedded_legacy_rbo_key_set_sha256,
authoritative_rbo_tensor_count=authoritative_rbo_tensor_count,
authoritative_rbo_key_set_sha256=authoritative_rbo_key_set_sha256,
exact_historical_source_loaded=True,
)
return loaded, receipt, bank, capability_source_sha256
def resynthesis_parent_info(cfg: ResynthesisConfig) -> ResynthesisParentInfo:
"""Extract typed base info without loading weights (cheap, for validation)."""
raw = load_resynthesis_parent_config(cfg)
manifest = load_resynthesis_parent_manifest(cfg)
parent_source_hashes = _verified_parent_source_hashes(cfg)
observed_parent_source_bundle_sha256 = _source_bundle_sha256(
parent_source_hashes
)
parent_source_bundle_sha256 = cfg.parent_source_bundle_sha256
capability_source_sha256 = _verified_legacy_capability_provenance(cfg)
text_cfg = raw.get("text_config", raw)
none_rbo = manifest.get("none_rbo")
additive_moe = manifest.get("additive_moe")
native_decode_confidence = manifest.get("native_decode_confidence")
model_artifact = manifest.get("model_artifact")
if (
not isinstance(none_rbo, dict)
or not isinstance(additive_moe, dict)
or not isinstance(native_decode_confidence, dict)
or not isinstance(model_artifact, dict)
):
raise RuntimeError(
"Resynthesis checkpoint lacks integrated NoNE/RBO, adaptive experts, or native confidence"
)
artifact_composition = manifest.get("composition")
artifact_checkpoint_id = manifest.get("checkpoint_id")
if (
artifact_composition != _LEGACY_PARENT_COMPOSITION
or not isinstance(artifact_checkpoint_id, str)
or not artifact_checkpoint_id
):
raise RuntimeError(
"Resynthesis parent artifact identity differs from its sealed lineage"
)
weights_path = _resolve_path(cfg.base_model_dir, cfg.base_weights)
resolved_native_root = Path(cfg.base_model_dir).expanduser().resolve()
parameter_elements = _safetensors_parameter_elements(weights_path)
native_manifest_sha256, migration_promotion_eligible = (
_verified_resynthesis_native_parent_manifest(
cfg,
resolved_native_root,
weights_path,
parameter_elements,
manifest,
)
)
return ResynthesisParentInfo(
hidden_size=int(
text_cfg.get("hidden_size", RESYNTHESIS_HIDDEN_SIZE)
),
num_hidden_layers=int(
text_cfg.get(
"num_hidden_layers", RESYNTHESIS_NUM_HIDDEN_LAYERS
)
),
vocab_size=int(
text_cfg.get("vocab_size", RESYNTHESIS_PROJECTION_VOCAB_SIZE)
),
max_position_embeddings=max(
int(
text_cfg.get(
"max_position_embeddings",
RESYNTHESIS_MAX_POSITION_EMBEDDINGS,
)
),
RESYNTHESIS_MAX_POSITION_EMBEDDINGS,
),
num_attention_heads=int(
text_cfg.get(
"num_attention_heads", RESYNTHESIS_NUM_ATTENTION_HEADS
)
),
num_key_value_heads=int(
text_cfg.get(
"num_key_value_heads",
RESYNTHESIS_NUM_KEY_VALUE_HEADS,
)
),
intermediate_size=int(
text_cfg.get(
"intermediate_size", RESYNTHESIS_INTERMEDIATE_SIZE
)
),
head_dim=int(text_cfg.get("head_dim", RESYNTHESIS_HEAD_DIM)),
weights_path=str(weights_path),
config_path=str(_resolve_path(cfg.base_model_dir, cfg.config_path)),
baseline_frozen=True,
tie_word_embeddings=bool(raw.get("tie_word_embeddings", False)),
model_type=_RESYNTHESIS_PARENT_MODEL_TYPE,
composition=_RESYNTHESIS_PARENT_COMPOSITION,
integrated_rbo_tensors=int(none_rbo.get("n_tensors", 0)),
integrated_additive_tensors=int(additive_moe.get("n_tensors", 0)),
integrated_native_decode_confidence_tensors=int(
native_decode_confidence.get("n_tensors", 0)
),
checkpoint_id=(
"resynthesis-native-parent:"
f"{str(model_artifact.get('artifact_sha256', ''))}"
),
manifest_payload_sha256=str(manifest.get("manifest_payload_sha256", "")),
model_artifact_sha256=str(model_artifact.get("artifact_sha256", "")),
parameter_elements=parameter_elements,
native_owner="Resynthesis",
native_generation=RESYNTHESIS_NATIVE_PARENT_GENERATION,
native_root=str(resolved_native_root),
native_manifest_path=str(
Path(cfg.native_parent_manifest_path).expanduser().resolve()
),
native_manifest_sha256=native_manifest_sha256,
native_migration_promotion_eligible=(migration_promotion_eligible),
parent_source_bundle_sha256=parent_source_bundle_sha256,
observed_parent_source_bundle_sha256=(
observed_parent_source_bundle_sha256
),
parent_source_bundle_matches_expected=(
observed_parent_source_bundle_sha256
== parent_source_bundle_sha256
),
legacy_capability_source_sha256=capability_source_sha256,
historical_inherited_checkpoint_id=artifact_checkpoint_id,
historical_inherited_composition=artifact_composition,
historical_inherited_model_type=str(
raw.get("model_type", text_cfg.get("model_type", ""))
),
)
def _build_native_hybrid_context_cache(runtime: nn.Module) -> Any:
"""Build the parent's bounded hot-KV plus global recurrent cache.
This is a storage-boundary adapter for the immutable parent architecture.
It does not select an answer or route: all input tokens still execute every
decoder layer. The 24 trained linear-attention layers retain their global
recurrent state, while the eight full-attention layers retain one native
Dual-Chunk local window of hot K/V.
"""
runtime_config = getattr(runtime, "config", None)
get_text_config = getattr(runtime_config, "get_text_config", None)
if not callable(get_text_config):
raise RuntimeError(
"Resynthesis runtime exposes no text configuration for native hybrid K/V"
)
text_config = get_text_config(decoder=True)
layer_types = getattr(text_config, "layer_types", None)
if (
not isinstance(layer_types, (list, tuple))
or len(layer_types) != RESYNTHESIS_NUM_HIDDEN_LAYERS
or not all(isinstance(layer_type, str) for layer_type in layer_types)
):
raise RuntimeError("Resynthesis native hybrid K/V layer geometry differs")
linear_layers = sum(layer_type == "linear_attention" for layer_type in layer_types)
full_layers = sum(layer_type == "full_attention" for layer_type in layer_types)
if (
linear_layers != RESYNTHESIS_LINEAR_ATTENTION_LAYERS
or full_layers != RESYNTHESIS_FULL_ATTENTION_LAYERS
or linear_layers + full_layers != len(layer_types)
):
raise RuntimeError(
"Resynthesis native hybrid K/V does not match the trained parent topology"
)
from transformers.cache_utils import (
Cache,
DynamicSlidingWindowLayer,
LinearAttentionLayer,
)
cache_layers: list[Any] = []
for layer_type in layer_types:
if layer_type == "linear_attention":
cache_layers.append(cast(Any, LinearAttentionLayer)())
else:
cache_layers.append(
DynamicSlidingWindowLayer(
sliding_window=RESYNTHESIS_NATIVE_HOT_KV_TOKENS
)
)
cache = Cache(layers=cache_layers)
setattr(cache, "_resynthesis_native_hybrid_context", True)
setattr(
cache,
"_resynthesis_recurrent_layer_count",
RESYNTHESIS_LINEAR_ATTENTION_LAYERS,
)
setattr(
cache,
"_resynthesis_full_attention_layer_count",
RESYNTHESIS_FULL_ATTENTION_LAYERS,
)
setattr(
cache,
"_resynthesis_hot_window_tokens",
RESYNTHESIS_NATIVE_HOT_KV_TOKENS,
)
return cache
def _expand_immutable_native_hybrid_context_cache_boundary(
master_cache: object,
batch_indices_t: torch.Tensor,
) -> Any:
"""Clone one sealed parent prefix cache and expand only its isolated copy.
The parent prefix is immutable shared evidence. ``batch_indices_t`` is a
tensor-native all-zero reorder index: each output row selects the one
authoritative prefix row. Transformers does not implement
``batch_repeat_interleave`` for ``LinearAttentionLayer``, while
``reorder_cache`` supports both that recurrent layer and
``DynamicSlidingWindowLayer``. Deep-copying before the reorder preserves
the master tensors and every cache-layer bookkeeping field.
"""
from transformers.cache_utils import (
Cache,
DynamicSlidingWindowLayer,
LinearAttentionLayer,
)
if (
not isinstance(master_cache, Cache)
or getattr(master_cache, "_resynthesis_native_hybrid_context", False)
is not True
):
raise RuntimeError(
"immutable prefix expansion requires the native hybrid context cache"
)
if (
batch_indices_t.ndim != 1
or batch_indices_t.dtype != torch.long
or batch_indices_t.numel() < 1
):
raise RuntimeError(
"immutable prefix expansion requires a nonempty rank-one long index"
)
torch._assert_async(
batch_indices_t.eq(0).all(),
"immutable prefix expansion index must select only the sealed prefix row",
)
layers = master_cache.layers
if (
not isinstance(layers, list)
or len(layers) != RESYNTHESIS_NUM_HIDDEN_LAYERS
or sum(isinstance(layer, LinearAttentionLayer) for layer in layers)
!= RESYNTHESIS_LINEAR_ATTENTION_LAYERS
or sum(isinstance(layer, DynamicSlidingWindowLayer) for layer in layers)
!= RESYNTHESIS_FULL_ATTENTION_LAYERS
):
raise RuntimeError("immutable prefix cache topology differs")
for layer in layers:
if isinstance(layer, LinearAttentionLayer):
for state_t in (layer.conv_states, layer.recurrent_states):
if state_t is not None and (
state_t.ndim < 1 or state_t.shape[0] != 1
):
raise RuntimeError(
"immutable recurrent prefix cache must contain one row"
)
elif isinstance(layer, DynamicSlidingWindowLayer):
for state_t in (layer.keys, layer.values):
if state_t is not None and (
state_t.ndim < 1 or state_t.shape[0] != 1
):
raise RuntimeError(
"immutable sliding-window prefix cache must contain one row"
)
expanded_cache = copy.deepcopy(master_cache)
expanded_cache.reorder_cache(cast(torch.LongTensor, batch_indices_t))
return expanded_cache
def _native_context_cache_telemetry_boundary(
cache: object,
*,
device: torch.device,
) -> NativeContextCacheTelemetry:
"""Observe cache storage geometry without influencing model decisions."""
packet = NativeContextCacheTelemetry(
hybrid_active=torch.empty((), device=device, dtype=torch.bool),
total_positions=torch.empty((), device=device, dtype=torch.long),
hot_resident_positions=torch.empty((), device=device, dtype=torch.long),
hot_window_tokens=torch.empty((), device=device, dtype=torch.long),
recurrent_layer_count=torch.empty((), device=device, dtype=torch.long),
full_attention_layer_count=torch.empty(
(),
device=device,
dtype=torch.long,
),
)
_update_native_context_cache_telemetry_boundary(cache, packet=packet)
return packet
def _update_native_context_cache_telemetry_boundary(
cache: object,
*,
packet: NativeContextCacheTelemetry,
) -> None:
"""Fill preallocated cache telemetry tensors without per-wave allocation."""
hybrid_active = bool(getattr(cache, "_resynthesis_native_hybrid_context", False))
recurrent_layers = int(getattr(cache, "_resynthesis_recurrent_layer_count", 0))
full_layers = int(getattr(cache, "_resynthesis_full_attention_layer_count", 0))
hot_window = int(getattr(cache, "_resynthesis_hot_window_tokens", 0))
total_positions = 0
get_seq_length = getattr(cache, "get_seq_length", None)
if callable(get_seq_length):
total_positions = int(get_seq_length())
elif isinstance(getattr(cache, "positions", None), int):
total_positions = int(getattr(cache, "positions"))
hot_resident_positions = 0
layers = getattr(cache, "layers", None)
if isinstance(layers, list):
for layer in layers:
keys = getattr(layer, "keys", None)
if isinstance(keys, torch.Tensor) and keys.ndim >= 2:
hot_resident_positions = max(
hot_resident_positions,
int(keys.shape[-2]),
)
elif hybrid_active:
hot_resident_positions = min(total_positions, hot_window)
with torch.no_grad():
packet.hybrid_active.fill_(hybrid_active)
packet.total_positions.fill_(total_positions)
packet.hot_resident_positions.fill_(hot_resident_positions)
packet.hot_window_tokens.fill_(hot_window)
packet.recurrent_layer_count.fill_(recurrent_layers)
packet.full_attention_layer_count.fill_(full_layers)
class ResynthesisNativeParent(nn.Module):
"""Frozen Resynthesis-owned parent exposing trained hidden/logit surfaces.
The base weights are loaded and frozen (requires_grad=False). The forward
pass produces the final hidden states [batch, seq, hidden_size] that the
additive science stack + RBO operate on.
For training, the base is a feature extractor: gradients flow only through
the additive science layers, not the frozen base (Pillar: additive-only,
baseline-frozen).
"""
_base_loaded_marker: torch.Tensor
_decode_cached_positions: torch.Tensor
_native_context_full_attention_layer_count: torch.Tensor
_native_context_hot_resident_positions: torch.Tensor
_native_context_hot_window_tokens: torch.Tensor
_native_context_hybrid_active: torch.Tensor
_native_context_recurrent_layer_count: torch.Tensor
_native_context_total_positions: torch.Tensor
_parent_inference_session_buffers_normalized: torch.Tensor
_training_low_rank_projection_cache: torch.Tensor | None
_training_low_rank_projection_source_id: int | None
_training_low_rank_projection_source_version: int | None
_last_frozen_backbone_final_hidden_t: torch.Tensor | None
_last_frozen_backbone_summary_hidden_t: torch.Tensor | None
_last_frozen_backbone_input_positions_t: torch.Tensor | None
def __init__(
self, cfg: ResynthesisConfig, *, device: torch.device | str = "cpu"
) -> None:
super().__init__()
self.cfg = cfg
self.device = torch.device(device)
self.info = resynthesis_parent_info(cfg)
self._weights_loaded = False
self.runtime: nn.Module | None = None
self.tokenizer: Any | None = None
self.tokenizer_backend_identity: ResynthesisTokenizerIdentity | None = None
self._last_forward: ResynthesisParentForward | None = None
self._decode_past_key_values: Any | None = None
self._decode_authority_active = False
self._parent_session_may_hold_inference_tensors = False
self._parent_session_buffers_verified_normal = False
self._training_low_rank_projection_cache = None
self._training_low_rank_projection_source_id = None
self._training_low_rank_projection_source_version = None
self._last_frozen_backbone_final_hidden_t = None
self._last_frozen_backbone_summary_hidden_t = None
self._last_frozen_backbone_input_positions_t = None
self.verified_model_artifact_sha256 = ""
self.ladder_namespace_migration_applied = False
self.embedded_legacy_rbo_migration_applied = False
self.embedded_legacy_rbo_tensor_count = 0
self.additive_tensor_count_after_legacy_split = 0
self.embedded_legacy_rbo_key_set_sha256 = ""
self.authoritative_rbo_tensor_count = 0
self.authoritative_rbo_key_set_sha256 = ""
self.exact_historical_source_loaded = False
self.historical_tensor_native_hotpath_id = ""
self.historical_recursive_arm_exhaustion_id = ""
self.legacy_capability_source_sha256 = ""
object.__setattr__(self, "_pending_legacy_capability_bank", None)
self.register_buffer(
"_base_loaded_marker", torch.tensor([0], dtype=torch.int8), persistent=False
)
self.register_buffer(
"_decode_cached_positions",
torch.zeros((), dtype=torch.long),
persistent=False,
)
self.register_buffer(
"_parent_inference_session_buffers_normalized",
torch.zeros((), dtype=torch.long),
persistent=False,
)
self.register_buffer(
"_native_context_hybrid_active",
torch.zeros((), dtype=torch.bool),
persistent=False,
)
for buffer_name in (
"_native_context_total_positions",
"_native_context_hot_resident_positions",
"_native_context_hot_window_tokens",
"_native_context_recurrent_layer_count",
"_native_context_full_attention_layer_count",
):
self.register_buffer(
buffer_name,
torch.zeros((), dtype=torch.long),
persistent=False,
)
def load_weights(self) -> "ResynthesisNativeParent":
"""Load the complete native backbone + adaptive MoE + NoNE/RBO graph.
The previous loader registered checkpoint tensors as inert buffers and
reduced the base forward to an embedding lookup. Loading now goes
through Resynthesis's integrated constructor directly in this process, making
its trained decoder, adaptive experts, NoNE Fabric, RBO traversal, VGE,
and native head children of this model graph.
"""
if self._weights_loaded:
return self
weights_path = Path(self.info.weights_path)
if not weights_path.is_file():
raise FileNotFoundError(
f"Resynthesis base weights not found: {weights_path}. "
"Set ResynthesisConfig.base_model_dir to the integrated Resynthesis checkpoint directory."
)
if self.info.composition != _RESYNTHESIS_PARENT_COMPOSITION:
raise RuntimeError(
"Resynthesis requires Resynthesis's one-model NoNE/RBO composition"
)
if (
self.info.integrated_rbo_tensors <= 0
or self.info.integrated_additive_tensors <= 0
or self.info.integrated_native_decode_confidence_tensors <= 0
):
raise RuntimeError(
"Resynthesis requires trained integrated RBO, adaptive-expert, and native-confidence tensors"
)
fastokens_dependency = activate_resynthesis_fastokens(self.cfg)
from resynthesis.none_paging import file_sha256_authority_boundary
parent_sha256_cache_root = (
Path(__file__).resolve().parents[1]
/ ".nnf-resynthesis"
/ "artifact_sha256_identity_cache"
/ RESYNTHESIS_NATIVE_PARENT_GENERATION
)
preload_artifact_sha256 = file_sha256_authority_boundary(
weights_path,
expected_sha256=self.info.model_artifact_sha256,
identity_cache_root=parent_sha256_cache_root,
)
loaded, migration, legacy_bank, capability_source_sha256 = (
_load_exact_resynthesis_parent(
self.cfg,
device=str(self.device),
expected_rbo_tensor_count=self.info.integrated_rbo_tensors,
expected_additive_tensor_count=self.info.integrated_additive_tensors,
)
)
runtime, vocabulary_graph, _bank, tokenizer, _ladder = loaded
loaded_tokenizer_identity = tokenizer_identity(
tokenizer,
dependency=fastokens_dependency,
tokenizer_path=_resolve_path(
self.cfg.base_model_dir,
self.cfg.tokenizer_path,
),
inherited_tokenizer_path=_resolve_path(
self.cfg.base_model_dir,
self.cfg.tokenizer_path,
),
)
setattr(
tokenizer,
"_resynthesis_tokenizer_identity",
loaded_tokenizer_identity,
)
if not isinstance(runtime, nn.Module):
raise RuntimeError(
"Resynthesis integrated constructor returned a non-module runtime"
)
_bind_resynthesis_parent_runtime_facade(
runtime,
vocabulary_graph=vocabulary_graph,
)
if getattr(runtime, "resynthesis_rbo", None) is None:
raise RuntimeError("Resynthesis integrated runtime has no trained in-graph RBO")
if not bool(
getattr(runtime, "resynthesis_none_architecture_active", False)
):
raise RuntimeError(
"Resynthesis integrated runtime has no active NoNE architecture"
)
native_decode_confidence = getattr(runtime, "native_decode_confidence", None)
if not isinstance(native_decode_confidence, nn.Module):
raise RuntimeError(
"Resynthesis integrated runtime has no native decode-confidence diagnostic"
)
native_confidence_tensor_count = len(native_decode_confidence.state_dict())
if (
native_confidence_tensor_count
!= self.info.integrated_native_decode_confidence_tensors
):
raise RuntimeError(
"Resynthesis native decode-confidence tensor count differs from its manifest"
)
verified_artifact_sha256 = file_sha256_authority_boundary(
weights_path,
expected_sha256=self.info.model_artifact_sha256,
identity_cache_root=parent_sha256_cache_root,
)
if verified_artifact_sha256 != preload_artifact_sha256:
raise RuntimeError(
"loaded Resynthesis model artifact SHA-256 changed during parent load"
)
runtime.requires_grad_(False)
runtime.eval()
self.runtime = runtime
self.tokenizer = tokenizer
self.tokenizer_backend_identity = loaded_tokenizer_identity
self.verified_model_artifact_sha256 = verified_artifact_sha256
self.ladder_namespace_migration_applied = migration.ladder_namespace_applied
self.embedded_legacy_rbo_migration_applied = (
migration.embedded_legacy_rbo_applied
)
self.embedded_legacy_rbo_tensor_count = (
migration.embedded_legacy_rbo_tensor_count
)
self.additive_tensor_count_after_legacy_split = (
migration.additive_tensor_count_after_split
)
self.embedded_legacy_rbo_key_set_sha256 = (
migration.embedded_legacy_rbo_key_set_sha256
)
self.authoritative_rbo_tensor_count = migration.authoritative_rbo_tensor_count
self.authoritative_rbo_key_set_sha256 = (
migration.authoritative_rbo_key_set_sha256
)
self.exact_historical_source_loaded = migration.exact_historical_source_loaded
self.historical_tensor_native_hotpath_id = (
HISTORICAL_TENSOR_NATIVE_HOTPATH_ID
if migration.exact_historical_source_loaded
else ""
)
self.historical_recursive_arm_exhaustion_id = (
HISTORICAL_RECURSIVE_ARM_EXHAUSTION_ID
if migration.exact_historical_source_loaded
else ""
)
self.legacy_capability_source_sha256 = capability_source_sha256
object.__setattr__(self, "_pending_legacy_capability_bank", legacy_bank)
self._weights_loaded = True
self._base_loaded_marker.fill_(1)
return self
def checkpoint_lineage(self) -> dict[str, Any]:
"""Return immutable parent identity at the checkpoint I/O boundary."""
if not self._weights_loaded:
self.load_weights()
if not all(
(
self.info.checkpoint_id,
self.info.manifest_payload_sha256,
self.info.model_artifact_sha256,
)
):
raise RuntimeError(
"integrated Resynthesis parent has incomplete artifact lineage"
)
return {
"schema": "nnf.resynthesis.parent_lineage.v4",
"checkpointId": self.info.public_checkpoint_id,
"manifestPayloadSha256": self.info.manifest_payload_sha256,
"modelArtifactSha256": self.info.model_artifact_sha256,
"parameterElements": self.info.parameter_elements,
"nativeOwner": self.info.native_owner,
"nativeGeneration": self.info.native_generation,
"nativeRoot": self.info.native_root,
"nativeManifestSha256": self.info.native_manifest_sha256,
"nativeMigrationPromotionEligible": (
self.info.native_migration_promotion_eligible
),
"externalProductCheckpointDependency": False,
"composition": self.info.public_composition,
"modelType": self.info.public_model_type,
"historicalInheritedCheckpointId": (
self.info.historical_inherited_checkpoint_id
),
"historicalInheritedComposition": (
self.info.historical_inherited_composition
),
"historicalInheritedModelType": (
self.info.historical_inherited_model_type
),
"rboTensorCount": self.info.integrated_rbo_tensors,
"adaptiveTensorCount": self.info.integrated_additive_tensors,
"nativeDecodeConfidenceTensorCount": (
self.info.integrated_native_decode_confidence_tensors
),
"authoritativeRboKeySetSha256": self.authoritative_rbo_key_set_sha256,
"exactHistoricalSourceLoaded": self.exact_historical_source_loaded,
"historicalTensorNativeHotpathId": (
self.historical_tensor_native_hotpath_id
),
"historicalTensorNativeExpertDispatch": True,
"historicalTensorNativeHopSelection": True,
"historicalRecursiveArmExhaustionId": (
self.historical_recursive_arm_exhaustion_id
),
"historicalRecursiveArmExhaustionPropagation": True,
"embeddedLegacyCapabilityTensorCount": self.embedded_legacy_rbo_tensor_count,
"embeddedLegacyCapabilityKeySetSha256": (
self.embedded_legacy_rbo_key_set_sha256
),
"nativeAnswerSurface": "rbo_head_argmax_mapped_through_trained_vge",
"parentDualChunkRoPECompose": True,
"parentOnlineSoftmaxLongPool": True,
"nativeAttentionPositionAperture": NATIVE_ATTENTION_POSITION_APERTURE,
"onlineSoftmaxTileTokens": RESYNTHESIS_ONLINE_SOFTMAX_TILE_TOKENS,
"dualChunkPretrainLength": DUAL_CHUNK_PRETRAIN_LENGTH,
"dualChunkLocalSize": DUAL_CHUNK_LOCAL_SIZE,
"dualChunkAtSuccessiveSeamExposed": True,
"pretrainedRoPEBandTokens": PRETRAINED_ROPE_BAND_TOKENS,
"nativePrefillTileTokens": RESYNTHESIS_NATIVE_PREFILL_TILE_TOKENS,
}
def tokenizer_backend_receipt_boundary(self) -> dict[str, object]:
"""Serialize the verified parent-BPE executor at an I/O boundary."""
if not self._weights_loaded:
self.load_weights()
if self.tokenizer is None or self.tokenizer_backend_identity is None:
raise RuntimeError("integrated parent has no verified tokenizer backend")
return tokenizer_boundary_receipt(self.tokenizer)
def take_legacy_capability_bank(self) -> nn.Module | None:
"""Transfer the preserved payload into the trainable Resynthesis graph."""
if not self._weights_loaded:
self.load_weights()
bank = getattr(self, "_pending_legacy_capability_bank", None)
if bank is not None and not isinstance(bank, nn.Module):
raise RuntimeError("pending legacy capability owner is not a module")
object.__setattr__(self, "_pending_legacy_capability_bank", None)
return bank
def active_none_fabric(self) -> nn.Module:
"""Return the exact trained NoNE fabric owned by the loaded parent graph."""
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
parent_rbo = getattr(runtime, "resynthesis_rbo", None)
parent_fabric = getattr(parent_rbo, "none_fabric", None)
if not isinstance(parent_fabric, nn.Module):
raise RuntimeError("Resynthesis integrated RBO has no trained NoNE fabric module")
if not callable(getattr(parent_fabric, "step_phase", None)):
raise RuntimeError(
"Resynthesis parent NoNE fabric exposes no step_phase contract"
)
return parent_fabric
def _record_native_context_cache_telemetry_boundary(
self,
cache: object,
) -> None:
"""Update diagnostic cache geometry in model-owned tensor buffers."""
packet = NativeContextCacheTelemetry(
hybrid_active=self._native_context_hybrid_active,
total_positions=self._native_context_total_positions,
hot_resident_positions=self._native_context_hot_resident_positions,
hot_window_tokens=self._native_context_hot_window_tokens,
recurrent_layer_count=self._native_context_recurrent_layer_count,
full_attention_layer_count=(
self._native_context_full_attention_layer_count
),
)
_update_native_context_cache_telemetry_boundary(
cache,
packet=packet,
)
def native_context_cache_telemetry_boundary(
self,
) -> NativeContextCacheTelemetry:
"""Return read-only tensor evidence; this packet has no answer authority."""
return NativeContextCacheTelemetry(
hybrid_active=self._native_context_hybrid_active.detach().clone(),
total_positions=self._native_context_total_positions.detach().clone(),
hot_resident_positions=(
self._native_context_hot_resident_positions.detach().clone()
),
hot_window_tokens=(self._native_context_hot_window_tokens.detach().clone()),
recurrent_layer_count=(
self._native_context_recurrent_layer_count.detach().clone()
),
full_attention_layer_count=(
self._native_context_full_attention_layer_count.detach().clone()
),
)
def _prefill_tiled_native(
self,
*,
runtime: nn.Module,
active_input_ids: torch.Tensor,
position_ids: torch.Tensor,
attention_mask: torch.Tensor,
record_kv: object,
starting_prefix: torch.Tensor,
telemetry_required: bool,
) -> NativeTiledPrefill:
"""Run a retained-cache prefill for native autoregressive continuation."""
return self._prefill_tiled_native_impl(
runtime=runtime,
active_input_ids=active_input_ids,
position_ids=position_ids,
attention_mask=attention_mask,
record_kv=record_kv,
starting_prefix=starting_prefix,
telemetry_required=telemetry_required,
retain_final_cache=True,
)
def _prefill_tiled_training_native(
self,
*,
runtime: nn.Module,
active_input_ids: torch.Tensor,
position_ids: torch.Tensor,
attention_mask: torch.Tensor,
record_kv: object,
starting_prefix: torch.Tensor,
telemetry_required: bool,
) -> NativeTiledPrefill:
"""Run an exact masked training prefill without retaining its final cache."""
return self._prefill_tiled_native_impl(
runtime=runtime,
active_input_ids=active_input_ids,
position_ids=position_ids,
attention_mask=attention_mask,
record_kv=record_kv,
starting_prefix=starting_prefix,
telemetry_required=telemetry_required,
retain_final_cache=False,
)
def _prefill_tiled_native_impl(
self,
*,
runtime: nn.Module,
active_input_ids: torch.Tensor,
position_ids: torch.Tensor,
attention_mask: torch.Tensor,
record_kv: object,
starting_prefix: torch.Tensor,
telemetry_required: bool,
retain_final_cache: bool,
) -> NativeTiledPrefill:
"""Tile the parent prefill so 4M+ prompts fit bounded activation memory.
Each tile threads the parent cache and uses a CUMULATIVE attention mask
(``attention_mask[:, :end]``). Within the pretrained band, the parent
keeps exact full-attention K/V. Longer prompts use its trained hybrid
topology: all 24 linear-attention layers keep global recurrent state,
while eight full-attention layers keep one Dual-Chunk hot K/V window.
Folded ``position_ids`` are sliced per tile (never re-folded), and no
token is dropped or truncated.
Raises if the parent loses its KV cache before every prompt token has
been preflighted.
"""
total_prefill_tokens = int(active_input_ids.shape[1])
tile_tokens = min(
total_prefill_tokens,
RESYNTHESIS_NATIVE_PREFILL_TILE_TOKENS,
)
running_prefix = starting_prefix.clone()
tile_past: Any = None
summary_hidden: torch.Tensor | None = None
summary_index = 0
summary_capacity = (
(total_prefill_tokens + tile_tokens - 1) // tile_tokens
) * RESYNTHESIS_NATIVE_PREFILL_SUMMARIES_PER_TILE
if total_prefill_tokens > RESYNTHESIS_NATIVE_HYBRID_ACTIVATION_TOKENS:
custom_cache_builder = getattr(
runtime,
"resynthesis_build_native_hybrid_context_cache",
None,
)
if callable(custom_cache_builder):
tile_past = custom_cache_builder(
hot_window_tokens=active_input_ids.new_ones(
(), dtype=torch.long
).mul_(RESYNTHESIS_NATIVE_HOT_KV_TOKENS)
)
else:
tile_past = _build_native_hybrid_context_cache(runtime)
if not bool(
getattr(
tile_past,
"_resynthesis_native_hybrid_context",
False,
)
):
raise RuntimeError(
"Resynthesis native hybrid context cache has no model-owned marker"
)
out: Any = None
for start in range(0, total_prefill_tokens, tile_tokens):
end = min(total_prefill_tokens, start + tile_tokens)
tile_cache_required = retain_final_cache or end != total_prefill_tokens
tile_ids = active_input_ids[:, start:end]
tile_positions = position_ids[:, start:end]
# Cumulative mask keeps every prior token attendable under exact SDPA.
tile_mask = attention_mask[:, :end]
tile_new_positions = tile_ids.new_ones(
(), dtype=torch.long
).mul_(tile_ids.shape[1])
if callable(record_kv):
record_kv(
prefix_positions=running_prefix,
new_positions=tile_new_positions,
)
elif telemetry_required:
raise RuntimeError(
"Resynthesis integrated runtime lacks tensor-native KV telemetry"
)
out = runtime(
input_ids=tile_ids,
position_ids=tile_positions,
attention_mask=tile_mask,
past_key_values=tile_past,
output_hidden_states=True,
return_dict=True,
use_cache=tile_cache_required,
logits_to_keep=1,
)
tile_hidden_states = getattr(out, "hidden_states", None)
if not tile_hidden_states or not isinstance(
tile_hidden_states[-1], torch.Tensor
):
raise RuntimeError(
"Resynthesis native prefill returned no hidden state for additive attention"
)
tile_hidden = tile_hidden_states[-1]
if tile_hidden.ndim != 3 or tile_hidden.shape[1] < 1:
raise RuntimeError("Resynthesis native prefill hidden geometry differs")
if summary_hidden is None:
summary_hidden = tile_hidden.new_empty(
tile_hidden.shape[0],
summary_capacity,
tile_hidden.shape[-1],
)
segment_count = min(
RESYNTHESIS_NATIVE_PREFILL_SUMMARIES_PER_TILE,
tile_hidden.shape[1],
)
for segment_index in range(segment_count):
segment_start = segment_index * tile_hidden.shape[1] // segment_count
segment_end = (
(segment_index + 1) * tile_hidden.shape[1] // segment_count
)
segment_hidden = tile_hidden[:, segment_start:segment_end, :]
# The installed final-hidden-only parent contract returns one
# logits-aligned position for ``logits_to_keep=1``. Attention
# over a singleton has exact unit weight, so its output is the
# same tensor. Avoid launching score, softmax, ring-softmax,
# matmul, arange, and allocating index_copy for every prefill
# tile. The multi-position compatibility path retains the full
# trained attention pool without changing its semantics.
segment_context = (
segment_hidden[:, 0, :]
if segment_hidden.shape[1] == 1
else _parent_hidden_context(segment_hidden)
)
summary_hidden[:, summary_index, :].copy_(segment_context)
summary_index += 1
returned_past = getattr(out, "past_key_values", None)
if tile_cache_required and returned_past is not None:
tile_past = returned_past
running_prefix = running_prefix + tile_new_positions
elif end != total_prefill_tokens:
raise RuntimeError(
"Resynthesis native 4M prefill lost KV cache before all tokens"
)
elif not tile_cache_required:
# A pre-existing multi-tile cache is passed into the final tile
# so attention remains exact. Some parent implementations return
# that object even with ``use_cache=False``; sever it explicitly
# after extracting hidden/logits so one training wave cannot
# retain parent KV/recurrent state into the next wave.
tile_past = None
setattr(out, "past_key_values", None)
else:
tile_past = None
if out is None:
raise RuntimeError("Resynthesis native prefill received an empty prompt")
if summary_hidden is None or summary_index < 1:
raise RuntimeError("Resynthesis native prefill produced no attended summaries")
return NativeTiledPrefill(
runtime_output=out,
summary_hidden=summary_hidden.narrow(1, 0, summary_index),
input_positions=active_input_ids.new_ones(
(), dtype=torch.long
).mul_(total_prefill_tokens),
)
def forward_hidden_logits(
self,
input_ids: torch.Tensor,
attention_mask: torch.Tensor | None = None,
) -> ResynthesisParentForward:
"""Execute one cache-retaining causal parent prefill or continuation."""
return self._forward_hidden_logits_impl(
input_ids,
attention_mask=attention_mask,
masked_training_prefill=False,
)
def forward_training_hidden_logits(
self,
input_ids: torch.Tensor,
*,
attention_mask: torch.Tensor,
) -> ResynthesisParentForward:
"""Execute one fresh masked training prefill with no final parent cache."""
return self._forward_hidden_logits_impl(
input_ids,
attention_mask=attention_mask,
masked_training_prefill=True,
)
def forward_training_hidden_logits_shared_prefix(
self,
packet: NativeSharedPrefixTrainingPacket,
) -> ResynthesisParentForward:
"""Run one packed batch from an immutable frozen-parent prefix cache.
Prefix construction enters only the frozen backbone. The integrated
parent RBO/Fabric therefore still executes exactly once, on the suffix
batch, matching an ordinary final-position training prefill while
avoiding one identical backbone prefix execution per row.
"""
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
prefix_ids = packet.prefix_ids.to(device=self.device, dtype=torch.long)
suffix_ids = packet.suffix_ids.to(device=self.device, dtype=torch.long)
suffix_mask = packet.suffix_mask.to(
device=self.device,
dtype=torch.long,
)
batch_indices_t = packet.batch_indices_t.to(
device=self.device,
dtype=torch.long,
)
if (
prefix_ids.ndim != 2
or prefix_ids.shape[0] != 1
or prefix_ids.shape[1] < 1
or suffix_ids.ndim != 2
or suffix_ids.shape[0] < 1
or suffix_ids.shape[1] < 1
or suffix_mask.shape != suffix_ids.shape
or batch_indices_t.shape != (suffix_ids.shape[0],)
):
raise RuntimeError("shared parent-prefix training geometry differs")
torch._assert_async(
suffix_mask.ge(0).logical_and(suffix_mask.le(1)).all(),
"shared parent-prefix suffix mask is not binary",
)
torch._assert_async(
suffix_mask[:, -1].eq(1).all(),
"shared parent-prefix suffix must end in a visible token",
)
if (
suffix_ids.shape[0] < 2
or prefix_ids.shape[1] + suffix_ids.shape[1]
> RESYNTHESIS_NATIVE_PREFILL_TILE_TOKENS
):
# A post-materialization CUDA replan may isolate one row, while a
# packed full-payload window may cross the native prefill tile.
# Neither condition invalidates the prompt. Reconstruct the exact
# target-free masked batch and use the ordinary tiled parent path;
# the live additive RBO/Fabric/expert/page graph still runs after
# this frozen-parent boundary. This is a semantic fallback, not a
# token cap: every visible suffix token remains in the forward.
prefix_batch_ids = prefix_ids.expand(suffix_ids.shape[0], -1)
full_ids = torch.cat((prefix_batch_ids, suffix_ids), dim=1)
full_mask = torch.cat(
(
torch.ones_like(prefix_batch_ids, dtype=torch.long),
suffix_mask,
),
dim=1,
)
return self.forward_training_hidden_logits(
full_ids,
attention_mask=full_mask,
)
if self._decode_past_key_values is not None:
raise RuntimeError(
"shared parent-prefix training requires a fresh decode arm"
)
torch._assert_async(
self._decode_cached_positions.eq(0),
"shared parent-prefix training requires a fresh decode arm",
)
backbone = getattr(runtime, "backbone", None)
if not isinstance(backbone, nn.Module) or getattr(
backbone,
"_resynthesis_final_hidden_only_forward_id",
"",
) != PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID:
raise RuntimeError(
"shared parent-prefix training requires the exact frozen backbone"
)
decoder_core = getattr(backbone, "model", None)
if not isinstance(decoder_core, nn.Module):
raise RuntimeError(
"shared parent-prefix training requires the frozen decoder core"
)
if not self._decode_authority_active:
begin_decode = getattr(runtime, "resynthesis_begin_authority_decode", None)
if callable(begin_decode):
authority_forward_id = begin_decode()
if not isinstance(authority_forward_id, torch.Tensor):
raise RuntimeError(
"Resynthesis authority transaction returned no tensor forward ID"
)
elif not self.exact_historical_source_loaded:
raise RuntimeError(
"Resynthesis integrated runtime lacks its authority transaction"
)
self._decode_authority_active = True
prefix_mask = torch.ones_like(prefix_ids, dtype=torch.long)
prefix_positions_t = (
prefix_mask.cumsum(dim=1).sub(1).clamp_min(0)
)
validate_native_context_admission(prefix_positions_t)
prefix_position_stack = build_long_context_position_stack(
prefix_positions_t
)
master_cache = _build_native_hybrid_context_cache(runtime)
prefix_count_t = prefix_ids.new_ones((), dtype=torch.long).mul_(
prefix_ids.shape[1]
)
with torch.no_grad():
# Enter the decoder core, not the conditional-generation wrapper.
# Its LM head owns additive experts and the embedded parent RBO;
# invoking that head here would execute RBO/Fabric once on the
# prefix and again on the suffix. The immutable prefix needs only
# the decoder's exact K/V and recurrent state.
prefix_output = decoder_core(
input_ids=prefix_ids,
position_ids=prefix_position_stack.rope_position_ids,
attention_mask=prefix_mask,
past_key_values=master_cache,
output_hidden_states=False,
return_dict=True,
use_cache=True,
)
returned_master = getattr(prefix_output, "past_key_values", None)
if (
returned_master is not master_cache
or getattr(
returned_master,
"_resynthesis_native_hybrid_context",
False,
)
is not True
):
raise RuntimeError(
"frozen backbone did not return its immutable hybrid prefix cache"
)
expanded_cache = _expand_immutable_native_hybrid_context_cache_boundary(
master_cache,
batch_indices_t,
)
setattr(prefix_output, "past_key_values", None)
prefix_batch_mask = prefix_mask.expand(suffix_ids.shape[0], -1)
full_input_positions_t = prefix_count_t + suffix_ids.new_ones(
(), dtype=torch.long
).mul_(suffix_ids.shape[1])
return self._forward_hidden_logits_impl(
suffix_ids,
attention_mask=suffix_mask,
masked_training_prefill=True,
shared_prefix_cache=expanded_cache,
shared_prefix_mask=prefix_batch_mask,
shared_full_input_positions_t=full_input_positions_t,
)
def frozen_backbone_position_policy_sha256_boundary(self) -> str:
"""Return the immutable decoder position/tile policy identity."""
return frozen_backbone_position_policy_sha256_boundary(
final_hidden_adapter_id=PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID,
dual_chunk_pretrain_length=DUAL_CHUNK_PRETRAIN_LENGTH,
dual_chunk_local_size=DUAL_CHUNK_LOCAL_SIZE,
pretrained_rope_band_tokens=PRETRAINED_ROPE_BAND_TOKENS,
prefill_tile_tokens=RESYNTHESIS_NATIVE_PREFILL_TILE_TOKENS,
prefill_summaries_per_tile=(
RESYNTHESIS_NATIVE_PREFILL_SUMMARIES_PER_TILE
),
)
def frozen_backbone_feature_dtype_boundary(self) -> torch.dtype:
"""Return the exact frozen decoder feature dtype before sidecar lookup.
A durable feature object is keyed before the expensive parent forward.
The dtype therefore has to come from the loaded decoder itself, not
from a host configuration guess. Captured features are authoritative
when this process has already run a prefill; otherwise the first
floating decoder parameter supplies the output dtype used by the
frozen final-hidden adapter.
"""
captured = self._last_frozen_backbone_final_hidden_t
if isinstance(captured, torch.Tensor):
return captured.dtype
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
backbone = getattr(runtime, "backbone", None)
decoder_core = getattr(backbone, "model", None)
if not isinstance(decoder_core, nn.Module):
raise RuntimeError(
"frozen-backbone feature dtype requires the frozen decoder core"
)
for parameter in decoder_core.parameters():
if parameter.is_floating_point():
return parameter.dtype
for buffer in decoder_core.buffers():
if buffer.is_floating_point():
return buffer.dtype
raise RuntimeError(
"frozen-backbone decoder has no floating feature dtype authority"
)
def frozen_backbone_cache_authority_boundary(
self,
*,
qualified_work_id: str,
prompt_sha256: str,
prompt_mask_sha256: str,
token_dtype: torch.dtype,
feature_dtype: torch.dtype,
summary_positions: int,
) -> FrozenBackboneCacheAuthority:
"""Bind one external packed row to this exact immutable parent."""
token_dtype_name = str(token_dtype).removeprefix("torch.")
feature_dtype_name = str(feature_dtype).removeprefix("torch.")
authority = FrozenBackboneCacheAuthority(
qualified_work_id=qualified_work_id,
prompt_sha256=prompt_sha256,
prompt_mask_sha256=prompt_mask_sha256,
parent_checkpoint_id=self.info.checkpoint_id,
parent_manifest_payload_sha256=(
self.info.manifest_payload_sha256
),
parent_model_artifact_sha256=self.info.model_artifact_sha256,
# Retained only as a direct-path hint for a historical source-bound
# sidecar. It is excluded from executable cache identity; a
# read-only normalized index finds older source observations.
parent_source_bundle_sha256=(
self.info.parent_source_bundle_sha256
),
position_policy_sha256=(
self.frozen_backbone_position_policy_sha256_boundary()
),
token_dtype=token_dtype_name,
feature_dtype=feature_dtype_name,
hidden_size=self.info.hidden_size,
summary_positions=summary_positions,
)
authority.record_boundary()
return authority
def precompute_frozen_backbone_prefill_boundary(
self,
input_ids: torch.Tensor,
*,
attention_mask: torch.Tensor,
authorities: tuple[FrozenBackboneCacheAuthority, ...],
) -> FrozenBackbonePrefillPacket:
"""Compute raw frozen-decoder features without entering live heads.
This is the one-shot packed-sidecar producer boundary. It deliberately
calls only the immutable decoder core: the conditional-generation
wrapper, additive head, historical RBO, Fabric, experts, page runtime,
answer targets, and task-intent targets are outside this interface.
The returned typed packet can therefore accelerate a later training
forward without caching any trainable or routing-owned result.
"""
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
if (
input_ids.ndim != 2
or input_ids.shape[0] < 1
or input_ids.shape[1] < 1
or attention_mask.shape != input_ids.shape
or len(authorities) != input_ids.shape[0]
):
raise ValueError(
"frozen-backbone precompute prompt geometry differs"
)
if self._decode_past_key_values is not None:
raise RuntimeError(
"frozen-backbone precompute requires a fresh decode arm"
)
active_input_ids = input_ids.to(
device=self.device,
dtype=torch.long,
)
active_attention_mask = attention_mask.to(
device=self.device,
dtype=torch.long,
)
torch._assert_async(
active_attention_mask.ge(0).logical_and(
active_attention_mask.le(1)
).all(),
"frozen-backbone precompute attention mask is not binary",
)
torch._assert_async(
active_attention_mask[:, -1].eq(1).all(),
"frozen-backbone precompute prompt must end in a visible token",
)
torch._assert_async(
self._decode_cached_positions.eq(0),
"frozen-backbone precompute requires a fresh decode arm",
)
backbone = getattr(runtime, "backbone", None)
if not isinstance(backbone, nn.Module) or getattr(
backbone,
"_resynthesis_final_hidden_only_forward_id",
"",
) != PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID:
raise RuntimeError(
"frozen-backbone precompute requires the exact parent adapter"
)
decoder_core = getattr(backbone, "model", None)
if not isinstance(decoder_core, nn.Module):
raise RuntimeError(
"frozen-backbone precompute requires the frozen decoder core"
)
absolute_positions = (
active_attention_mask.cumsum(dim=1).sub(1).clamp_min(0)
)
validate_native_context_admission(absolute_positions)
position_ids = build_long_context_position_stack(
absolute_positions
).rope_position_ids
total_prefill_tokens = active_input_ids.shape[1]
tile_tokens = min(
total_prefill_tokens,
RESYNTHESIS_NATIVE_PREFILL_TILE_TOKENS,
)
summary_positions = (
total_prefill_tokens + tile_tokens - 1
) // tile_tokens
feature_dtype = self.frozen_backbone_feature_dtype_boundary()
if any(
authority.parent_checkpoint_id != self.info.checkpoint_id
or authority.parent_manifest_payload_sha256
!= self.info.manifest_payload_sha256
or authority.parent_model_artifact_sha256
!= self.info.model_artifact_sha256
or authority.position_policy_sha256
!= self.frozen_backbone_position_policy_sha256_boundary()
or authority.token_dtype
!= str(input_ids.dtype).removeprefix("torch.")
or authority.feature_dtype
!= str(feature_dtype).removeprefix("torch.")
or authority.hidden_size != self.info.hidden_size
or authority.summary_positions != summary_positions
for authority in authorities
):
raise RuntimeError(
"frozen-backbone precompute authority differs from the parent"
)
tile_past: Any = None
if (
total_prefill_tokens
> RESYNTHESIS_NATIVE_HYBRID_ACTIVATION_TOKENS
):
custom_cache_builder = getattr(
runtime,
"resynthesis_build_native_hybrid_context_cache",
None,
)
if callable(custom_cache_builder):
tile_past = custom_cache_builder(
hot_window_tokens=active_input_ids.new_ones(
(),
dtype=torch.long,
).mul_(RESYNTHESIS_NATIVE_HOT_KV_TOKENS)
)
else:
tile_past = _build_native_hybrid_context_cache(runtime)
if not bool(
getattr(
tile_past,
"_resynthesis_native_hybrid_context",
False,
)
):
raise RuntimeError(
"frozen-backbone precompute hybrid cache is not native"
)
summary_hidden_t: torch.Tensor | None = None
final_hidden_t: torch.Tensor | None = None
summary_index = 0
with torch.no_grad():
for start in range(0, total_prefill_tokens, tile_tokens):
end = min(total_prefill_tokens, start + tile_tokens)
tile_cache_required = end != total_prefill_tokens
output = decoder_core(
input_ids=active_input_ids[:, start:end],
position_ids=position_ids[:, start:end],
attention_mask=active_attention_mask[:, :end],
past_key_values=tile_past,
output_hidden_states=False,
return_dict=True,
use_cache=tile_cache_required,
)
tile_hidden_t = getattr(
output,
"last_hidden_state",
None,
)
if (
not isinstance(tile_hidden_t, torch.Tensor)
or tile_hidden_t.ndim != 3
or tile_hidden_t.shape[0] != input_ids.shape[0]
or tile_hidden_t.shape[1] < 1
or tile_hidden_t.shape[2] != self.info.hidden_size
or tile_hidden_t.dtype != feature_dtype
):
raise RuntimeError(
"frozen-backbone decoder feature geometry differs"
)
# The installed parent adapter exposes the one logits-aligned
# final position from each tile. Selecting the same position
# here makes the offline packet byte-equivalent without
# invoking the additive LM head that records it online.
final_hidden_t = tile_hidden_t[:, -1:, :]
if summary_hidden_t is None:
summary_hidden_t = final_hidden_t.new_empty(
input_ids.shape[0],
summary_positions,
self.info.hidden_size,
)
summary_hidden_t[:, summary_index : summary_index + 1, :].copy_(
final_hidden_t
)
summary_index += 1
returned_past = getattr(output, "past_key_values", None)
if tile_cache_required and returned_past is not None:
tile_past = returned_past
elif tile_cache_required:
raise RuntimeError(
"frozen-backbone precompute lost its decoder cache"
)
else:
tile_past = None
setattr(output, "past_key_values", None)
if (
final_hidden_t is None
or summary_hidden_t is None
or summary_index != summary_positions
):
raise RuntimeError(
"frozen-backbone precompute produced incomplete features"
)
input_positions_t = active_input_ids.new_ones(
(input_ids.shape[0],),
dtype=torch.long,
).mul_(total_prefill_tokens)
row_packets = tuple(
FrozenBackbonePrefillPacket.from_features_boundary(
authority=authority,
final_hidden_t=final_hidden_t[row_index : row_index + 1],
summary_hidden_t=summary_hidden_t[
row_index : row_index + 1
],
input_positions_t=input_positions_t[
row_index : row_index + 1
],
)
for row_index, authority in enumerate(authorities)
)
return FrozenBackbonePrefillPacket.stack_boundary(row_packets)
def frozen_backbone_prefill_row_packet_boundary(
self,
*,
authority: FrozenBackboneCacheAuthority,
batch_index: int,
) -> FrozenBackbonePrefillPacket:
"""Select one just-computed raw decoder row for durable external I/O."""
final_hidden_t = self._last_frozen_backbone_final_hidden_t
summary_hidden_t = self._last_frozen_backbone_summary_hidden_t
input_positions_t = self._last_frozen_backbone_input_positions_t
if (
not isinstance(final_hidden_t, torch.Tensor)
or not isinstance(summary_hidden_t, torch.Tensor)
or not isinstance(input_positions_t, torch.Tensor)
):
raise RuntimeError(
"frozen-backbone row requested before one masked parent prefill"
)
if batch_index < 0 or batch_index >= final_hidden_t.shape[0]:
raise IndexError("frozen-backbone batch row is unavailable")
if (
authority.parent_checkpoint_id != self.info.checkpoint_id
or authority.parent_manifest_payload_sha256
!= self.info.manifest_payload_sha256
or authority.parent_model_artifact_sha256
!= self.info.model_artifact_sha256
or authority.position_policy_sha256
!= self.frozen_backbone_position_policy_sha256_boundary()
or authority.hidden_size != self.info.hidden_size
or authority.summary_positions != summary_hidden_t.shape[1]
or authority.feature_dtype
!= str(final_hidden_t.dtype).removeprefix("torch.")
):
raise RuntimeError(
"frozen-backbone row authority differs from the loaded parent"
)
row = slice(batch_index, batch_index + 1)
return FrozenBackbonePrefillPacket.from_features_boundary(
authority=authority,
final_hidden_t=final_hidden_t[row],
summary_hidden_t=summary_hidden_t[row],
input_positions_t=input_positions_t[row],
)
def forward_training_from_frozen_backbone_packet(
self,
input_ids: torch.Tensor,
*,
attention_mask: torch.Tensor,
packet: FrozenBackbonePrefillPacket,
) -> ResynthesisParentForward:
"""Replay decoder-only features through the complete live parent graph.
The decoder core is replaced for this one synchronous call only. The
surrounding conditional-generation wrapper, additive LM head,
historical RBO, and historical Fabric all execute normally for every
original prefill tile. This is deliberately narrower than replaying a
cached ``ResynthesisParentForward``, which would bypass those trained surfaces.
"""
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
packet.validate_boundary()
active_packet = packet.to_device_boundary(self.device)
if (
input_ids.ndim != 2
or input_ids.shape[1] < 1
or attention_mask.shape != input_ids.shape
or attention_mask.dtype != torch.bool
or active_packet.final_hidden_t.shape[0] != input_ids.shape[0]
or active_packet.final_hidden_t.shape[2] != self.info.hidden_size
):
raise RuntimeError(
"frozen-backbone replay prompt/feature geometry differs"
)
expected_summary_positions = (
input_ids.shape[1] + RESYNTHESIS_NATIVE_PREFILL_TILE_TOKENS - 1
) // RESYNTHESIS_NATIVE_PREFILL_TILE_TOKENS
if (
active_packet.summary_hidden_t.shape[1]
!= expected_summary_positions
):
raise RuntimeError(
"frozen-backbone replay summary/tile geometry differs"
)
expected_input_positions_t = attention_mask.sum(
dim=1,
dtype=torch.long,
)
torch._assert_async(
active_packet.input_positions_t.eq(
expected_input_positions_t
).all(),
"frozen-backbone replay input positions differ",
)
expected_left_padding_mask_t = torch.arange(
input_ids.shape[1],
device=attention_mask.device,
dtype=torch.long,
).unsqueeze(0).ge(
input_ids.shape[1] - expected_input_positions_t.unsqueeze(1)
)
torch._assert_async(
attention_mask.eq(expected_left_padding_mask_t).all(),
"frozen-backbone replay mask is not canonical left padding",
)
torch._assert_async(
input_ids.masked_select(~attention_mask).eq(0).all(),
"frozen-backbone replay padding tokens must be zero",
)
torch._assert_async(
active_packet.final_hidden_t.eq(
active_packet.summary_hidden_t[:, -1:, :]
).all(),
"frozen-backbone final hidden differs from its final tile summary",
)
backbone = getattr(runtime, "backbone", None)
if not isinstance(backbone, nn.Module) or getattr(
backbone,
"_resynthesis_final_hidden_only_forward_id",
"",
) != PARENT_FINAL_HIDDEN_ONLY_FORWARD_ID:
raise RuntimeError(
"frozen-backbone replay requires the exact parent adapter"
)
decoder_core = getattr(backbone, "model", None)
if not isinstance(decoder_core, nn.Module):
raise RuntimeError(
"frozen-backbone replay requires the frozen decoder core"
)
original_forward = decoder_core.forward
replay_call_index = 0
replay_cache = object()
def replay_decoder_forward(
*args: Any,
**kwargs: Any,
) -> _FrozenBackboneDecoderOutput:
nonlocal replay_call_index
input_value = kwargs.get("input_ids")
if input_value is None and args:
input_value = args[0]
if (
not isinstance(input_value, torch.Tensor)
or input_value.ndim != 2
or input_value.shape[0]
!= active_packet.final_hidden_t.shape[0]
or replay_call_index
>= active_packet.summary_hidden_t.shape[1]
):
raise RuntimeError(
"frozen-backbone decoder replay invocation differs"
)
hidden_t = active_packet.summary_hidden_t[
:,
replay_call_index : replay_call_index + 1,
:,
]
replay_call_index += 1
past_key_values = kwargs.get("past_key_values")
if kwargs.get("use_cache") is True and past_key_values is None:
past_key_values = replay_cache
return _FrozenBackboneDecoderOutput(
last_hidden_state=hidden_t,
past_key_values=past_key_values,
)
setattr(decoder_core, "forward", replay_decoder_forward)
try:
result = self._forward_hidden_logits_impl(
input_ids,
attention_mask=attention_mask,
masked_training_prefill=True,
)
finally:
setattr(decoder_core, "forward", original_forward)
if replay_call_index != active_packet.summary_hidden_t.shape[1]:
raise RuntimeError(
"frozen-backbone replay did not consume every sealed tile"
)
# The live tiled wrapper reports the padded batch width because every
# row shares its decoder call geometry. Durable sidecars retain the
# exact unpadded row positions, which are the prefill participation
# evidence consumed by the live RBO/Fabric graph. Preserve that vector
# after the decoder-only replay instead of manufacturing the wider
# cohort position for shorter rows.
return replace(
result,
parent_prefill_input_positions=(
active_packet.input_positions_t.detach()
),
)
def _forward_hidden_logits_impl(
self,
input_ids: torch.Tensor,
*,
attention_mask: torch.Tensor | None,
masked_training_prefill: bool,
shared_prefix_cache: object | None = None,
shared_prefix_mask: torch.Tensor | None = None,
shared_full_input_positions_t: torch.Tensor | None = None,
) -> ResynthesisParentForward:
"""Execute one causal parent prefill or native KV continuation.
A decode arm runs the complete prompt exactly once. Later emissions
enter the same integrated Resynthesis/RBO graph as one new token with
its native KV state. If the parent supplies no cache, this falls back
to complete-prefix execution without changing stop or route authority.
"""
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
self._last_frozen_backbone_final_hidden_t = None
self._last_frozen_backbone_summary_hidden_t = None
self._last_frozen_backbone_input_positions_t = None
if input_ids.ndim != 2 or input_ids.shape[1] < 1:
raise ValueError("Resynthesis parent input IDs must have shape [batch, sequence]")
active_input_ids = input_ids.to(device=self.device, dtype=torch.long)
explicit_attention_mask = attention_mask is not None
if attention_mask is None:
active_attention_mask = torch.ones(
input_ids.shape,
device=self.device,
dtype=torch.long,
)
else:
if attention_mask.shape != input_ids.shape:
raise ValueError("Resynthesis parent attention mask geometry differs")
active_attention_mask = attention_mask.to(
device=self.device,
dtype=torch.long,
)
torch._assert_async(
active_attention_mask.ge(0).logical_and(
active_attention_mask.le(1)
).all(),
"Resynthesis parent attention mask is not binary",
)
torch._assert_async(
active_attention_mask[:, -1].eq(1).all(),
"Resynthesis left-padded prompt must end in a visible token",
)
shared_prefix_active = shared_prefix_cache is not None
if shared_prefix_active != (
shared_prefix_mask is not None
and shared_full_input_positions_t is not None
):
raise RuntimeError("shared parent-prefix cache boundary is incomplete")
if shared_prefix_active and (
not masked_training_prefill
or not explicit_attention_mask
or shared_prefix_mask is None
or shared_prefix_mask.ndim != 2
or shared_prefix_mask.shape[0] != active_input_ids.shape[0]
or shared_prefix_mask.shape[1] < 1
or shared_prefix_mask.device != active_input_ids.device
or self._decode_past_key_values is not None
):
raise RuntimeError("shared parent-prefix continuation geometry differs")
use_past = (
shared_prefix_active
or self._decode_past_key_values is not None
)
if not self._decode_authority_active:
begin_decode = getattr(runtime, "resynthesis_begin_authority_decode", None)
if callable(begin_decode):
authority_forward_id = begin_decode()
if not isinstance(authority_forward_id, torch.Tensor):
raise RuntimeError(
"Resynthesis authority transaction returned no tensor forward ID"
)
elif not self.exact_historical_source_loaded:
raise RuntimeError(
"Resynthesis integrated runtime lacks its authority transaction"
)
self._decode_authority_active = True
if use_past:
if attention_mask is not None and not shared_prefix_active:
raise RuntimeError(
"explicit batched attention masks require a fresh decode arm"
)
if not shared_prefix_active:
active_input_ids = active_input_ids[:, -1:]
torch._assert_async(
self._decode_cached_positions.eq(input_ids.shape[1] - 1),
"Resynthesis KV continuation does not match the visible prefix",
)
prefix_positions = (
shared_prefix_mask.new_ones((), dtype=torch.long).mul_(
shared_prefix_mask.shape[1]
)
if shared_prefix_active and shared_prefix_mask is not None
else self._decode_cached_positions.to(
device=active_input_ids.device,
dtype=torch.long,
).clone()
)
runtime_new_positions = active_input_ids.new_ones(
(), dtype=torch.long
).mul_(active_input_ids.shape[1])
result_prefix_positions = (
prefix_positions.new_zeros(())
if shared_prefix_active
else prefix_positions
)
result_new_positions = (
shared_full_input_positions_t
if shared_prefix_active
and shared_full_input_positions_t is not None
else runtime_new_positions
)
record_kv = getattr(runtime, "resynthesis_record_kv_cache_reuse", None)
position_attention_mask = (
active_attention_mask
if shared_prefix_active
else active_attention_mask[:, -active_input_ids.shape[1] :]
if use_past
else active_attention_mask
)
absolute_positions = (
position_attention_mask.cumsum(dim=1)
.sub(1)
.clamp_min(0)
.add(prefix_positions.to(device=self.device))
)
validate_native_context_admission(absolute_positions)
# STACK+COMPOSE parent decode: absolute KV cache + Dual Chunk → parent RoPE.
# ``position_ids`` feed the parent's live rotary/YaRN; KV slots stay absolute.
# The full-prompt folded positions are computed once and then SLICED per
# prefill tile, so each tile sees the correct in-distribution RoPE phase
# for its absolute position (never re-folded per tile).
position_stack = build_long_context_position_stack(absolute_positions)
position_ids = position_stack.rope_position_ids
runtime_attention_mask = (
torch.cat(
(
shared_prefix_mask.to(dtype=active_attention_mask.dtype),
active_attention_mask,
),
dim=1,
)
if shared_prefix_active and shared_prefix_mask is not None
else active_attention_mask
)
prefill: NativeTiledPrefill | None = None
parent_outputs_consumed_by_autograd = torch.is_grad_enabled()
parent_forward_inference_boundary = torch.is_inference_mode_enabled()
# The parent is frozen. ``no_grad`` avoids retaining its activation
# tape while preserving ordinary tensor identity for historical
# recurrent/session buffers. ``inference_mode`` was marginally cheaper
# inside the parent, but forced a full module-buffer traversal plus
# output clones after every training wave.
with torch.no_grad():
if use_past:
# Decode continuation: one new token, one KV telemetry record.
if callable(record_kv):
record_kv(
prefix_positions=result_prefix_positions,
new_positions=result_new_positions,
)
elif not self.exact_historical_source_loaded:
raise RuntimeError(
"Resynthesis integrated runtime lacks tensor-native KV telemetry"
)
output = runtime(
input_ids=active_input_ids,
position_ids=position_ids,
attention_mask=runtime_attention_mask,
past_key_values=(
shared_prefix_cache
if shared_prefix_active
else self._decode_past_key_values
),
output_hidden_states=True,
return_dict=True,
use_cache=not shared_prefix_active,
logits_to_keep=1,
)
else:
# Native 4M+ tiled prefill: every token executes the parent.
# The trained linear-attention state remains global; the full-
# attention K/V becomes a bounded hot window only beyond the
# parent's pretrained band. No token is dropped or truncated.
transient_training_prefill = masked_training_prefill
if transient_training_prefill and not explicit_attention_mask:
raise RuntimeError(
"masked training prefill requires an explicit attention mask"
)
prefill_boundary = (
self._prefill_tiled_training_native
if transient_training_prefill
else self._prefill_tiled_native
)
prefill = prefill_boundary(
runtime=runtime,
active_input_ids=active_input_ids,
position_ids=position_ids,
attention_mask=runtime_attention_mask,
record_kv=record_kv,
starting_prefix=prefix_positions,
telemetry_required=not self.exact_historical_source_loaded,
)
output = prefill.runtime_output
# The external parent owns recurrent/session buffers that may be
# updated in its inference-mode forward. Normalize those buffers
# before the next RBO session reset, while the parent runtime is still
# attached and before any trainable graph consumes the result.
parent_rbo = getattr(runtime, "resynthesis_rbo", None)
if (
isinstance(parent_rbo, nn.Module)
and (
self._parent_session_may_hold_inference_tensors
or parent_forward_inference_boundary
)
):
normalized = self._normalize_inference_session_buffers(parent_rbo)
with torch.no_grad():
self._parent_inference_session_buffers_normalized.add_(
normalized.to(
device=self._parent_inference_session_buffers_normalized.device
)
)
# The traversal above is exhaustive over registered historical
# session buffers. Its completion proves ordinary tensor identity;
# extracting ``normalized`` as a Python scalar here only adds a
# host boundary to every inference-to-training transition.
self._parent_session_may_hold_inference_tensors = False
self._parent_session_buffers_verified_normal = True
returned_cache = getattr(output, "past_key_values", None)
if shared_prefix_active:
if shared_prefix_cache is None:
raise RuntimeError("shared parent-prefix cache was lost")
self._record_native_context_cache_telemetry_boundary(
shared_prefix_cache
)
setattr(output, "past_key_values", None)
self._decode_past_key_values = None
else:
self._decode_past_key_values = returned_cache
if self._decode_past_key_values is not None:
self._record_native_context_cache_telemetry_boundary(
self._decode_past_key_values
)
with torch.no_grad():
if self._decode_past_key_values is None:
self._decode_cached_positions.zero_()
else:
self._decode_cached_positions.add_(
runtime_new_positions.to(
device=self._decode_cached_positions.device
)
)
logits = getattr(output, "logits", None)
hidden_states = getattr(output, "hidden_states", None)
if not isinstance(logits, torch.Tensor) or not hidden_states:
raise RuntimeError(
"Resynthesis integrated forward returned no hidden/logit tensors"
)
parent_result = _resynthesis_parent_last_rbo_result(runtime)
shaped_hidden = getattr(parent_result, "shaped_hidden", None)
hidden = (
shaped_hidden
if isinstance(shaped_hidden, torch.Tensor)
else hidden_states[-1]
)
if hidden.shape[:-1] != logits.shape[:-1]:
raise RuntimeError(
"Resynthesis integrated hidden/logit geometry differs: "
f"hidden={tuple(hidden.shape)} logits={tuple(logits.shape)}"
)
parent_context_hidden = _parent_hidden_context(hidden)
if shared_prefix_active:
suffix_hidden = hidden_states[-1]
if (
not isinstance(suffix_hidden, torch.Tensor)
or suffix_hidden.ndim != 3
or suffix_hidden.shape[1] != 1
):
raise RuntimeError(
"shared parent-prefix final hidden geometry differs"
)
parent_prefill_hidden = suffix_hidden
assert shared_full_input_positions_t is not None
parent_prefill_input_positions = shared_full_input_positions_t
elif prefill is None:
parent_prefill_hidden = hidden.new_empty(
hidden.shape[0],
0,
hidden.shape[-1],
)
parent_prefill_input_positions = runtime_new_positions.new_zeros(())
else:
parent_prefill_hidden = prefill.summary_hidden.to(
device=hidden.device,
dtype=hidden.dtype,
)
parent_prefill_input_positions = prefill.input_positions.to(
device=hidden.device,
dtype=torch.long,
)
if masked_training_prefill and not use_past:
raw_final_hidden_t = hidden_states[-1]
if (
not isinstance(raw_final_hidden_t, torch.Tensor)
or raw_final_hidden_t.ndim != 3
or raw_final_hidden_t.shape[1] != 1
or parent_prefill_hidden.ndim != 3
or parent_prefill_hidden.shape[0]
!= raw_final_hidden_t.shape[0]
or parent_prefill_hidden.shape[2]
!= raw_final_hidden_t.shape[2]
):
raise RuntimeError(
"frozen-backbone captured feature geometry differs"
)
input_positions_t = parent_prefill_input_positions.reshape(-1)
if input_positions_t.numel() == 1:
input_positions_t = input_positions_t.expand(
raw_final_hidden_t.shape[0]
)
if input_positions_t.shape != (raw_final_hidden_t.shape[0],):
raise RuntimeError(
"frozen-backbone captured input positions differ"
)
self._last_frozen_backbone_final_hidden_t = (
raw_final_hidden_t[:, -1:, :].detach()
)
self._last_frozen_backbone_summary_hidden_t = (
parent_prefill_hidden.detach()
)
self._last_frozen_backbone_input_positions_t = (
input_positions_t.detach().clone()
)
# Resynthesis has already causally contextualized the complete prefill.
# The appended autoregressive RBO stack consumes the current position,
# just as it does for every cached continuation. This preserves the
# whole parent context without re-running four 4096-wide GRU/attention
# expert layers over historical positions on every next-token decision.
hidden = hidden[:, -1:, :]
logits = logits[:, -1:, :]
parent_rbo = getattr(runtime, "resynthesis_rbo", None)
expert_routes = getattr(parent_rbo, "_last_none_actual_expert_routes", None)
layer_routes = getattr(parent_rbo, "_last_none_actual_layer_routes", None)
if not isinstance(expert_routes, torch.Tensor):
expert_routes = hidden.new_empty(0)
if not isinstance(layer_routes, torch.Tensor):
layer_routes = hidden.new_empty(0)
result = ResynthesisParentForward(
hidden=(
_regularize_parent_tensor_for_autograd_boundary(hidden)
if parent_outputs_consumed_by_autograd
else hidden.detach()
),
logits=(
_regularize_parent_tensor_for_autograd_boundary(logits)
if parent_outputs_consumed_by_autograd
else logits.detach()
),
parent_context_hidden=(
_regularize_parent_tensor_for_autograd_boundary(
parent_context_hidden
)
if parent_outputs_consumed_by_autograd
else parent_context_hidden.detach()
),
parent_expert_routes=(
_regularize_parent_tensor_for_autograd_boundary(expert_routes)
if parent_outputs_consumed_by_autograd
else expert_routes.detach()
),
parent_layer_routes=(
_regularize_parent_tensor_for_autograd_boundary(layer_routes)
if parent_outputs_consumed_by_autograd
else layer_routes.detach()
),
kv_prefix_positions=(
_regularize_parent_tensor_for_autograd_boundary(
result_prefix_positions
)
if parent_outputs_consumed_by_autograd
else result_prefix_positions.detach()
),
kv_new_positions=(
_regularize_parent_tensor_for_autograd_boundary(
result_new_positions
)
if parent_outputs_consumed_by_autograd
else result_new_positions.detach()
),
parent_prefill_hidden=(
_regularize_parent_tensor_for_autograd_boundary(
parent_prefill_hidden
)
if parent_outputs_consumed_by_autograd
else parent_prefill_hidden.detach()
),
parent_prefill_input_positions=(
_regularize_parent_tensor_for_autograd_boundary(
parent_prefill_input_positions
)
if parent_outputs_consumed_by_autograd
else parent_prefill_input_positions.detach()
),
)
self._last_forward = result
return result
def begin_decode(self) -> None:
"""Reset frozen feature/KV plumbing without granting parent authority."""
self._decode_past_key_values = None
self._decode_authority_active = False
self._last_forward = None
with torch.no_grad():
self._decode_cached_positions.zero_()
self._native_context_hybrid_active.zero_()
self._native_context_total_positions.zero_()
self._native_context_hot_resident_positions.zero_()
self._native_context_hot_window_tokens.zero_()
self._native_context_recurrent_layer_count.zero_()
self._native_context_full_attention_layer_count.zero_()
@staticmethod
def _normalize_inference_session_buffers(parent_rbo: nn.Module) -> torch.Tensor:
"""Restore ordinary tensor identity at the inference/training boundary.
The verified historical parent predates its later recurrent-buffer
repair. An inference-mode decode can therefore replace a registered
session buffer with an inference tensor. Such a tensor cannot be reset
by the subsequent training transaction outside inference mode. This is
a caller-session compatibility boundary: it clones only registered
buffers that actually carry inference identity and leaves parameters,
trained values, routing, and immutable parent source untouched.
"""
normalized = torch.zeros((), dtype=torch.long)
with torch.inference_mode(False):
for module in parent_rbo.modules():
for name, buffer in module.named_buffers(recurse=False):
if buffer.is_inference():
setattr(module, name, buffer.detach().clone())
normalized.add_(torch.ones_like(normalized))
return normalized
def begin_session(self) -> None:
"""Reset caller-owned parent state without changing trained tensors."""
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
parent_rbo = getattr(runtime, "resynthesis_rbo", None)
reset_session = getattr(parent_rbo, "reset_session_state", None)
if not isinstance(parent_rbo, nn.Module) or not callable(reset_session):
raise RuntimeError("Resynthesis integrated RBO lacks caller-session reset")
inference_mode = torch.is_inference_mode_enabled()
if not inference_mode and (
self._parent_session_may_hold_inference_tensors
or not self._parent_session_buffers_verified_normal
):
normalized = self._normalize_inference_session_buffers(parent_rbo)
with torch.no_grad():
self._parent_inference_session_buffers_normalized.add_(
normalized.to(
device=self._parent_inference_session_buffers_normalized.device
)
)
self._parent_session_may_hold_inference_tensors = False
self._parent_session_buffers_verified_normal = True
reset_session()
if inference_mode:
self._parent_session_may_hold_inference_tensors = True
self._parent_session_buffers_verified_normal = False
self.begin_decode()
def session_transition_receipt_boundary(self) -> dict[str, object]:
"""Serialize inference-to-training compatibility only at log boundary."""
return {
"schema": "nnf.resynthesis.parent_session_transition.v1",
"normalizedInferenceSessionBuffers": int(
self._parent_inference_session_buffers_normalized.detach()
.to(device="cpu", dtype=torch.long)
.reshape(())
),
"parentSessionMayHoldInferenceTensors": (
self._parent_session_may_hold_inference_tensors
),
"parentSessionBuffersVerifiedNormal": (
self._parent_session_buffers_verified_normal
),
"trainedParametersChangedByTransition": False,
"immutableParentSourceChanged": False,
"baseForwardCacheOwner": "ResynthesisRBO",
}
def forward_hidden(self, input_ids: torch.Tensor) -> torch.Tensor:
"""Compatibility boundary for callers that only consume parent hidden."""
return self.forward_hidden_logits(input_ids).hidden
def forward_logits(self, hidden: torch.Tensor) -> torch.Tensor:
"""Project through Resynthesis's frozen native RBO-owned generation head.
Parent parameters remain frozen, while autograd is retained with respect
to ``hidden`` so the appended Resynthesis experts receive real CE signal.
"""
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
head = getattr(getattr(runtime, "backbone", None), "lm_head", None)
if not isinstance(head, nn.Module):
raise RuntimeError("Resynthesis integrated runtime has no native generation head")
logits = head(hidden)
if not isinstance(logits, torch.Tensor):
raise RuntimeError(
"Resynthesis native generation head returned a non-tensor value"
)
return logits
def forward_low_rank_logits_projection(
self,
hidden_projection: torch.Tensor,
) -> torch.Tensor:
"""Compose the frozen native head with a trainable hidden projection.
For ``U: [hidden, rank]`` this returns ``W_head @ U`` in FP32. The
full-vocabulary result and gradient are exact; only the associative
order of the two linear projections changes. The detached forward value
is reused across waves until the optimizer mutates ``U``. Each wave
attaches an exact tiled ``W_head.T @ grad`` backward, so reuse never
severs the trainable correction path.
"""
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
head = getattr(getattr(runtime, "backbone", None), "lm_head", None)
native_rbo = getattr(head, "_resynthesis_rbo", None)
frozen_weight = getattr(native_rbo, "_frozen_lm_weight", None)
if (
not isinstance(head, nn.Module)
or getattr(head, "training_rbo_active", False) is not True
or not isinstance(frozen_weight, torch.Tensor)
):
raise RuntimeError(
"Resynthesis native linear head is unavailable for low-rank completion"
)
if (
hidden_projection.ndim != 2
or hidden_projection.shape[0] != frozen_weight.shape[1]
or hidden_projection.device != frozen_weight.device
):
raise ValueError("low-rank completion projection geometry differs")
source_id = id(hidden_projection)
source_version = hidden_projection._version
projection = self._training_low_rank_projection_cache
if (
projection is None
or self._training_low_rank_projection_source_id != source_id
or self._training_low_rank_projection_source_version != source_version
or projection.device != hidden_projection.device
or projection.shape
!= (frozen_weight.shape[0], hidden_projection.shape[1])
):
projection = hidden_projection.new_empty(
(frozen_weight.shape[0], hidden_projection.shape[1]),
dtype=torch.float32,
)
projection_fp32 = hidden_projection.detach().float()
with torch.no_grad():
for start in range(
0,
frozen_weight.shape[0],
_FROZEN_HEAD_PROJECTION_TILE_ROWS,
):
end = min(
start + _FROZEN_HEAD_PROJECTION_TILE_ROWS,
frozen_weight.shape[0],
)
projection[start:end] = torch.mm(
frozen_weight[start:end].float(),
projection_fp32,
)
self._training_low_rank_projection_cache = projection
self._training_low_rank_projection_source_id = source_id
self._training_low_rank_projection_source_version = source_version
return cast(
torch.Tensor,
_CachedFrozenHeadLowRankProjection.apply( # type: ignore[no-untyped-call]
hidden_projection,
frozen_weight,
projection,
),
)
def native_decode_stop(
self,
hidden: torch.Tensor,
logits: torch.Tensor,
generated_ids: torch.Tensor,
) -> ResynthesisNativeDecodeStop:
"""Observe the exact parent's legacy completion surface diagnostically.
Only the active final hidden/logit position is scored. ``generated_ids``
contains model-emitted continuation tokens, never the immutable prompt.
No EOS, host token count, or RBO traversal heuristic participates. The
returned tensors have no answer, stop, retention, or veto authority;
the additive Resynthesis completion graph owns those decisions.
"""
if not self._weights_loaded:
self.load_weights()
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
surface = getattr(runtime, "native_decode_confidence", None)
if not isinstance(surface, nn.Module):
raise RuntimeError(
"Resynthesis parent has no trained native decode-confidence surface"
)
if (
hidden.ndim != 3
or logits.ndim != 3
or hidden.shape[:2] != logits.shape[:2]
or generated_ids.ndim != 2
or hidden.shape[0] != generated_ids.shape[0]
or generated_ids.shape[1] < 1
):
raise RuntimeError("Resynthesis native decode-confidence input geometry differs")
with torch.no_grad():
raw_score = surface(
hidden=hidden[:, -1:, :],
logits=logits[:, -1:, :],
generated_ids=generated_ids,
)
if not isinstance(raw_score, torch.Tensor):
raise RuntimeError(
"Resynthesis native decode-confidence surface returned no tensor"
)
score = raw_score.reshape(hidden.shape[0], -1)[:, -1]
probability = score.sigmoid()
decision = probability.ge(0.5)
return ResynthesisNativeDecodeStop(
score=score,
probability=probability,
decision=decision,
)
def apply_native_answer_surface(
self,
hidden: torch.Tensor,
logits: torch.Tensor,
) -> ResynthesisNativeAnswer:
"""Encode additive logits with the parent's immutable vocabulary map.
``hidden`` is accepted only to preserve the tensor-native historical
interface. It cannot enter answer selection. In particular, this
boundary deliberately does not call the frozen parent's active RBO or
answer head: Resynthesis has already produced the authoritative logits,
and the parent supplies only token-to-bit/glyph vocabulary plumbing.
"""
del hidden
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
vge = getattr(runtime, "resynthesis_vge", None)
token_to_glyph = getattr(vge, "token_ids_to_glyph", None)
token_to_bits = getattr(vge, "token_ids_to_bit_ids", None)
if not callable(token_to_glyph) or not callable(token_to_bits):
raise RuntimeError("frozen parent VGE lacks its immutable bit mapping")
if logits.ndim != 3 or logits.shape[1] < 1:
raise RuntimeError("additive vocabulary logits geometry differs")
token_ids = logits[:, -1:, :].argmax(dim=-1)
glyph = token_to_glyph(token_ids)
bit_ids = token_to_bits(token_ids)
if not all(
isinstance(value, torch.Tensor)
for value in (token_ids, glyph, bit_ids)
):
raise RuntimeError("frozen parent VGE returned a non-tensor packet")
return ResynthesisNativeAnswer(
logits=logits,
token_ids=token_ids,
bit_ids=bit_ids,
glyph=glyph,
)
def native_token_glyphs_loss_boundary(
self,
token_ids_t: torch.Tensor,
) -> torch.Tensor:
"""Map token identities through immutable vocabulary plumbing only.
Object-native knowledge absorption already owns the verified token
identities at its explicit loss boundary. Re-running the frozen 12B
decoder merely to recover their vocabulary coordinates would make that
historical parent the training bottleneck again. This boundary calls
only the parent's immutable VGE lookup: it performs no parent forward,
routing, answer selection, teacher projection, or parameter update.
The same interface maps target-free context IDs and verified value IDs;
callers remain responsible for keeping value glyphs on the loss side
so ground-truth-derived tensors never enter ``forward_thinking``.
"""
if (
token_ids_t.ndim < 1
or token_ids_t.dtype not in (torch.int32, torch.int64)
):
raise ValueError(
"native vocabulary glyph lookup requires integer token tensors"
)
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
vge = getattr(runtime, "resynthesis_vge", None)
token_to_glyph = getattr(vge, "token_ids_to_glyph", None)
if not callable(token_to_glyph):
raise RuntimeError(
"frozen parent VGE lacks its immutable glyph mapping"
)
glyph_t = token_to_glyph(token_ids_t)
if (
not isinstance(glyph_t, torch.Tensor)
or glyph_t.ndim != token_ids_t.ndim + 1
or glyph_t.shape[:-1] != token_ids_t.shape
or glyph_t.shape[-1] < 1
or not glyph_t.is_floating_point()
or glyph_t.device != token_ids_t.device
):
raise RuntimeError(
"frozen parent VGE returned an invalid glyph tensor"
)
torch._assert_async(
torch.isfinite(glyph_t).all(),
"frozen parent VGE returned non-finite glyph coordinates",
)
return glyph_t
def apply_execution_outcome(
self,
outcome_features: torch.Tensor,
) -> ResynthesisOutcomeApplication:
"""Apply one persisted verifier/tool outcome to the exact parent route.
The eight Resynthesis fields are observations only. They are translated
to Resynthesis's fixed execution-memory geometry without fabricating unknown
code-specific evidence such as patch application or timeout status.
"""
if outcome_features.shape != (1, 8):
raise ValueError("one parent execution outcome must have shape [1, 8]")
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
apply_outcome = getattr(
runtime,
"resynthesis_apply_current_turn_execution_outcome",
None,
)
observed = outcome_features.detach().to(device=self.device, dtype=torch.float32)
passed = observed[0, 0].clamp(0.0, 1.0)
failed = observed[0, 1].clamp(0.0, 1.0)
score = observed[0, 2].clamp(0.0, 1.0)
coverage = observed[0, 3].clamp(0.0, 1.0)
verified = observed[0, 4].clamp(0.0, 1.0)
infrastructure_failure = observed[0, 6].clamp(0.0, 1.0)
zero = observed.new_zeros(())
observation = torch.stack(
(
zero,
verified,
passed,
torch.maximum(failed, infrastructure_failure),
zero,
failed * verified,
zero,
zero,
score,
coverage,
)
)
acquisition = torch.stack(
(
failed * verified,
zero,
zero,
passed * verified,
)
)
if not callable(apply_outcome):
if not self.exact_historical_source_loaded:
raise RuntimeError(
"Resynthesis integrated runtime lacks its trained outcome boundary"
)
parent_rbo = getattr(runtime, "resynthesis_rbo", None)
capture = getattr(parent_rbo, "capture_session_state", None)
apply_historical = getattr(
parent_rbo,
"apply_execution_observation_from_boundary",
None,
)
if not callable(capture) or not callable(apply_historical):
raise RuntimeError(
"historical Resynthesis RBO lacks outcome-memory boundaries"
)
parent_result = _resynthesis_parent_last_rbo_result(runtime)
domain_idx = int(getattr(parent_result, "domain_idx", 0))
subdomain_idx = int(getattr(parent_result, "subdomain_idx", 0))
before = capture()
apply_historical(
observation,
domain_idx=domain_idx,
subdomain_idx=subdomain_idx,
resolved=bool(passed.eq(1.0).detach().to(device="cpu")),
)
after = capture()
before_values = vars(before)
after_values = vars(after)
if set(before_values) != set(after_values):
raise RuntimeError("historical Resynthesis outcome-state geometry changed")
squared = observation.new_zeros((), dtype=torch.float32)
for name in sorted(before_values):
before_value = before_values[name]
after_value = after_values[name]
if isinstance(before_value, torch.Tensor):
if not isinstance(after_value, torch.Tensor) or (
before_value.shape != after_value.shape
):
raise RuntimeError(
"historical Resynthesis outcome-state tensor geometry differs"
)
delta = after_value.detach().to(
device=observation.device,
dtype=torch.float32,
) - before_value.detach().to(
device=observation.device,
dtype=torch.float32,
)
squared = squared + delta.square().sum()
rbo_delta = squared.sqrt()
route_changed = rbo_delta.gt(0)
if not bool(route_changed.detach().to(device="cpu")):
raise RuntimeError(
"persisted outcome did not change historical RBO state"
)
zero_delta = rbo_delta.new_zeros(())
return ResynthesisOutcomeApplication(
applied=route_changed,
rbo_state_delta_l2=rbo_delta,
arm_state_delta_l1=zero_delta,
legacy_state_delta_l2=zero_delta,
route_state_changed=route_changed,
)
packet = apply_outcome(
observation,
acquisition=acquisition,
resolved=passed.eq(1.0),
)
packet_applied = getattr(packet, "applied", None)
packet_rbo_delta = getattr(packet, "rbo_state_delta_l2", None)
packet_arm_delta = getattr(packet, "arm_state_delta_l1", None)
packet_legacy_delta = getattr(packet, "legacy_state_delta_l2", None)
packet_route_changed = getattr(packet, "route_state_changed", None)
if not all(
isinstance(value, torch.Tensor)
for value in (
packet_applied,
packet_rbo_delta,
packet_arm_delta,
packet_legacy_delta,
packet_route_changed,
)
):
raise RuntimeError(
"Resynthesis outcome boundary returned an invalid tensor packet"
)
assert isinstance(packet_applied, torch.Tensor)
assert isinstance(packet_rbo_delta, torch.Tensor)
assert isinstance(packet_arm_delta, torch.Tensor)
assert isinstance(packet_legacy_delta, torch.Tensor)
assert isinstance(packet_route_changed, torch.Tensor)
return ResynthesisOutcomeApplication(
applied=packet_applied,
rbo_state_delta_l2=packet_rbo_delta,
arm_state_delta_l1=packet_arm_delta,
legacy_state_delta_l2=packet_legacy_delta,
route_state_changed=packet_route_changed,
)
def current_acquisition_policy(self) -> ResynthesisAcquisitionPolicy:
"""Read the trained parent action after a real outcome was ingested."""
runtime = self.runtime
if runtime is None:
raise RuntimeError("Resynthesis integrated runtime was not attached")
active_rbo_fn = getattr(runtime, "_active_resynthesis_rbo", None)
if not callable(active_rbo_fn):
raise RuntimeError("Resynthesis integrated runtime has no active RBO boundary")
active_rbo = active_rbo_fn(required=True)
execution_grounding = getattr(active_rbo, "execution_grounding", None)
policy_fn = getattr(execution_grounding, "acquisition_policy", None)
authority = getattr(execution_grounding, "acquisition_policy_authority", None)
if not callable(policy_fn) or not isinstance(authority, torch.Tensor):
raise RuntimeError("Resynthesis RBO has no trained evidence-acquisition policy")
policy = policy_fn(device=self.device, dtype=torch.float32)
action_probs = getattr(policy, "action_probs", None)
action_index = getattr(policy, "action_index", None)
confidence = getattr(policy, "confidence", None)
observation_count = getattr(policy, "observation_count", None)
acquisition_count = getattr(policy, "acquisition_count", None)
values = (
action_probs,
action_index,
confidence,
observation_count,
acquisition_count,
)
if not all(isinstance(value, torch.Tensor) for value in values):
raise RuntimeError(
"Resynthesis acquisition policy returned an invalid tensor packet"
)
assert isinstance(action_probs, torch.Tensor)
assert isinstance(action_index, torch.Tensor)
assert isinstance(confidence, torch.Tensor)
assert isinstance(observation_count, torch.Tensor)
assert isinstance(acquisition_count, torch.Tensor)
if action_probs.shape != (4,):
raise RuntimeError("Resynthesis acquisition action geometry differs")
return ResynthesisAcquisitionPolicy(
action_probs=action_probs.detach(),
action_index=action_index.detach().reshape(()),
confidence=confidence.detach().reshape(()),
observation_count=observation_count.detach().reshape(()),
acquisition_count=acquisition_count.detach().reshape(()),
authority=authority.detach().reshape(()),
)
def freeze(self) -> "ResynthesisNativeParent":
"""Ensure all base parameters are frozen (requires_grad=False)."""
for p in self.parameters():
p.requires_grad_(False)
for b in self.buffers():
b.requires_grad_(False)
return self
# Historical names remain import-compatible, but all factories construct the
# Resynthesis-native owner. They are aliases only and never redirect loading.
FrozenResynthesisParent = ResynthesisNativeParent
FrozenNexumBase = ResynthesisNativeParent
def build_frozen_base(
cfg: ResynthesisConfig | None = None,
*,
device: torch.device | str = "cpu",
lazy: bool = True,
) -> ResynthesisNativeParent:
"""Factory: build the frozen Resynthesis native graph parent.
Args:
cfg: Resynthesis config (defaults to ResynthesisConfig()).
device: torch device.
lazy: if True, weights are loaded on first forward_hidden() call.
if False, weights are loaded immediately.
"""
cfg = cfg or ResynthesisConfig()
base = ResynthesisNativeParent(cfg, device=device)
if not lazy:
base.load_weights()
base.freeze()
return base
|