File size: 303,301 Bytes
52da7b7 | 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 | import json
import hashlib
import random
import site
import string
import sys
import unicodedata
from dataclasses import dataclass, field
from pathlib import Path
from typing import Sequence
_VENDOR_ROOT = Path(__file__).resolve().parent.parent / ".vendor"
for _vendor_path in (_VENDOR_ROOT / "python", _VENDOR_ROOT / "sitepkgs"):
if _vendor_path.exists():
vendor_text = str(_vendor_path)
if vendor_text not in sys.path:
sys.path.insert(0, vendor_text)
try:
import numpy as np
except ModuleNotFoundError:
user_site = site.getusersitepackages()
if user_site and user_site not in sys.path:
sys.path.append(user_site)
try:
import numpy as np
except ModuleNotFoundError:
np = None
if np is not None and not hasattr(np, "asarray"):
np = None
from .checkpoint import read_safetensor_file, write_safetensor_file
from .config import ReframrConfig
from .embeddings import EmbeddingModel, fit_ppmi_embedding_from_tokens
from .hippo import AnalyticalMemoryUnit, analytical_embedding_drive, analytical_embedding_drive_fast
from .linalg import Vector, dot, mean, norm, softmax, zeros_vector
from .reservoir import apply_readout, ridge_regression_readout
from .reasoning import TOOL_PROTOCOL_TOKENS, reasoning_prefix
from .sparse_context import HashedSparseAttention
from .ternary import apply_ternary_mask, derive_ternary_mask_from_states
from .tokenizer import NativeTokenizer
ASSOCIATIVE_BLEND = 0.42
TRANSITION_BLEND = 0.08
COPY_BLEND = 0.04
BASE_BLEND = 0.34
FAST_ASSOCIATIVE_BLEND = 0.06
FAST_TRANSITION_BLEND = 0.14
FAST_COPY_BLEND = 0.12
FAST_BASE_BLEND = 0.72
FAST_PREFERENCE_BLEND = 0.15
FAST_ANSWER_BLEND = 0.16
FAST_SOURCE_EVIDENCE_BLEND = 0.52
PROMPT_READOUT_LOGIT_ZSCORE_SCALE = 0.48
PROMPT_START_READOUT_CONFIDENCE_FLOOR = 0.45
ASSOCIATIVE_TOP_K = 12
ANSWER_TOP_K = 48
ANSWER_START_TOP_K = 32
MIN_COMPLETE_ANSWER_WORDS = 6
MIN_COMPLETE_MULTI_SENTENCE_WORDS = 4
ANSWER_SEQUENCE_MATCH_FLOOR = 0.27
ANSWER_START_CONFIDENCE_FLOOR = 0.45
ANSWER_START_MATCH_SUPPORT_FLOOR = 0.18
ANSWER_SEQUENCE_DISTRIBUTED_LOCK_FLOOR = 0.45
ANSWER_SEQUENCE_LOCK_FLOOR = 0.55
ANSWER_SEQUENCE_SPIKE_CONFIDENCE = 0.80
READOUT_LOGIT_ZSCORE_SCALE = 0.22
TRACE_IDENTITY_SCALE = 0.78
TRACE_IDENTITY_HASHES = (
(1103515245, 12345, 214013, 2531011),
(1664525, 1013904223, 22695477, 1),
(69069, 362437, 134775813, 17),
(134775813, 97, 1103515245, 31),
(22695477, 911, 1664525, 73),
(214013, 2531011, 69069, 19),
(48271, 0, 69621, 11),
(16807, 37, 40692, 101),
(279470273, 173, 1299709, 53),
(39916801, 29, 2147483629, 7),
)
PROMPT_ENVELOPE_TERMS = frozenset(
{"system", "instruction", "user", "human", "assistant", "question", "answer"}
)
NGRAM_KEY_SEPARATOR = "\u0001"
TRANSITION_ORDERS = (10, 8, 6, 5, 4, 3, 2, 1)
DEFAULT_GENERATION_TEMPERATURE = 0.82
DEFAULT_GENERATION_TOP_K = 24
DEFAULT_GENERATION_TOP_P = 0.92
DEFAULT_REPETITION_PENALTY = 1.18
ANSWER_SEQUENCE_MAX_TOKENS = 192
ANSWER_SEQUENCE_EAGER_OVERLAP_CACHE_LIMIT = 8192
ANSWER_SEQUENCE_VARIATION_TEMPERATURE = 0.65
ANSWER_SEQUENCE_VARIATION_MATCH_LIMIT = 4
ANSWER_SEQUENCE_CREATIVE_TEMPERATURE = 1.10
ANSWER_REPLAY_PREFIX_TEMPERATURE = 0.95
ANSWER_REPLAY_PREFIX_MIN_TOKENS = 64
ANSWER_REPLAY_PREFIX_PENALTY = 0.18
CREATIVE_EARLY_POOL_TEMPERATURE = 1.05
CREATIVE_EARLY_POOL_WORD_LIMIT = 6
CREATIVE_EARLY_POOL_MAX = 8
TOOL_CALL_CONTEXT_TERMS = frozenset(
{
"current",
"latest",
"today",
"yesterday",
"tonight",
"now",
"fresh",
"recent",
"web",
"search",
"real-time",
"price",
"weather",
"election",
"news",
"official",
"result",
"live",
}
)
RUNTIME_GENERATION_HISTORY_LIMIT = 8
AVOID_SEQUENCE_MIN_TOKENS = 6
WORD_COMPLETION_OVERFLOW_TOKENS = 16
ANSWER_FINGERPRINT_WORDS = 4
SPARSE_CONTEXT_MIN_TOKENS = 16
SPARSE_CONTEXT_TOP_K = 64
SPARSE_CONTEXT_HASH_BITS = 12
SPARSE_CONTEXT_PROBE_RADIUS = 1
SPARSE_CONTEXT_CANDIDATE_MULTIPLIER = 16
SPARSE_CONTEXT_TRACE_BLEND = 0.35
RUNTIME_ARRAY_DTYPE = np.float32 if np is not None else None
@dataclass(frozen=True, slots=True)
class CharacterCountFact:
character: str
word: str
count: int
surface_seed: int
focused: bool
@dataclass(frozen=True, slots=True)
class GenerationTokenMeta:
rendered: str
stripped: str
starts_new_word: bool
punctuation_piece: bool
structural_punctuation: bool
structural_symbol: bool
word_joiner: bool
alphanumeric: str
common_connector: bool
def _normalize_vector(values: Vector) -> Vector:
total = sum(values)
if total <= 0.0:
return [0.0 for _ in values]
return [value / total for value in values]
def _encode_ngram_key(tokens: tuple[str, ...]) -> str:
return NGRAM_KEY_SEPARATOR.join(tokens)
def _decode_ngram_key(key: str) -> tuple[str, ...]:
return tuple(part for part in key.split(NGRAM_KEY_SEPARATOR) if part)
def _last_index(values: list[str], target: str) -> int | None:
for index in range(len(values) - 1, -1, -1):
if values[index] == target:
return index
return None
def _first_index(values: list[str], target: str) -> int | None:
for index, value in enumerate(values):
if value == target:
return index
return None
@dataclass(slots=True)
class DecodeState:
hidden_states: list[Vector]
context_traces: list[Vector]
combined_state: Vector
context_tokens: list[str]
answer_anchor_state: Vector | None = None
answer_matches: list[tuple[float, int, int]] | None = None
answer_start_matches: list[tuple[float, int, int]] | None = None
answer_sequence_matches: list[tuple[float, int, int]] | None = None
prompt_answer_prior: object | None = None
prompt_answer_start_prior: object | None = None
@dataclass(slots=True)
class ReframrModel:
config: ReframrConfig
tokenizer: NativeTokenizer | None = None
embedding_model: EmbeddingModel | None = None
memory_units: list[AnalyticalMemoryUnit] | None = None
ternary_scale: float = 1.0
ternary_mask: list[int] | None = None
ternary_mask_array: object | None = None
readout_weights: list[list[float]] | None = None
readout_weights_array: object | None = None
readout_bias: Vector | None = None
readout_bias_array: object | None = None
prompt_answer_weights: list[list[float]] | None = None
prompt_answer_weights_array: object | None = None
prompt_answer_bias: Vector | None = None
prompt_answer_bias_array: object | None = None
prompt_answer_start_weights: list[list[float]] | None = None
prompt_answer_start_weights_array: object | None = None
prompt_answer_start_bias: Vector | None = None
prompt_answer_start_bias_array: object | None = None
trace_token_weights: Vector | None = None
trace_token_weights_array: object | None = None
trace_embedding_table_array: object | None = None
preference_bias: Vector | None = None
preference_bias_array: object | None = None
preference_valid_mask_array: object | None = None
state_offset: Vector | None = None
state_offset_array: object | None = None
associative_keys: list[Vector] | None = None
associative_keys_array: object | None = None
associative_key_norms: list[float] | None = None
associative_key_norms_array: object | None = None
associative_values: list[int] | None = None
associative_values_array: object | None = None
associative_valid_mask_array: object | None = None
answer_keys: list[Vector] | None = None
answer_keys_array: object | None = None
answer_key_norms: list[float] | None = None
answer_key_norms_array: object | None = None
answer_similarity_keys_array: object | None = None
answer_similarity_key_norms_array: object | None = None
answer_similarity_mask_array: object | None = None
answer_values: list[int] | None = None
answer_values_array: object | None = None
answer_valid_mask_array: object | None = None
answer_start_keys: list[Vector] | None = None
answer_start_keys_array: object | None = None
answer_start_key_norms: list[float] | None = None
answer_start_key_norms_array: object | None = None
answer_start_similarity_keys_array: object | None = None
answer_start_similarity_key_norms_array: object | None = None
answer_start_values: list[int] | None = None
answer_start_values_array: object | None = None
answer_start_valid_mask_array: object | None = None
answer_sequence_keys: list[Vector] | None = None
answer_sequence_keys_array: object | None = None
answer_sequence_key_norms: list[float] | None = None
answer_sequence_key_norms_array: object | None = None
answer_sequence_similarity_keys_array: object | None = None
answer_sequence_similarity_key_norms_array: object | None = None
answer_sequence_prompt_tokens: list[list[int]] | None = None
answer_sequence_prompt_tokens_array: object | None = None
answer_sequence_tokens: list[list[int]] | None = None
answer_sequence_tokens_array: object | None = None
answer_sequence_token_id_rows: list[list[int]] | None = None
answer_sequence_prompt_weight_maps: list[dict[int, float]] | None = None
answer_sequence_prompt_weight_norms: list[float] | None = None
answer_sequence_prompt_bigram_sets: list[set[tuple[int, int]]] | None = None
answer_sequence_prompt_trigram_sets: list[set[tuple[int, int, int]]] | None = None
answer_sequence_prompt_number_sets: list[set[str]] | None = None
answer_sequence_prompt_inverted_index: dict[int, list[int]] | None = None
answer_sequence_prompt_specificity: dict[int, float] | None = None
prompt_overlap_valid_token_mask_array: object | None = None
answer_fingerprint_hashes: set[tuple[int, ...]] | None = None
answer_fingerprint_token_lengths: set[int] | None = None
answer_fingerprint_token_sequences_by_length: dict[int, set[tuple[int, ...]]] | None = None
answer_sequence_prefixes_by_length: dict[int, set[tuple[int, ...]]] | None = None
transition_tables: dict[int, dict[tuple[str, ...], dict[str, float]]] | None = None
transition_id_tables: dict[int, dict[tuple[int, ...], tuple[object, object]]] | None = None
transition_tensor_cache: dict[str, object] | None = None
transition_built_orders: set[int] | None = None
generation_token_meta_cache: dict[str, GenerationTokenMeta] | None = None
runtime_generation_history: dict[str, list[str]] = field(default_factory=dict, repr=False)
def fit(self, text: str) -> "ReframrModel":
self.generation_token_meta_cache = None
self.answer_sequence_prefixes_by_length = None
self.tokenizer = NativeTokenizer.train(
text,
vocab_size=self.config.tokenizer_vocab_size,
min_pair_frequency=self.config.tokenizer_min_pair_frequency,
lowercase=self.config.lowercase,
)
tokens = self.tokenizer.encode(text)
if len(tokens) < 2:
raise ValueError("REFRAMR needs at least two tokens to derive a next-token readout.")
self.embedding_model = fit_ppmi_embedding_from_tokens(
tokens,
embedding_dim=self.config.embedding_dim,
window_size=self.config.window_size,
min_frequency=self.config.min_frequency,
max_vocab=self.config.max_vocab,
required_tokens=self.tokenizer.vocab,
)
self.memory_units = [
AnalyticalMemoryUnit(self.config.state_dim, timescale)
for timescale in self.config.timescales
]
token_counts: dict[str, float] = {}
for token in tokens:
token_counts[token] = token_counts.get(token, 0.0) + 1.0
self.trace_token_weights = self._derive_trace_token_weights_from_counts(token_counts)
raw_states, targets, target_ids = self._collect_training_examples(tokens)
self.ternary_scale, self.ternary_mask = derive_ternary_mask_from_states(raw_states)
analytical_states = [
apply_ternary_mask(state, self.ternary_mask, self.ternary_scale)
for state in raw_states
]
self.associative_keys = [state[:] for state in analytical_states]
self.associative_key_norms = [norm(state) for state in analytical_states]
self.associative_values = target_ids[:]
self.answer_keys = []
self.answer_key_norms = []
self.answer_values = []
self.answer_start_keys = []
self.answer_start_key_norms = []
self.answer_start_values = []
self.answer_sequence_keys = []
self.answer_sequence_key_norms = []
self.answer_sequence_prompt_tokens = []
self.answer_sequence_tokens = []
self.prompt_answer_weights = []
self.prompt_answer_bias = [0.0 for _ in self.embedding_model.id_to_token]
self.prompt_answer_start_weights = []
self.prompt_answer_start_bias = [0.0 for _ in self.embedding_model.id_to_token]
self.transition_tables = self._build_transition_tables(tokens)
self._fit_answer_memory_from_text(text)
self._refresh_answer_fingerprint_hashes()
self.readout_weights = ridge_regression_readout(
analytical_states,
targets,
regularization=self.config.regularization,
)
self.readout_bias = [0.0 for _ in self.embedding_model.id_to_token]
self.preference_bias = [0.0 for _ in self.embedding_model.id_to_token]
self.state_offset = [0.0 for _ in analytical_states[0]] if analytical_states else []
self._refresh_numeric_caches()
return self
def _fit_answer_memory_from_text(self, text: str) -> None:
assert self.tokenizer is not None
assert self.embedding_model is not None
if (
self.answer_keys is None
or self.answer_key_norms is None
or self.answer_values is None
or self.answer_start_keys is None
or self.answer_start_key_norms is None
or self.answer_start_values is None
or self.answer_sequence_keys is None
or self.answer_sequence_key_norms is None
or self.answer_sequence_prompt_tokens is None
or self.answer_sequence_tokens is None
):
return
for line in text.splitlines():
if "<answer>" not in line:
continue
prompt_text, answer_text = line.split("<answer>", 1)
prompt_text = prompt_text.strip()
answer_text = answer_text.strip()
if not prompt_text or not answer_text:
continue
prompt_tokens = self.tokenizer.encode(prompt_text) + ["<answer>"]
answer_tokens = [
token
for token in self.tokenizer.encode(answer_text)
if token in self.embedding_model.token_to_id
and (
token not in self.tokenizer.special_tokens
or token in TOOL_PROTOCOL_TOKENS
)
]
if not prompt_tokens or not answer_tokens:
continue
key = self._encode_context(prompt_tokens)
key_norm = norm(key)
if key_norm <= 0.0:
continue
answer_ids = [
self.embedding_model.token_to_id[token]
for token in answer_tokens[:ANSWER_SEQUENCE_MAX_TOKENS]
]
prompt_ids = [
self.embedding_model.token_to_id[token]
for token in prompt_tokens[:ANSWER_SEQUENCE_MAX_TOKENS]
if token in self.embedding_model.token_to_id
and (
token not in self.tokenizer.special_tokens
or token in TOOL_PROTOCOL_TOKENS
)
]
if not answer_ids:
continue
self.answer_keys.append(key[:])
self.answer_key_norms.append(key_norm)
self.answer_values.append(answer_ids[0])
self.answer_start_keys.append(key[:])
self.answer_start_key_norms.append(key_norm)
self.answer_start_values.append(answer_ids[0])
self.answer_sequence_keys.append(key[:])
self.answer_sequence_key_norms.append(key_norm)
self.answer_sequence_prompt_tokens.append(
prompt_ids
+ [-1 for _ in range(ANSWER_SEQUENCE_MAX_TOKENS - len(prompt_ids))]
)
self.answer_sequence_tokens.append(
answer_ids
+ [-1 for _ in range(ANSWER_SEQUENCE_MAX_TOKENS - len(answer_ids))]
)
def predict_next_distribution(
self,
context: str,
*,
reasoning_mode: str | None = None,
) -> dict[str, float]:
self._require_fit()
assert self.tokenizer is not None
assert self.embedding_model is not None
probabilities = self.predict_next_token_distribution(
context,
reasoning_mode=reasoning_mode,
)
distribution: dict[str, float] = {}
for token, probability in probabilities.items():
rendered = self._render_token(token)
distribution[rendered] = distribution.get(rendered, 0.0) + probability
return distribution
def predict_next_token_distribution(
self,
context: str,
*,
reasoning_mode: str | None = None,
) -> dict[str, float]:
self._require_fit()
assert self.tokenizer is not None
assert self.embedding_model is not None
assert self.readout_weights is not None
active_mode = reasoning_mode or self.config.default_reasoning_profile
context_tokens = reasoning_prefix(active_mode) + self.tokenizer.encode(context)
return self._predict_next_token_distribution_from_tokens(context_tokens)
def generate_text(
self,
context: str,
*,
max_tokens: int = 64,
reasoning_mode: str | None = None,
temperature: float = 0.0,
top_k: int = DEFAULT_GENERATION_TOP_K,
top_p: float = DEFAULT_GENERATION_TOP_P,
repetition_penalty: float = DEFAULT_REPETITION_PENALTY,
avoid_texts: Sequence[str] | None = None,
) -> str:
character_count_response = self._character_count_response(
context,
temperature=temperature,
)
if character_count_response is not None:
return character_count_response
self._require_fit()
self._ensure_numeric_caches()
assert self.tokenizer is not None
runtime_avoid_texts = self._runtime_avoid_texts(
context,
avoid_texts,
temperature=temperature,
)
avoid_token_sequences = self._avoid_text_token_sequences(runtime_avoid_texts)
if (
np is not None
and self.readout_weights_array is not None
and self.embedding_model is not None
and len(self.embedding_model.id_to_token) >= 1024
):
generated_text = self._generate_text_fast(
context,
max_tokens=max_tokens,
reasoning_mode=reasoning_mode,
temperature=temperature,
top_k=top_k,
top_p=top_p,
repetition_penalty=repetition_penalty,
avoid_token_sequences=avoid_token_sequences,
)
self._remember_runtime_generation(
context,
generated_text,
temperature=temperature,
)
return generated_text
active_mode = reasoning_mode or self.config.default_reasoning_profile
_, context_tokens = self._generation_prompt_tokens(context, active_mode)
decode_state = self._build_decode_state(context_tokens)
generated_tokens: list[str] = []
for _ in range(max_tokens):
distribution, _ = self._score_next_token_from_state(
decode_state,
include_trace=False,
generated_tokens=generated_tokens,
temperature=temperature,
avoid_token_sequences=avoid_token_sequences,
)
forced_source_token = self._source_evidence_next_token(
decode_state.context_tokens,
generated_tokens,
)
next_token = forced_source_token or self._select_generation_token(
distribution,
context_tokens=decode_state.context_tokens,
generated_tokens=generated_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
repetition_penalty=repetition_penalty,
avoid_token_sequences=avoid_token_sequences,
preserve_dominant_candidates=(
self._answer_decode_has_continuation(decode_state, generated_tokens)
or self._source_evidence_has_continuation(
decode_state.context_tokens,
generated_tokens,
)
),
)
if not next_token:
break
generated_tokens.append(next_token)
self._advance_decode_state(decode_state, next_token)
if self._should_stop_answer_sequence(decode_state, generated_tokens):
break
if self._should_stop_after_answer_path_drift(decode_state, generated_tokens):
break
if self._source_evidence_is_complete(decode_state.context_tokens, generated_tokens):
break
if (
self._should_stop_generation(generated_tokens)
and not self._answer_decode_has_continuation(decode_state, generated_tokens)
and not self._source_evidence_has_continuation(
decode_state.context_tokens,
generated_tokens,
)
):
break
overflow_budget = max(WORD_COMPLETION_OVERFLOW_TOKENS, max_tokens)
while generated_tokens and overflow_budget > 0:
has_answer_continuation = self._answer_decode_has_continuation(
decode_state,
generated_tokens,
)
has_source_continuation = self._source_evidence_has_continuation(
decode_state.context_tokens,
generated_tokens,
)
if (
self._starts_new_word(generated_tokens[-1])
and not has_answer_continuation
and not has_source_continuation
):
break
distribution, _ = self._score_next_token_from_state(
decode_state,
include_trace=False,
generated_tokens=generated_tokens,
temperature=temperature,
avoid_token_sequences=avoid_token_sequences,
)
forced_source_token = self._source_evidence_next_token(
decode_state.context_tokens,
generated_tokens,
)
next_token = forced_source_token or self._select_generation_token(
distribution,
context_tokens=decode_state.context_tokens,
generated_tokens=generated_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
repetition_penalty=repetition_penalty,
avoid_token_sequences=avoid_token_sequences,
preserve_dominant_candidates=has_answer_continuation
or has_source_continuation,
)
if not next_token:
break
if (
self._starts_new_word(next_token)
and not has_answer_continuation
and not has_source_continuation
):
break
generated_tokens.append(next_token)
self._advance_decode_state(decode_state, next_token)
overflow_budget -= 1
generated_text = self._finalize_generated_text(
self._normalize_generated_tool_protocol_text(
self._decode_tokens(generated_tokens),
context=context,
)
)
self._remember_runtime_generation(
context,
generated_text,
temperature=temperature,
)
return generated_text
@staticmethod
def _character_count_fact(context: str) -> CharacterCountFact | None:
normalized = unicodedata.normalize("NFKC", context).strip()
tokens = ReframrModel._character_count_word_tokens(normalized)
if not tokens:
return None
lowered = [token.casefold() for token in tokens]
count_terms = {"count", "counts", "counting", "many"}
unit_terms = {"character", "characters", "letter", "letters"}
if not any(token in count_terms for token in lowered):
return None
if not any(token in unit_terms for token in lowered) and "count" not in lowered:
return None
filler_terms = {"a", "an", "the", "single", "one", "please"}
word_markers = {"in", "inside"}
char_index = ReframrModel._character_count_target_index(
lowered,
unit_terms=unit_terms,
filler_terms=filler_terms,
)
word_index = ReframrModel._character_count_word_index(
lowered,
char_index=char_index,
filler_terms=filler_terms,
word_markers=word_markers,
)
if char_index is None or word_index is None:
return None
character = tokens[char_index]
word = tokens[word_index]
if len(character) != 1 or not word:
return None
order_offset = 0 if char_index < word_index else 1
surface_seed = ((char_index + 1) * 7 + (word_index + 1) * 3 + len(tokens) + order_offset) % 4
structural_terms = (
count_terms
| unit_terms
| filler_terms
| word_markers
| {
"for",
"of",
"to",
"how",
"do",
"does",
"there",
"are",
"is",
"appear",
"appears",
"times",
"word",
}
)
extra_content_tokens = [
token
for index, token in enumerate(lowered)
if index not in {char_index, word_index}
and token not in structural_terms
]
return CharacterCountFact(
character=character,
word=word,
count=word.casefold().count(character.casefold()),
surface_seed=surface_seed,
focused=not extra_content_tokens,
)
@staticmethod
def _character_count_word_tokens(text: str) -> list[str]:
tokens: list[str] = []
current: list[str] = []
for character in text:
if character != "_" and character.isalnum():
current.append(character)
continue
if current:
tokens.append("".join(current))
current = []
if current:
tokens.append("".join(current))
return tokens
@staticmethod
def _character_count_target_index(
tokens: list[str],
*,
unit_terms: set[str],
filler_terms: set[str],
) -> int | None:
for index, token in enumerate(tokens):
if token not in unit_terms:
continue
for adjacent in (index - 1, index + 1):
if 0 <= adjacent < len(tokens) and len(tokens[adjacent]) == 1:
return adjacent
before = ReframrModel._nearest_content_index(tokens, index - 1, -1, filler_terms)
after = ReframrModel._nearest_content_index(tokens, index + 1, 1, filler_terms)
for candidate in (before, after):
if candidate is not None and len(tokens[candidate]) == 1:
return candidate
for index, token in enumerate(tokens):
if token not in {"count", "counts", "counting"}:
continue
candidate = ReframrModel._nearest_content_index(tokens, index + 1, 1, filler_terms)
if candidate is not None and tokens[candidate] in unit_terms:
candidate = ReframrModel._nearest_content_index(tokens, candidate + 1, 1, filler_terms)
if candidate is not None and len(tokens[candidate]) == 1:
return candidate
return None
@staticmethod
def _character_count_word_index(
tokens: list[str],
*,
char_index: int | None,
filler_terms: set[str],
word_markers: set[str],
) -> int | None:
for index, token in enumerate(tokens):
if token != "word":
continue
candidate = ReframrModel._nearest_content_index(tokens, index + 1, 1, filler_terms)
if candidate is not None and candidate != char_index and len(tokens[candidate]) > 1:
return candidate
for index, token in enumerate(tokens):
if token not in word_markers:
continue
candidate = ReframrModel._nearest_content_index(tokens, index + 1, 1, filler_terms)
if candidate is not None and tokens[candidate] == "word":
candidate = ReframrModel._nearest_content_index(tokens, candidate + 1, 1, filler_terms)
if candidate is not None and candidate != char_index and len(tokens[candidate]) > 1:
return candidate
skipped_terms = {
"how",
"many",
"do",
"does",
"count",
"counts",
"counting",
"letter",
"letters",
"character",
"characters",
"word",
"there",
"are",
"is",
"appear",
"appears",
"times",
} | filler_terms | word_markers
for index in range(len(tokens) - 1, -1, -1):
if index == char_index:
continue
if len(tokens[index]) <= 1 or tokens[index] in skipped_terms:
continue
return index
return None
@staticmethod
def _nearest_content_index(
tokens: list[str],
start: int,
direction: int,
skipped_terms: set[str],
) -> int | None:
index = start
while 0 <= index < len(tokens):
if tokens[index] not in skipped_terms:
return index
index += direction
return None
@classmethod
def _character_count_response(cls, context: str, *, temperature: float = 0.0) -> str | None:
fact = cls._character_count_fact(context)
if fact is None:
return None
if not fact.focused:
return None
return cls._render_character_count_fact(fact, temperature=temperature)
@staticmethod
def _render_character_count_fact(fact: CharacterCountFact, *, temperature: float = 0.0) -> str:
character_label = f"'{fact.character}'"
word_label = f"'{fact.word}'"
character_noun = "character" if fact.count == 1 else "characters"
return f"{word_label} has {fact.count} {character_label} {character_noun}."
@classmethod
def _runtime_source_grounded_response(cls, context: str) -> str | None:
return None
@classmethod
def _runtime_source_records(cls, context: str) -> list[tuple[str, str, str]]:
records: list[tuple[str, str, str]] = []
marker = "<source>"
search_from = 0
while True:
source_start = context.find(marker, search_from)
if source_start < 0:
break
content_start = source_start + len(marker)
content_end = cls._runtime_source_record_end(context, content_start)
raw_record = context[content_start:content_end].strip()
record = cls._parse_runtime_source_record(raw_record)
if record is not None:
records.append(record)
search_from = max(content_end, content_start + 1)
return records
@staticmethod
def _runtime_source_record_end(context: str, start: int) -> int:
boundaries = [
position
for marker in (
"\n",
"<source>",
"<tool_call>",
"<tool_result>",
"<final>",
"<answer>",
"<reason>",
)
if (position := context.find(marker, start)) >= 0
]
return min(boundaries) if boundaries else len(context)
@staticmethod
def _parse_runtime_source_record(raw_record: str) -> tuple[str, str, str] | None:
if not raw_record:
return None
pieces = [piece.strip() for piece in raw_record.split("|", 2)]
if len(pieces) >= 3:
title, url, snippet = pieces[0], pieces[1], pieces[2]
else:
title, url, snippet = "the provided source", "", pieces[-1]
title = ReframrModel._clean_runtime_source_field(title) or "the provided source"
url = ReframrModel._clean_runtime_source_field(url)
snippet = ReframrModel._clean_runtime_source_field(snippet)
if not snippet:
return None
return title, url, snippet
@staticmethod
def _clean_runtime_source_field(text: str) -> str:
normalized = unicodedata.normalize("NFKC", text)
cleaned = " ".join(normalized.split())
return cleaned.strip(" \t\r\n|")
def _generate_text_fast(
self,
context: str,
*,
max_tokens: int,
reasoning_mode: str | None,
temperature: float,
top_k: int,
top_p: float,
repetition_penalty: float,
avoid_token_sequences: Sequence[Sequence[str]] | None = None,
) -> str:
assert self.tokenizer is not None
active_mode = reasoning_mode or self.config.default_reasoning_profile
_, context_tokens = self._generation_prompt_tokens(context, active_mode)
decode_state = self._build_decode_state(context_tokens)
generated_tokens: list[str] = []
for _ in range(max_tokens):
probabilities, _ = self._score_next_token_array_from_state(
decode_state,
include_associative=not generated_tokens,
generated_tokens=generated_tokens,
temperature=temperature,
avoid_token_sequences=avoid_token_sequences,
)
forced_source_token = self._source_evidence_next_token(
decode_state.context_tokens,
generated_tokens,
)
next_token = forced_source_token or self._select_generation_token_from_array(
probabilities,
context_tokens=decode_state.context_tokens,
generated_tokens=generated_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
repetition_penalty=repetition_penalty,
avoid_token_sequences=avoid_token_sequences,
preserve_dominant_candidates=(
self._answer_decode_has_continuation(decode_state, generated_tokens)
or self._source_evidence_has_continuation(
decode_state.context_tokens,
generated_tokens,
)
),
)
if not next_token:
break
generated_tokens.append(next_token)
self._advance_decode_state(decode_state, next_token)
if self._should_stop_answer_sequence(decode_state, generated_tokens):
break
if self._should_stop_after_answer_path_drift(decode_state, generated_tokens):
break
if self._source_evidence_is_complete(decode_state.context_tokens, generated_tokens):
break
if (
self._should_stop_generation(generated_tokens)
and not self._answer_decode_has_continuation(decode_state, generated_tokens)
and not self._source_evidence_has_continuation(
decode_state.context_tokens,
generated_tokens,
)
):
break
overflow_budget = max(WORD_COMPLETION_OVERFLOW_TOKENS, max_tokens)
while generated_tokens and overflow_budget > 0:
has_answer_continuation = self._answer_decode_has_continuation(
decode_state,
generated_tokens,
)
has_source_continuation = self._source_evidence_has_continuation(
decode_state.context_tokens,
generated_tokens,
)
if (
self._starts_new_word(generated_tokens[-1])
and not has_answer_continuation
and not has_source_continuation
):
break
probabilities, _ = self._score_next_token_array_from_state(
decode_state,
include_associative=False,
generated_tokens=generated_tokens,
temperature=temperature,
avoid_token_sequences=avoid_token_sequences,
)
forced_source_token = self._source_evidence_next_token(
decode_state.context_tokens,
generated_tokens,
)
next_token = forced_source_token or self._select_generation_token_from_array(
probabilities,
context_tokens=decode_state.context_tokens,
generated_tokens=generated_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
repetition_penalty=repetition_penalty,
avoid_token_sequences=avoid_token_sequences,
preserve_dominant_candidates=has_answer_continuation
or has_source_continuation,
)
if not next_token:
break
if (
self._starts_new_word(next_token)
and not has_answer_continuation
and not has_source_continuation
):
break
generated_tokens.append(next_token)
self._advance_decode_state(decode_state, next_token)
overflow_budget -= 1
return self._finalize_generated_text(
self._normalize_generated_tool_protocol_text(
self._decode_tokens(generated_tokens),
context=context,
)
)
def trace_next_token(
self,
context: str,
*,
reasoning_mode: str | None = None,
top_k: int = 5,
) -> dict[str, object]:
self._require_fit()
assert self.tokenizer is not None
active_mode = reasoning_mode or self.config.default_reasoning_profile
context_tokens = reasoning_prefix(active_mode) + self.tokenizer.encode(context)
_, trace = self._score_next_token_from_tokens(
context_tokens,
top_k=top_k,
include_trace=True,
)
trace.update(
{
"context": context,
"reasoning_mode": active_mode,
"reasoning_tokens": reasoning_prefix(active_mode),
"context_tokens": context_tokens,
}
)
return trace
def trace_generation(
self,
context: str,
*,
max_tokens: int = 16,
reasoning_mode: str | None = None,
top_k: int = 5,
temperature: float = 0.0,
top_p: float = DEFAULT_GENERATION_TOP_P,
repetition_penalty: float = DEFAULT_REPETITION_PENALTY,
) -> dict[str, object]:
character_count_response = self._character_count_response(
context,
temperature=temperature,
)
if character_count_response is not None:
active_mode = reasoning_mode or self.config.default_reasoning_profile
prompt = context if "<answer>" in context else f"{context} <answer>"
return {
"context": context,
"prompt": prompt,
"reasoning_mode": active_mode,
"reasoning_tokens": reasoning_prefix(active_mode),
"generation_policy": {
"temperature": temperature,
"top_k": max(DEFAULT_GENERATION_TOP_K, top_k),
"top_p": top_p,
"repetition_penalty": repetition_penalty,
},
"prompt_tokens": [],
"generated_tokens": [],
"generated_text": character_count_response,
"generated_token_count": len(character_count_response.split()),
"steps": [],
"reasoning_summary": (
"The prompt matched the generic character-counting path, so Reframr "
"read the requested character and word from the prompt and counted "
"the characters directly."
),
}
self._require_fit()
assert self.tokenizer is not None
active_mode = reasoning_mode or self.config.default_reasoning_profile
prompt, context_tokens = self._generation_prompt_tokens(context, active_mode)
decode_state = self._build_decode_state(context_tokens)
prompt_tokens = decode_state.context_tokens[:]
generated_tokens: list[str] = []
steps: list[dict[str, object]] = []
for step_index in range(1, max_tokens + 1):
distribution, trace = self._score_next_token_from_state(
decode_state,
top_k=top_k,
include_trace=True,
generated_tokens=generated_tokens,
temperature=temperature,
)
forced_source_token = self._source_evidence_next_token(
decode_state.context_tokens,
generated_tokens,
)
next_token = forced_source_token or self._select_generation_token(
distribution,
context_tokens=decode_state.context_tokens,
generated_tokens=generated_tokens,
temperature=temperature,
top_k=max(DEFAULT_GENERATION_TOP_K, top_k),
top_p=top_p,
repetition_penalty=repetition_penalty,
preserve_dominant_candidates=(
self._answer_decode_has_continuation(decode_state, generated_tokens)
or self._source_evidence_has_continuation(
decode_state.context_tokens,
generated_tokens,
)
),
)
if not next_token:
break
generated_tokens.append(next_token)
self._advance_decode_state(decode_state, next_token)
trace["step"] = step_index
trace["chosen_token"] = next_token
trace["chosen_text"] = self._render_token(next_token)
trace["chosen_probability"] = distribution[next_token]
steps.append(trace)
if self._should_stop_answer_sequence(decode_state, generated_tokens):
break
if self._should_stop_after_answer_path_drift(decode_state, generated_tokens):
break
if self._source_evidence_is_complete(decode_state.context_tokens, generated_tokens):
break
if (
self._should_stop_generation(generated_tokens)
and not self._answer_decode_has_continuation(decode_state, generated_tokens)
and not self._source_evidence_has_continuation(
decode_state.context_tokens,
generated_tokens,
)
):
break
overflow_budget = max(WORD_COMPLETION_OVERFLOW_TOKENS, max_tokens)
while generated_tokens and overflow_budget > 0:
has_answer_continuation = self._answer_decode_has_continuation(
decode_state,
generated_tokens,
)
has_source_continuation = self._source_evidence_has_continuation(
decode_state.context_tokens,
generated_tokens,
)
if (
self._starts_new_word(generated_tokens[-1])
and not has_answer_continuation
and not has_source_continuation
):
break
distribution, trace = self._score_next_token_from_state(
decode_state,
top_k=top_k,
include_trace=True,
generated_tokens=generated_tokens,
temperature=temperature,
)
forced_source_token = self._source_evidence_next_token(
decode_state.context_tokens,
generated_tokens,
)
next_token = forced_source_token or self._select_generation_token(
distribution,
context_tokens=decode_state.context_tokens,
generated_tokens=generated_tokens,
temperature=temperature,
top_k=max(DEFAULT_GENERATION_TOP_K, top_k),
top_p=top_p,
repetition_penalty=repetition_penalty,
preserve_dominant_candidates=has_answer_continuation
or has_source_continuation,
)
if not next_token:
break
if (
self._starts_new_word(next_token)
and not has_answer_continuation
and not has_source_continuation
):
break
generated_tokens.append(next_token)
self._advance_decode_state(decode_state, next_token)
trace["step"] = len(steps) + 1
trace["chosen_token"] = next_token
trace["chosen_text"] = self._render_token(next_token)
trace["chosen_probability"] = distribution[next_token]
steps.append(trace)
if self._should_stop_answer_sequence(decode_state, generated_tokens):
break
if self._should_stop_after_answer_path_drift(decode_state, generated_tokens):
break
overflow_budget -= 1
return {
"context": context,
"prompt": prompt,
"reasoning_mode": active_mode,
"reasoning_tokens": reasoning_prefix(active_mode),
"generation_policy": {
"temperature": temperature,
"top_k": max(DEFAULT_GENERATION_TOP_K, top_k),
"top_p": top_p,
"repetition_penalty": repetition_penalty,
},
"prompt_tokens": prompt_tokens,
"generated_tokens": generated_tokens,
"generated_text": self._finalize_generated_text(
self._normalize_generated_tool_protocol_text(
self._decode_tokens(generated_tokens),
context=context,
)
),
"generated_token_count": len(generated_tokens),
"steps": steps,
}
def _generation_prompt_tokens(self, context: str, active_mode: str) -> tuple[str, list[str]]:
assert self.tokenizer is not None
prompt = context if "<answer>" in context else f"{context} <answer>"
prefix = reasoning_prefix(active_mode)
prompt_tokens = self.tokenizer.encode(prompt)
if (
"<answer>" in prompt_tokens
and "<reason>" not in prompt_tokens
and "<reason>" not in prefix
):
prompt_tokens = ["<reason>"] + prompt_tokens
return prompt, prefix + prompt_tokens
def _predict_next_token_distribution_from_tokens(
self,
context_tokens: list[str],
) -> dict[str, float]:
decode_state = self._build_decode_state(context_tokens)
return self._predict_next_token_distribution_from_state(decode_state)
def _predict_next_token_distribution_from_state(
self,
decode_state: DecodeState,
) -> dict[str, float]:
probabilities, _ = self._score_next_token_from_state(
decode_state,
include_trace=False,
)
return probabilities
@staticmethod
def _answer_memory_is_confident(
*,
answer_sequence_match_confidence: float,
answer_start_confidence: float,
generated_count: int,
) -> bool:
if generated_count > 0:
return answer_sequence_match_confidence >= ANSWER_SEQUENCE_MATCH_FLOOR
if answer_sequence_match_confidence >= ANSWER_SEQUENCE_DISTRIBUTED_LOCK_FLOOR:
return True
if answer_sequence_match_confidence >= ANSWER_SEQUENCE_MATCH_FLOOR:
return True
if answer_start_confidence >= ANSWER_START_CONFIDENCE_FLOOR + ANSWER_SEQUENCE_MATCH_FLOOR:
return True
return (
answer_sequence_match_confidence >= ANSWER_START_MATCH_SUPPORT_FLOOR
and answer_start_confidence >= ANSWER_START_CONFIDENCE_FLOOR
and answer_start_confidence <= answer_sequence_match_confidence + ANSWER_START_CONFIDENCE_FLOOR
)
@staticmethod
def _answer_sequence_should_lock(
*,
answer_sequence_confidence: float,
answer_sequence_match_confidence: float,
has_answer_sequence_prior: bool,
) -> bool:
if not has_answer_sequence_prior or answer_sequence_confidence <= 0.0:
return False
if answer_sequence_match_confidence >= ANSWER_SEQUENCE_LOCK_FLOOR:
return True
if (
answer_sequence_match_confidence >= ANSWER_SEQUENCE_MATCH_FLOOR
and answer_sequence_confidence >= 0.30
and answer_sequence_confidence <= 0.65
):
return True
return (
answer_sequence_match_confidence >= ANSWER_SEQUENCE_DISTRIBUTED_LOCK_FLOOR
and answer_sequence_confidence <= ANSWER_SEQUENCE_SPIKE_CONFIDENCE
)
def _prompt_start_readout_is_confident(
self,
prior: object,
tokens: Sequence[str] | None = None,
) -> bool:
if self.tokenizer is None:
return False
if tokens is None:
if self.embedding_model is None:
return False
tokens = self.embedding_model.id_to_token
values = prior.tolist() if hasattr(prior, "tolist") else list(prior)
if not values or not tokens:
return False
limit = min(len(values), len(tokens))
if limit <= 0:
return False
best_index = max(range(limit), key=lambda index: float(values[index]))
best_probability = float(values[best_index])
if best_probability < PROMPT_START_READOUT_CONFIDENCE_FLOOR:
return False
meta = self._generation_token_meta(tokens[best_index])
return (
meta.starts_new_word
and bool(meta.alphanumeric)
and not meta.structural_punctuation
and not meta.structural_symbol
)
def _locked_answer_sequence_matches(
self,
matches: list[tuple[float, int, int]],
*,
generated_tokens: list[str],
temperature: float,
answer_sequence_confidence: float,
answer_sequence_match_confidence: float,
) -> list[tuple[float, int, int]]:
if not matches:
return []
if generated_tokens:
aligned_matches = [
match
for match in matches[:ANSWER_START_TOP_K]
if self._answer_sequence_match_has_continuation(
match,
generated_tokens,
)
]
return aligned_matches[:ANSWER_SEQUENCE_VARIATION_MATCH_LIMIT] or matches[:1]
best_similarity = matches[0][0]
near_match_floor = max(ANSWER_SEQUENCE_MATCH_FLOOR, best_similarity - 0.08)
varied = [
match
for match in matches[:ANSWER_SEQUENCE_VARIATION_MATCH_LIMIT]
if match[0] >= near_match_floor
]
if (
temperature < ANSWER_SEQUENCE_VARIATION_TEMPERATURE
and answer_sequence_match_confidence >= ANSWER_SEQUENCE_LOCK_FLOOR
and len(varied) <= 1
):
return matches[:1]
return varied or matches[:1]
@staticmethod
def _answer_sequence_matches_are_ambiguous(
matches: Sequence[tuple[float, int, int]],
) -> bool:
if len(matches) < 2:
return False
best_similarity = float(matches[0][0])
if best_similarity < ANSWER_SEQUENCE_MATCH_FLOOR:
return False
near_match_floor = max(ANSWER_SEQUENCE_MATCH_FLOOR, best_similarity - 0.08)
return any(
float(match[0]) >= near_match_floor
for match in matches[1:ANSWER_SEQUENCE_VARIATION_MATCH_LIMIT]
)
def _answer_sequence_match_has_continuation(
self,
match: tuple[float, int, int],
generated_tokens: list[str],
) -> bool:
if (
self.embedding_model is None
or self.answer_sequence_tokens is None
or not generated_tokens
):
return False
similarity, sequence_index, _ = match
if similarity < ANSWER_SEQUENCE_MATCH_FLOOR or sequence_index >= len(self.answer_sequence_tokens):
return False
generated_ids = [
self.embedding_model.token_to_id[token]
for token in generated_tokens
if token in self.embedding_model.token_to_id
]
if not generated_ids:
return False
row = self.answer_sequence_tokens[sequence_index]
token_ids = [
int(value)
for value in (row.tolist() if hasattr(row, "tolist") else row)
if int(value) >= 0
]
if not token_ids:
return False
next_token_id = self._next_sequence_token_id(token_ids, generated_ids)
if next_token_id is None:
return False
token = self.embedding_model.id_to_token[next_token_id]
return self._allowed_answer_sequence_token(token, generated_tokens)
def _allowed_answer_sequence_token(
self,
token: str,
generated_tokens: list[str],
) -> bool:
assert self.tokenizer is not None
if token == self.tokenizer.unk_token:
return False
if token in self.tokenizer.special_tokens:
return self._allowed_generation_token(token, generated_tokens)
return True
def _should_relax_answer_sequence_memory(
self,
matches: list[tuple[float, int, int]],
answer_sequence_prior: Sequence[float],
*,
generated_tokens: list[str],
temperature: float,
) -> bool:
if temperature < ANSWER_SEQUENCE_CREATIVE_TEMPERATURE or not matches:
return False
if self._is_inside_tool_protocol_continuation(generated_tokens):
return False
if self._answer_sequence_prior_prefers_tool_protocol(answer_sequence_prior):
return False
return True
def _answer_sequence_prior_prefers_tool_protocol(
self,
answer_sequence_prior: Sequence[float],
) -> bool:
if self.embedding_model is None or not answer_sequence_prior:
return False
best_index = -1
best_value = 0.0
for index, value in enumerate(answer_sequence_prior):
if value > best_value:
best_index = index
best_value = float(value)
return (
best_index >= 0
and best_index < len(self.embedding_model.id_to_token)
and best_value > 0.0
and self.embedding_model.id_to_token[best_index] in TOOL_PROTOCOL_TOKENS
)
@staticmethod
def _answer_start_blend_weights(
*,
answer_sequence_match_confidence: float,
temperature: float = 0.0,
) -> dict[str, float]:
if temperature >= ANSWER_SEQUENCE_CREATIVE_TEMPERATURE:
return {
"prompt_answer_start": 0.46,
"prompt_answer": 0.24,
"answer_sequence": 0.10,
"answer_start": 0.20,
}
if answer_sequence_match_confidence >= ANSWER_SEQUENCE_LOCK_FLOOR:
return {
"prompt_answer_start": 0.35,
"prompt_answer": 0.10,
"answer_sequence": 0.45,
"answer_start": 0.10,
}
if answer_sequence_match_confidence >= 0.40:
return {
"prompt_answer_start": 0.25,
"prompt_answer": 0.12,
"answer_sequence": 0.53,
"answer_start": 0.10,
}
return {
"prompt_answer_start": 0.08,
"prompt_answer": 0.10,
"answer_sequence": 0.02,
"answer_start": 0.80,
}
def _score_next_token_from_tokens(
self,
context_tokens: list[str],
*,
top_k: int = 5,
include_trace: bool = True,
) -> tuple[dict[str, float], dict[str, object]]:
decode_state = self._build_decode_state(context_tokens)
return self._score_next_token_from_state(
decode_state,
top_k=top_k,
include_trace=include_trace,
)
def _score_next_token_from_state(
self,
decode_state: DecodeState,
*,
top_k: int = 5,
include_trace: bool = True,
generated_tokens: list[str] | None = None,
temperature: float = 0.0,
avoid_token_sequences: Sequence[Sequence[str]] | None = None,
) -> tuple[dict[str, float], dict[str, object]]:
assert self.embedding_model is not None
assert self.readout_weights is not None
generated_tokens = generated_tokens or []
state = self._masked_decode_state(decode_state)
logits = self._apply_readout_fast(state)
base_probabilities = self._calibrated_softmax(logits)
if decode_state.answer_matches is None:
decode_state.answer_matches = self._score_answer_matches(
decode_state.answer_anchor_state,
limit=max(ANSWER_TOP_K, top_k) if include_trace else ANSWER_TOP_K,
)
answer_matches = decode_state.answer_matches
if decode_state.answer_start_matches is None:
decode_state.answer_start_matches = self._score_answer_start_matches(
decode_state.answer_anchor_state,
limit=max(ANSWER_START_TOP_K, top_k) if include_trace else ANSWER_START_TOP_K,
)
answer_start_matches = decode_state.answer_start_matches
if decode_state.answer_sequence_matches is None:
decode_state.answer_sequence_matches = self._score_answer_sequence_matches(
decode_state.answer_anchor_state,
decode_state.context_tokens,
limit=max(ANSWER_START_TOP_K, top_k) if include_trace else ANSWER_START_TOP_K,
)
answer_sequence_matches = self._filter_avoided_answer_sequence_matches(
decode_state.answer_sequence_matches,
avoid_token_sequences,
)
if not answer_start_matches and answer_sequence_matches:
answer_start_matches = self._answer_start_matches_from_sequences(
answer_sequence_matches
)
decode_state.answer_start_matches = answer_start_matches
answer_prior = self._answer_prior_from_matches(answer_matches, generated_tokens)
answer_start_prior = self._answer_prior_from_matches(answer_start_matches, generated_tokens)
answer_sequence_prior = self._answer_sequence_prior_from_matches(
answer_sequence_matches,
generated_tokens,
temperature=temperature,
)
answer_sequence_confidence = max(answer_sequence_prior) if answer_sequence_prior else 0.0
answer_sequence_match_confidence = (
answer_sequence_matches[0][0] if answer_sequence_matches else 0.0
)
answer_start_confidence = answer_start_matches[0][0] if answer_start_matches else 0.0
prompt_copy_is_distinctive = (
not generated_tokens
and self._prompt_copy_evidence_is_distinctive(decode_state.context_tokens)
)
answer_memory_confident = self._answer_memory_is_confident(
answer_sequence_match_confidence=answer_sequence_match_confidence,
answer_start_confidence=answer_start_confidence,
generated_count=len(generated_tokens),
)
if prompt_copy_is_distinctive and not answer_sequence_matches:
answer_memory_confident = False
has_answer_sequence_prior = any(value > 0.0 for value in answer_sequence_prior)
if not answer_memory_confident:
zero_prior = [0.0 for _ in self.embedding_model.id_to_token]
answer_prior = zero_prior
answer_start_prior = zero_prior
answer_sequence_prior = zero_prior
answer_sequence_confidence = 0.0
has_answer_sequence_prior = False
answer_locked = self._answer_sequence_should_lock(
answer_sequence_confidence=answer_sequence_confidence,
answer_sequence_match_confidence=answer_sequence_match_confidence,
has_answer_sequence_prior=has_answer_sequence_prior,
) or (
bool(generated_tokens)
and temperature < ANSWER_SEQUENCE_CREATIVE_TEMPERATURE
and self._answer_sequence_has_continuation(
generated_tokens,
answer_sequence_matches,
)
)
if self._should_relax_answer_sequence_memory(
answer_sequence_matches,
answer_sequence_prior,
generated_tokens=generated_tokens,
temperature=temperature,
):
answer_locked = False
if decode_state.prompt_answer_prior is None:
decode_state.prompt_answer_prior = self._prompt_answer_readout_prior(
decode_state.answer_anchor_state,
start=False,
)
prompt_answer_prior = decode_state.prompt_answer_prior
prompt_answer_start_prior = (
decode_state.prompt_answer_start_prior
if not generated_tokens
else [0.0 for _ in self.embedding_model.id_to_token]
)
if not generated_tokens and prompt_answer_start_prior is None:
decode_state.prompt_answer_start_prior = self._prompt_answer_readout_prior(
decode_state.answer_anchor_state,
start=True,
)
prompt_answer_start_prior = decode_state.prompt_answer_start_prior
prompt_start_readout_confident = (
not generated_tokens
and prompt_answer_start_prior is not None
and self._prompt_start_readout_is_confident(prompt_answer_start_prior)
)
prompt_readout_supported = answer_memory_confident and (
answer_sequence_match_confidence >= ANSWER_SEQUENCE_MATCH_FLOOR
or answer_start_confidence >= ANSWER_START_CONFIDENCE_FLOOR
)
if prompt_start_readout_confident:
prompt_readout_supported = True
if not prompt_readout_supported:
prompt_answer_prior = [0.0 for _ in self.embedding_model.id_to_token]
prompt_answer_start_prior = [0.0 for _ in self.embedding_model.id_to_token]
use_answer_start = (
not generated_tokens
and (
any(value > 0.0 for value in answer_start_prior)
or any(value > 0.0 for value in prompt_answer_start_prior)
)
)
if answer_locked:
locked_matches = self._locked_answer_sequence_matches(
answer_sequence_matches,
generated_tokens=generated_tokens,
temperature=temperature,
answer_sequence_confidence=answer_sequence_confidence,
answer_sequence_match_confidence=answer_sequence_match_confidence,
)
answer_sequence_prior = self._answer_sequence_prior_from_matches(
locked_matches,
generated_tokens,
temperature=temperature,
)
answer_prior = answer_sequence_prior
elif use_answer_start:
start_blend = self._answer_start_blend_weights(
answer_sequence_match_confidence=answer_sequence_match_confidence,
temperature=temperature,
)
answer_prior = self._weighted_prior_sum(
[
(start_blend["prompt_answer_start"], prompt_answer_start_prior),
(start_blend["prompt_answer"], prompt_answer_prior),
(start_blend["answer_sequence"], answer_sequence_prior),
(start_blend["answer_start"], answer_start_prior),
],
)
elif any(value > 0.0 for value in answer_sequence_prior):
sequence_weight = (
0.10
if temperature >= ANSWER_SEQUENCE_CREATIVE_TEMPERATURE
else 0.30
)
answer_prior = self._weighted_prior_sum(
[
(0.55, prompt_answer_prior),
(sequence_weight, answer_sequence_prior),
(0.20, answer_prior),
],
)
elif any(value > 0.0 for value in prompt_answer_prior):
answer_prior = self._weighted_prior_sum(
[
(0.65, prompt_answer_prior),
(0.35, answer_prior),
],
)
answer_guided = (
max(answer_prior) >= 0.08
if answer_prior
else False
)
associative_matches = (
[]
if use_answer_start or answer_guided
else self._score_associative_matches(
state,
limit=max(ASSOCIATIVE_TOP_K, top_k) if include_trace else ASSOCIATIVE_TOP_K,
)
)
associative_prior = (
[0.0 for _ in self.embedding_model.id_to_token]
if use_answer_start or answer_guided
else self._associative_prior_from_matches(associative_matches)
)
transition_prior, transition_order = self._transition_prior_with_order(decode_state.context_tokens)
copy_prior = self._copy_prior(decode_state.context_tokens)
source_evidence_prior = self._source_evidence_prior(
decode_state.context_tokens,
generated_tokens,
)
preference_prior = self._preference_prior()
probabilities, blend_weights = self._blend_probabilities(
base_probabilities,
answer_prior,
associative_prior,
transition_prior,
copy_prior,
source_evidence_prior,
preference_prior,
transition_order=transition_order,
generated_count=len(generated_tokens),
answer_locked=answer_locked,
answer_guided_start=use_answer_start,
copy_guided_start=prompt_copy_is_distinctive,
)
probabilities = self._focus_answer_start_probabilities(
probabilities,
answer_sequence_prior,
generated_tokens=generated_tokens,
answer_memory_confident=answer_memory_confident,
has_answer_sequence_prior=has_answer_sequence_prior,
sequence_focus_allowed=answer_sequence_match_confidence >= 0.40 or answer_locked,
temperature=temperature,
)
distribution = {
token: probabilities[index]
for index, token in enumerate(self.embedding_model.id_to_token)
}
if not include_trace:
return distribution, {}
trace = {
"state_norm": norm(state),
"blend_weights": blend_weights,
"transition_order": transition_order,
"base_top_predictions": self._top_entries_from_vector(base_probabilities, top_k),
"answer_top_predictions": self._top_entries_from_vector(answer_prior, top_k),
"prompt_answer_top_predictions": self._top_entries_from_vector(prompt_answer_prior, top_k),
"prompt_answer_start_top_predictions": self._top_entries_from_vector(prompt_answer_start_prior, top_k),
"answer_start_top_predictions": self._top_entries_from_vector(answer_start_prior, top_k),
"answer_sequence_top_predictions": self._top_entries_from_vector(answer_sequence_prior, top_k),
"associative_top_predictions": self._top_entries_from_vector(associative_prior, top_k),
"transition_top_predictions": self._top_entries_from_vector(transition_prior, top_k),
"copy_top_predictions": self._top_entries_from_vector(copy_prior, top_k),
"source_evidence_top_predictions": self._top_entries_from_vector(source_evidence_prior, top_k),
"preference_top_predictions": self._top_entries_from_vector(preference_prior, top_k),
"final_top_predictions": self._top_entries_from_vector(probabilities, top_k),
"associative_matches": [
{
"example_index": example_index,
"similarity": similarity,
**self._token_entry(token_id, similarity),
}
for similarity, token_id, example_index in associative_matches[:top_k]
],
"answer_matches": [
{
"example_index": example_index,
"similarity": similarity,
**self._token_entry(token_id, similarity),
}
for similarity, token_id, example_index in answer_matches[:top_k]
],
"answer_start_matches": [
{
"example_index": example_index,
"similarity": similarity,
**self._token_entry(token_id, similarity),
}
for similarity, token_id, example_index in answer_start_matches[:top_k]
],
"answer_sequence_matches": [
{
"example_index": example_index,
"similarity": similarity,
}
for similarity, _, example_index in answer_sequence_matches[:top_k]
],
"reasoning_summary": self._build_reasoning_summary(
transition_order,
blend_weights,
),
}
return distribution, trace
def _score_next_token_array_from_state(
self,
decode_state: DecodeState,
*,
include_associative: bool,
generated_tokens: list[str] | None = None,
temperature: float = 0.0,
avoid_token_sequences: Sequence[Sequence[str]] | None = None,
) -> tuple[object, dict[str, float]]:
assert np is not None
assert self.embedding_model is not None
generated_tokens = generated_tokens or []
state = self._masked_decode_state_array(decode_state)
logits = self._apply_readout_array(state)
base_probabilities = self._calibrated_softmax_array(logits)
if decode_state.answer_matches is None:
decode_state.answer_matches = self._score_answer_matches(decode_state.answer_anchor_state)
answer_prior = np.asarray(
self._answer_prior_from_matches(
decode_state.answer_matches,
generated_tokens,
),
dtype=np.float64,
)
if decode_state.answer_sequence_matches is None:
decode_state.answer_sequence_matches = self._score_answer_sequence_matches(
decode_state.answer_anchor_state,
decode_state.context_tokens,
)
answer_sequence_matches = self._filter_avoided_answer_sequence_matches(
decode_state.answer_sequence_matches,
avoid_token_sequences,
)
if not decode_state.answer_start_matches and answer_sequence_matches:
decode_state.answer_start_matches = self._answer_start_matches_from_sequences(
answer_sequence_matches
)
answer_sequence_prior = np.asarray(
self._answer_sequence_prior_from_matches(
answer_sequence_matches,
generated_tokens,
temperature=temperature,
),
dtype=np.float64,
)
answer_sequence_confidence = (
float(answer_sequence_prior.max()) if answer_sequence_prior.size else 0.0
)
answer_sequence_match_confidence = (
answer_sequence_matches[0][0] if answer_sequence_matches else 0.0
)
if not generated_tokens and decode_state.answer_start_matches is None:
decode_state.answer_start_matches = self._score_answer_start_matches(
decode_state.answer_anchor_state
)
answer_start_confidence = (
decode_state.answer_start_matches[0][0]
if not generated_tokens and decode_state.answer_start_matches
else 0.0
)
prompt_copy_is_distinctive = (
not generated_tokens
and self._prompt_copy_evidence_is_distinctive(decode_state.context_tokens)
)
answer_memory_confident = self._answer_memory_is_confident(
answer_sequence_match_confidence=answer_sequence_match_confidence,
answer_start_confidence=answer_start_confidence,
generated_count=len(generated_tokens),
)
if prompt_copy_is_distinctive and not answer_sequence_matches:
answer_memory_confident = False
has_answer_sequence_prior = bool(np.any(answer_sequence_prior > 0.0))
if not answer_memory_confident:
answer_prior = np.zeros_like(base_probabilities)
answer_sequence_prior = np.zeros_like(base_probabilities)
answer_sequence_confidence = 0.0
has_answer_sequence_prior = False
answer_locked = self._answer_sequence_should_lock(
answer_sequence_confidence=answer_sequence_confidence,
answer_sequence_match_confidence=answer_sequence_match_confidence,
has_answer_sequence_prior=has_answer_sequence_prior,
) or (
bool(generated_tokens)
and temperature < ANSWER_SEQUENCE_CREATIVE_TEMPERATURE
and self._answer_sequence_has_continuation(
generated_tokens,
answer_sequence_matches,
)
)
if self._should_relax_answer_sequence_memory(
answer_sequence_matches,
answer_sequence_prior.tolist(),
generated_tokens=generated_tokens,
temperature=temperature,
):
answer_locked = False
if decode_state.prompt_answer_prior is None:
decode_state.prompt_answer_prior = self._prompt_answer_readout_prior_array(
decode_state.answer_anchor_state,
start=False,
)
prompt_answer_prior = decode_state.prompt_answer_prior
prompt_answer_start_prior = np.zeros_like(base_probabilities)
use_answer_start = False
if answer_locked:
locked_matches = self._locked_answer_sequence_matches(
answer_sequence_matches,
generated_tokens=generated_tokens,
temperature=temperature,
answer_sequence_confidence=answer_sequence_confidence,
answer_sequence_match_confidence=answer_sequence_match_confidence,
)
answer_sequence_prior = np.asarray(
self._answer_sequence_prior_from_matches(
locked_matches,
generated_tokens,
temperature=temperature,
),
dtype=np.float64,
)
answer_prior = answer_sequence_prior
elif not generated_tokens:
if decode_state.prompt_answer_start_prior is None:
decode_state.prompt_answer_start_prior = self._prompt_answer_readout_prior_array(
decode_state.answer_anchor_state,
start=True,
)
prompt_answer_start_prior = (
decode_state.prompt_answer_start_prior
if decode_state.prompt_answer_start_prior is not None
else np.zeros_like(base_probabilities)
)
prompt_start_readout_confident = self._prompt_start_readout_is_confident(
prompt_answer_start_prior
)
prompt_readout_supported = answer_memory_confident and (
answer_sequence_match_confidence >= ANSWER_SEQUENCE_MATCH_FLOOR
or answer_start_confidence >= ANSWER_START_CONFIDENCE_FLOOR
)
if prompt_start_readout_confident:
prompt_readout_supported = True
if not prompt_readout_supported:
prompt_answer_prior = np.zeros_like(base_probabilities)
prompt_answer_start_prior = np.zeros_like(base_probabilities)
answer_start_prior = np.asarray(
self._answer_prior_from_matches(
decode_state.answer_start_matches,
generated_tokens,
),
dtype=np.float64,
)
if not answer_memory_confident:
answer_start_prior = np.zeros_like(base_probabilities)
if np.any(answer_start_prior > 0.0) or np.any(prompt_answer_start_prior > 0.0):
start_blend = self._answer_start_blend_weights(
answer_sequence_match_confidence=answer_sequence_match_confidence,
temperature=temperature,
)
answer_prior = self._weighted_prior_sum_array(
[
(start_blend["prompt_answer_start"], prompt_answer_start_prior),
(start_blend["prompt_answer"], prompt_answer_prior),
(start_blend["answer_sequence"], answer_sequence_prior),
(start_blend["answer_start"], answer_start_prior),
],
)
use_answer_start = True
if answer_locked:
answer_prior = answer_sequence_prior
elif not use_answer_start and np.any(answer_sequence_prior > 0.0):
sequence_weight = (
0.10
if temperature >= ANSWER_SEQUENCE_CREATIVE_TEMPERATURE
else 0.30
)
answer_prior = self._weighted_prior_sum_array(
[
(0.55, prompt_answer_prior),
(sequence_weight, answer_sequence_prior),
(0.20, answer_prior),
],
)
elif not use_answer_start and np.any(prompt_answer_prior > 0.0):
answer_prior = self._weighted_prior_sum_array(
[
(0.65, prompt_answer_prior),
(0.35, answer_prior),
],
)
answer_guided = bool(answer_prior.size and float(np.max(answer_prior)) >= 0.08)
if include_associative and not use_answer_start and not answer_guided:
associative_prior = np.asarray(
self._associative_prior_from_matches(
self._score_associative_matches(state)
),
dtype=np.float64,
)
else:
associative_prior = np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
transition_prior, transition_order = self._transition_prior_array_with_order(
decode_state.context_tokens
)
copy_prior = self._copy_prior_array(decode_state.context_tokens)
source_evidence_prior = self._source_evidence_prior_array(
decode_state.context_tokens,
generated_tokens,
)
preference_prior = self._preference_prior_array()
probabilities, blend_weights = self._blend_probability_arrays(
base_probabilities,
answer_prior,
associative_prior,
transition_prior,
copy_prior,
source_evidence_prior,
preference_prior,
transition_order=transition_order,
generated_count=len(generated_tokens),
answer_locked=answer_locked,
answer_guided_start=use_answer_start,
)
probabilities = self._focus_answer_start_probability_array(
probabilities,
answer_sequence_prior,
generated_tokens=generated_tokens,
answer_memory_confident=answer_memory_confident,
has_answer_sequence_prior=has_answer_sequence_prior,
sequence_focus_allowed=answer_sequence_match_confidence >= 0.40 or answer_locked,
temperature=temperature,
)
return probabilities, blend_weights
@staticmethod
def _focus_answer_start_probabilities(
probabilities: Vector,
answer_sequence_prior: Vector,
*,
generated_tokens: list[str],
answer_memory_confident: bool,
has_answer_sequence_prior: bool,
sequence_focus_allowed: bool | None = None,
temperature: float = 0.0,
) -> Vector:
if sequence_focus_allowed is None:
sequence_focus_allowed = has_answer_sequence_prior
if temperature >= ANSWER_SEQUENCE_CREATIVE_TEMPERATURE:
return probabilities
if (
generated_tokens
or not answer_memory_confident
or not has_answer_sequence_prior
or not sequence_focus_allowed
):
return probabilities
if not probabilities or not answer_sequence_prior:
return probabilities
focused = [
probability if index < len(answer_sequence_prior) and answer_sequence_prior[index] > 0.0 else probability * 0.02
for index, probability in enumerate(probabilities)
]
total = sum(focused)
if total <= 0.0:
return probabilities
return [value / total for value in focused]
@staticmethod
def _focus_answer_start_probability_array(
probabilities: object,
answer_sequence_prior: object,
*,
generated_tokens: list[str],
answer_memory_confident: bool,
has_answer_sequence_prior: bool,
sequence_focus_allowed: bool | None = None,
temperature: float = 0.0,
) -> object:
if sequence_focus_allowed is None:
sequence_focus_allowed = has_answer_sequence_prior
if temperature >= ANSWER_SEQUENCE_CREATIVE_TEMPERATURE:
return probabilities
if (
np is None
or generated_tokens
or not answer_memory_confident
or not has_answer_sequence_prior
or not sequence_focus_allowed
):
return probabilities
values = np.asarray(probabilities, dtype=np.float64)
prior = np.asarray(answer_sequence_prior, dtype=np.float64)
if values.size == 0 or prior.size != values.size or not np.any(prior > 0.0):
return probabilities
focused = values.copy()
focused[prior <= 0.0] *= 0.02
total = float(focused.sum())
if total <= 0.0:
return probabilities
return focused / total
def _calibrated_softmax(
self,
logits: Vector,
*,
scale: float = READOUT_LOGIT_ZSCORE_SCALE,
) -> Vector:
if np is not None:
return self._calibrated_softmax_array(
np.asarray(logits, dtype=np.float64),
scale=scale,
).tolist()
if not logits:
return []
center = mean(logits)
variance = mean([(value - center) * (value - center) for value in logits])
spread = variance**0.5
if spread <= 1e-12:
return softmax(logits)
calibrated = [
max(-20.0, min(20.0, ((value - center) / spread) * scale))
for value in logits
]
return softmax(calibrated)
def _calibrated_softmax_array(
self,
logits: object,
*,
scale: float = READOUT_LOGIT_ZSCORE_SCALE,
) -> object:
assert np is not None
values = np.asarray(logits, dtype=np.float64)
if values.size == 0:
return values
spread = float(values.std())
if spread > 1e-12:
values = ((values - float(values.mean())) / spread) * scale
values = np.clip(values, -20.0, 20.0)
else:
values = values - float(values.max())
values = values - float(values.max())
exponentials = np.exp(values)
total = float(exponentials.sum())
if total <= 0.0:
return np.full(values.shape, 1.0 / max(1, values.size), dtype=np.float64)
return exponentials / total
def _weighted_prior_sum(self, sources: list[tuple[float, Vector]]) -> Vector:
assert self.embedding_model is not None
active_sources = [
(weight, vector)
for weight, vector in sources
if weight > 0.0 and any(value > 0.0 for value in vector)
]
if not active_sources:
return [0.0 for _ in self.embedding_model.id_to_token]
total_weight = sum(weight for weight, _ in active_sources)
merged = [0.0 for _ in self.embedding_model.id_to_token]
for weight, vector in active_sources:
normalized_weight = weight / total_weight
for index, value in enumerate(vector):
merged[index] += normalized_weight * value
return _normalize_vector(merged)
def _weighted_prior_sum_array(self, sources: list[tuple[float, object]]) -> object:
assert np is not None
assert self.embedding_model is not None
active_sources = [
(weight, np.asarray(vector, dtype=np.float64))
for weight, vector in sources
if weight > 0.0 and np.any(np.asarray(vector, dtype=np.float64) > 0.0)
]
if not active_sources:
return np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
total_weight = sum(weight for weight, _ in active_sources)
merged = np.zeros_like(active_sources[0][1], dtype=np.float64)
for weight, vector in active_sources:
merged += (weight / total_weight) * vector
total = float(merged.sum())
if total > 0.0:
merged /= total
return merged
def _prompt_answer_readout_prior(
self,
answer_anchor_state: Vector | None,
*,
start: bool,
) -> Vector:
assert self.embedding_model is not None
if answer_anchor_state is None:
return [0.0 for _ in self.embedding_model.id_to_token]
weights = self.prompt_answer_start_weights if start else self.prompt_answer_weights
bias = self.prompt_answer_start_bias if start else self.prompt_answer_bias
if np is not None:
return self._prompt_answer_readout_prior_array(
answer_anchor_state,
start=start,
).tolist()
if not weights:
return [0.0 for _ in self.embedding_model.id_to_token]
state = self._center_state_vector(self._masked_combined_state(answer_anchor_state))
logits = apply_readout(weights, state)
if bias:
logits = [value + bias[index] for index, value in enumerate(logits)]
return self._calibrated_softmax(
logits,
scale=PROMPT_READOUT_LOGIT_ZSCORE_SCALE,
)
def _prompt_answer_readout_prior_array(
self,
answer_anchor_state: Vector | None,
*,
start: bool,
) -> object:
assert np is not None
assert self.embedding_model is not None
if answer_anchor_state is None:
return np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
weights = (
self.prompt_answer_start_weights_array
if start
else self.prompt_answer_weights_array
)
bias = self.prompt_answer_start_bias_array if start else self.prompt_answer_bias_array
if weights is None:
return np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
state_array = self._center_state_array(
self._masked_combined_state_array(answer_anchor_state)
)
logits = weights @ state_array
if bias is not None and bias.shape == logits.shape:
logits = logits + bias
return self._calibrated_softmax_array(
logits,
scale=PROMPT_READOUT_LOGIT_ZSCORE_SCALE,
)
def save(self, path: str | Path) -> None:
self._require_fit()
assert self.tokenizer is not None
assert self.embedding_model is not None
assert self.ternary_mask is not None
assert self.readout_weights is not None
assert self.associative_keys is not None
assert self.associative_values is not None
assert self.transition_tables is not None
metadata = {
"schema_version": "1",
"checkpoint_kind": "reframr-analytical",
"tokenizer_name": self.tokenizer.name,
"config": json.dumps(self.config.to_dict(), separators=(",", ":")),
"tokenizer": json.dumps(self.tokenizer.to_dict(), separators=(",", ":")),
"embedding_id_to_token": json.dumps(self.embedding_model.id_to_token, separators=(",", ":")),
"tokenizer_vocab_size": str(self.tokenizer.vocab_size),
"transition_table_format": "tensor-v1",
}
self._refresh_answer_fingerprint_hashes()
if np is not None:
self._refresh_numeric_caches()
transition_tensors = self._transition_table_tensors()
tensors = {
"embedding_table": self.embedding_model.embeddings,
"ternary_scale": [self.ternary_scale],
"ternary_mask": self.ternary_mask,
"readout_weights": self.readout_weights,
"readout_bias": self.readout_bias
or [0.0 for _ in self.embedding_model.id_to_token],
"prompt_answer_weights": self.prompt_answer_weights
if self.prompt_answer_weights is not None
else [],
"prompt_answer_bias": self.prompt_answer_bias
or [0.0 for _ in self.embedding_model.id_to_token],
"prompt_answer_start_weights": self.prompt_answer_start_weights
if self.prompt_answer_start_weights is not None
else [],
"prompt_answer_start_bias": self.prompt_answer_start_bias
or [0.0 for _ in self.embedding_model.id_to_token],
"trace_token_weights": self.trace_token_weights
or [1.0 for _ in self.embedding_model.id_to_token],
"preference_bias": self.preference_bias
or [0.0 for _ in self.embedding_model.id_to_token],
"state_offset": self.state_offset
or [0.0 for _ in range(self._combined_state_width())],
"associative_keys": self.associative_keys,
"associative_key_norms": self.associative_key_norms_array
if self.associative_key_norms_array is not None
else self.associative_key_norms or [],
"associative_values": self.associative_values,
"answer_keys": self.answer_keys if self.answer_keys is not None else [],
"answer_key_norms": self.answer_key_norms_array
if self.answer_key_norms_array is not None
else self.answer_key_norms or [],
"answer_similarity_keys": self.answer_similarity_keys_array
if self.answer_similarity_keys_array is not None
else [],
"answer_similarity_key_norms": self.answer_similarity_key_norms_array
if self.answer_similarity_key_norms_array is not None
else [],
"answer_values": self.answer_values if self.answer_values is not None else [],
"answer_start_keys": self.answer_start_keys if self.answer_start_keys is not None else [],
"answer_start_key_norms": self.answer_start_key_norms_array
if self.answer_start_key_norms_array is not None
else self.answer_start_key_norms or [],
"answer_start_similarity_keys": self.answer_start_similarity_keys_array
if self.answer_start_similarity_keys_array is not None
else [],
"answer_start_similarity_key_norms": self.answer_start_similarity_key_norms_array
if self.answer_start_similarity_key_norms_array is not None
else [],
"answer_start_values": self.answer_start_values if self.answer_start_values is not None else [],
"answer_sequence_keys": self.answer_sequence_keys if self.answer_sequence_keys is not None else [],
"answer_sequence_key_norms": self.answer_sequence_key_norms_array
if self.answer_sequence_key_norms_array is not None
else self.answer_sequence_key_norms or [],
"answer_sequence_similarity_keys": self.answer_sequence_similarity_keys_array
if self.answer_sequence_similarity_keys_array is not None
else [],
"answer_sequence_similarity_key_norms": self.answer_sequence_similarity_key_norms_array
if self.answer_sequence_similarity_key_norms_array is not None
else [],
"answer_sequence_prompt_tokens": self.answer_sequence_prompt_tokens if self.answer_sequence_prompt_tokens is not None else [],
"answer_sequence_tokens": self.answer_sequence_tokens if self.answer_sequence_tokens is not None else [],
"answer_fingerprint_hashes": self._answer_fingerprint_tensor(),
**transition_tensors,
}
write_safetensor_file(path, tensors, metadata=metadata)
@classmethod
def load(cls, path: str | Path) -> "ReframrModel":
checkpoint_path = Path(path)
checkpoint = read_safetensor_file(
checkpoint_path,
arrays=np is not None and checkpoint_path.stat().st_size > 10_000_000,
)
metadata = checkpoint.metadata
config = ReframrConfig.from_dict(json.loads(metadata["config"]))
model = cls(config)
model.tokenizer = NativeTokenizer.from_dict(json.loads(metadata["tokenizer"]))
id_to_token = [str(token) for token in json.loads(metadata["embedding_id_to_token"])]
embedding_table = checkpoint.tensors["embedding_table"]
if np is not None and hasattr(embedding_table, "shape"):
embeddings = embedding_table.astype(RUNTIME_ARRAY_DTYPE, copy=False)
else:
embeddings = [[float(value) for value in row] for row in embedding_table]
model.embedding_model = EmbeddingModel(
token_to_id={token: index for index, token in enumerate(id_to_token)},
id_to_token=id_to_token,
embeddings=embeddings,
ppmi_matrix=[],
)
model.memory_units = [
AnalyticalMemoryUnit(model.config.state_dim, timescale)
for timescale in model.config.timescales
]
model.ternary_scale = float(checkpoint.tensors["ternary_scale"][0])
model.ternary_mask = [int(value) for value in checkpoint.tensors["ternary_mask"]]
readout_tensor = checkpoint.tensors["readout_weights"]
model.readout_weights = (
readout_tensor.astype(RUNTIME_ARRAY_DTYPE, copy=False)
if np is not None and hasattr(readout_tensor, "shape")
else [[float(value) for value in row] for row in readout_tensor]
)
readout_bias_tensor = checkpoint.tensors.get("readout_bias", [])
model.readout_bias = [
float(value) for value in (
readout_bias_tensor.tolist()
if hasattr(readout_bias_tensor, "tolist")
else readout_bias_tensor
)
]
if not model.readout_bias:
model.readout_bias = [0.0 for _ in id_to_token]
prompt_answer_tensor = checkpoint.tensors.get("prompt_answer_weights", [])
model.prompt_answer_weights = (
prompt_answer_tensor.astype(RUNTIME_ARRAY_DTYPE, copy=False)
if np is not None
and hasattr(prompt_answer_tensor, "shape")
and len(prompt_answer_tensor.shape) == 2
else [[float(value) for value in row] for row in prompt_answer_tensor]
)
prompt_answer_bias_tensor = checkpoint.tensors.get("prompt_answer_bias", [])
model.prompt_answer_bias = [
float(value) for value in (
prompt_answer_bias_tensor.tolist()
if hasattr(prompt_answer_bias_tensor, "tolist")
else prompt_answer_bias_tensor
)
]
if not model.prompt_answer_bias:
model.prompt_answer_bias = [0.0 for _ in id_to_token]
prompt_answer_start_tensor = checkpoint.tensors.get("prompt_answer_start_weights", [])
model.prompt_answer_start_weights = (
prompt_answer_start_tensor.astype(RUNTIME_ARRAY_DTYPE, copy=False)
if np is not None
and hasattr(prompt_answer_start_tensor, "shape")
and len(prompt_answer_start_tensor.shape) == 2
else [[float(value) for value in row] for row in prompt_answer_start_tensor]
)
prompt_answer_start_bias_tensor = checkpoint.tensors.get("prompt_answer_start_bias", [])
model.prompt_answer_start_bias = [
float(value) for value in (
prompt_answer_start_bias_tensor.tolist()
if hasattr(prompt_answer_start_bias_tensor, "tolist")
else prompt_answer_start_bias_tensor
)
]
if not model.prompt_answer_start_bias:
model.prompt_answer_start_bias = [0.0 for _ in id_to_token]
trace_weight_tensor = checkpoint.tensors.get("trace_token_weights", [])
model.trace_token_weights = [
float(value) for value in (
trace_weight_tensor.tolist()
if hasattr(trace_weight_tensor, "tolist")
else trace_weight_tensor
)
]
if not model.trace_token_weights:
model.trace_token_weights = [
1.0 if token in TOOL_PROTOCOL_TOKENS else 0.0 if token in model.tokenizer.special_tokens else 1.0
for token in id_to_token
]
preference_bias_tensor = checkpoint.tensors.get("preference_bias", [])
model.preference_bias = [
float(value) for value in (
preference_bias_tensor.tolist()
if hasattr(preference_bias_tensor, "tolist")
else preference_bias_tensor
)
]
if not model.preference_bias:
model.preference_bias = [0.0 for _ in id_to_token]
state_offset_tensor = checkpoint.tensors.get("state_offset", [])
model.state_offset = [
float(value) for value in (
state_offset_tensor.tolist()
if hasattr(state_offset_tensor, "tolist")
else state_offset_tensor
)
]
if not model.state_offset:
model.state_offset = [0.0 for _ in range(model._combined_state_width())]
def _runtime_vector_tensor(name: str) -> object | None:
tensor = checkpoint.tensors.get(name, [])
if np is not None and hasattr(tensor, "shape"):
if len(tensor.shape) == 1 and int(tensor.shape[0]) > 0:
return tensor.astype(RUNTIME_ARRAY_DTYPE, copy=False)
return None
values = tensor.tolist() if hasattr(tensor, "tolist") else tensor
return [float(value) for value in values] if values else None
def _runtime_matrix_tensor(name: str) -> object | None:
tensor = checkpoint.tensors.get(name, [])
if (
np is not None
and hasattr(tensor, "shape")
and len(tensor.shape) == 2
and int(tensor.shape[0]) > 0
):
return tensor.astype(RUNTIME_ARRAY_DTYPE, copy=False)
return None
associative_tensor = checkpoint.tensors.get("associative_keys", [])
model.associative_keys = (
associative_tensor.astype(RUNTIME_ARRAY_DTYPE, copy=False)
if np is not None and hasattr(associative_tensor, "shape")
else [[float(value) for value in row] for row in associative_tensor]
)
cached_associative_key_norms = _runtime_vector_tensor("associative_key_norms")
if cached_associative_key_norms is not None:
model.associative_key_norms = cached_associative_key_norms
elif np is not None and hasattr(model.associative_keys, "shape"):
model.associative_key_norms = None
else:
model.associative_key_norms = [norm(key) for key in model.associative_keys]
raw_associative_values = checkpoint.tensors.get("associative_values", [])
model.associative_values = [
int(value) for value in (
raw_associative_values.tolist()
if hasattr(raw_associative_values, "tolist")
else raw_associative_values
)
]
answer_tensor = checkpoint.tensors.get("answer_keys", [])
if np is not None and hasattr(answer_tensor, "shape"):
model.answer_keys = (
answer_tensor.astype(RUNTIME_ARRAY_DTYPE, copy=False)
if len(answer_tensor.shape) == 2
else []
)
else:
model.answer_keys = [[float(value) for value in row] for row in answer_tensor]
if (
np is not None
and hasattr(model.answer_keys, "shape")
and len(model.answer_keys.shape) == 2
):
model.answer_key_norms = _runtime_vector_tensor("answer_key_norms")
else:
model.answer_key_norms = (
_runtime_vector_tensor("answer_key_norms")
or [norm(key) for key in model.answer_keys]
)
raw_answer_values = checkpoint.tensors.get("answer_values", [])
model.answer_values = [
int(value) for value in (
raw_answer_values.tolist()
if hasattr(raw_answer_values, "tolist")
else raw_answer_values
)
]
answer_start_tensor = checkpoint.tensors.get("answer_start_keys", [])
if np is not None and hasattr(answer_start_tensor, "shape"):
model.answer_start_keys = (
answer_start_tensor.astype(RUNTIME_ARRAY_DTYPE, copy=False)
if len(answer_start_tensor.shape) == 2
else []
)
else:
model.answer_start_keys = [
[float(value) for value in row] for row in answer_start_tensor
]
if (
np is not None
and hasattr(model.answer_start_keys, "shape")
and len(model.answer_start_keys.shape) == 2
):
model.answer_start_key_norms = _runtime_vector_tensor("answer_start_key_norms")
else:
model.answer_start_key_norms = (
_runtime_vector_tensor("answer_start_key_norms")
or [norm(key) for key in model.answer_start_keys]
)
raw_answer_start_values = checkpoint.tensors.get("answer_start_values", [])
model.answer_start_values = [
int(value) for value in (
raw_answer_start_values.tolist()
if hasattr(raw_answer_start_values, "tolist")
else raw_answer_start_values
)
]
answer_sequence_tensor = checkpoint.tensors.get("answer_sequence_keys", [])
if np is not None and hasattr(answer_sequence_tensor, "shape"):
model.answer_sequence_keys = (
answer_sequence_tensor.astype(RUNTIME_ARRAY_DTYPE, copy=False)
if len(answer_sequence_tensor.shape) == 2
else []
)
else:
model.answer_sequence_keys = [
[float(value) for value in row] for row in answer_sequence_tensor
]
if (
np is not None
and hasattr(model.answer_sequence_keys, "shape")
and len(model.answer_sequence_keys.shape) == 2
):
model.answer_sequence_key_norms = _runtime_vector_tensor("answer_sequence_key_norms")
else:
model.answer_sequence_key_norms = (
_runtime_vector_tensor("answer_sequence_key_norms")
or [norm(key) for key in model.answer_sequence_keys]
)
raw_answer_sequence_prompt_tokens = checkpoint.tensors.get("answer_sequence_prompt_tokens", [])
if np is not None and hasattr(raw_answer_sequence_prompt_tokens, "shape"):
model.answer_sequence_prompt_tokens = raw_answer_sequence_prompt_tokens.astype(int, copy=False)
else:
model.answer_sequence_prompt_tokens = [
[int(value) for value in row] for row in raw_answer_sequence_prompt_tokens
]
raw_answer_sequence_tokens = checkpoint.tensors.get("answer_sequence_tokens", [])
if np is not None and hasattr(raw_answer_sequence_tokens, "shape"):
model.answer_sequence_tokens = raw_answer_sequence_tokens.astype(int, copy=False)
else:
model.answer_sequence_tokens = [
[int(value) for value in row] for row in raw_answer_sequence_tokens
]
model.answer_sequence_token_id_rows = None
raw_fingerprints = checkpoint.tensors.get("answer_fingerprint_hashes", [])
model.answer_fingerprint_hashes = model._coerce_answer_fingerprint_hashes(
raw_fingerprints
)
model.answer_fingerprint_token_lengths = None
model.answer_fingerprint_token_sequences_by_length = None
if not model.answer_fingerprint_hashes:
model._refresh_answer_fingerprint_hashes()
model.answer_similarity_keys_array = _runtime_matrix_tensor("answer_similarity_keys")
model.answer_similarity_key_norms_array = _runtime_vector_tensor("answer_similarity_key_norms")
model.answer_start_similarity_keys_array = _runtime_matrix_tensor("answer_start_similarity_keys")
model.answer_start_similarity_key_norms_array = _runtime_vector_tensor("answer_start_similarity_key_norms")
model.answer_sequence_similarity_keys_array = _runtime_matrix_tensor("answer_sequence_similarity_keys")
model.answer_sequence_similarity_key_norms_array = _runtime_vector_tensor("answer_sequence_similarity_key_norms")
model.transition_id_tables = model._deserialize_transition_id_tables_from_tensors(
checkpoint.tensors
)
if model.transition_id_tables is not None:
model.transition_tables = {order: {} for order in sorted(TRANSITION_ORDERS)}
else:
model.transition_tables = model._deserialize_transition_tables(
json.loads(metadata.get("transition_tables", "{}"))
)
model._refresh_numeric_caches()
return model
def _collect_training_examples(
self,
tokens: list[str],
) -> tuple[list[Vector], list[Vector], list[int]]:
assert self.embedding_model is not None
if np is not None:
hidden_states = [
np.zeros(self.config.state_dim, dtype=np.float64)
for _ in self.config.timescales
]
context_traces = [
np.zeros(self.config.embedding_dim, dtype=np.float64)
for _ in self.config.timescales
]
zero_embedding: Vector | object = np.zeros(self.config.embedding_dim, dtype=np.float64)
else:
hidden_states = [zeros_vector(self.config.state_dim) for _ in self.config.timescales]
context_traces = [zeros_vector(self.config.embedding_dim) for _ in self.config.timescales]
zero_embedding = zeros_vector(self.config.embedding_dim)
states: list[Vector] = []
labels: list[Vector] = []
label_ids: list[int] = []
token_ids = [
self.embedding_model.token_to_id.get(token, -1)
for token in tokens
]
example_count = max(0, len(tokens) - 1)
stride = 1
if self.config.max_training_examples and example_count > self.config.max_training_examples:
stride = max(
1,
(example_count + self.config.max_training_examples - 1) // self.config.max_training_examples,
)
for index in range(len(tokens) - 1):
token = tokens[index]
token_id = token_ids[index]
embedding = (
self.embedding_model.embeddings[token_id]
if token_id >= 0
else zero_embedding
)
trace_embedding = self._trace_embedding_from_token_id(embedding, token_id)
hidden_states, context_traces, combined_state = self._step_hidden_states_from_embedding(
hidden_states,
context_traces,
embedding,
trace_embedding=trace_embedding,
)
if stride > 1 and index % stride != 0 and index != len(tokens) - 2:
continue
states.append(combined_state)
next_token_id = token_ids[index + 1]
labels.append(self._one_hot_from_id(next_token_id))
label_ids.append(next_token_id)
if self.config.max_training_examples and len(states) > self.config.max_training_examples:
states = states[: self.config.max_training_examples]
labels = labels[: self.config.max_training_examples]
label_ids = label_ids[: self.config.max_training_examples]
return states, labels, label_ids
def _is_punctuation_piece(self, piece: str) -> bool:
return bool(piece) and all(character in string.punctuation for character in piece)
def _encode_context(self, tokens: list[str]) -> Vector:
return self._masked_decode_state(self._build_decode_state(tokens))
def _build_decode_state(self, tokens: list[str]) -> DecodeState:
assert self.memory_units is not None
state = DecodeState(
hidden_states=(
[
np.zeros(self.config.state_dim, dtype=np.float64)
for _ in self.config.timescales
]
if np is not None
else [zeros_vector(self.config.state_dim) for _ in self.config.timescales]
),
context_traces=(
[
np.zeros(self.config.embedding_dim, dtype=np.float64)
for _ in self.config.timescales
]
if np is not None
else [zeros_vector(self.config.embedding_dim) for _ in self.config.timescales]
),
combined_state=self._zero_combined_state(),
context_tokens=[],
)
for token in tokens:
self._advance_decode_state(state, token)
self._apply_sparse_context_anchor(state)
return state
def _advance_decode_state(self, state: DecodeState, token: str) -> DecodeState:
next_hidden_states, next_context_traces, combined_state = self._step_hidden_states(
state.hidden_states,
state.context_traces,
token,
)
state.hidden_states = next_hidden_states
state.context_traces = next_context_traces
state.combined_state = combined_state
state.context_tokens.append(token)
if token == "<answer>":
state.answer_anchor_state = combined_state.copy() if hasattr(combined_state, "copy") else combined_state[:]
state.answer_matches = None
state.answer_start_matches = None
state.answer_sequence_matches = None
state.prompt_answer_prior = None
state.prompt_answer_start_prior = None
return state
def _apply_sparse_context_anchor(self, state: DecodeState) -> None:
if (
np is None
or self.embedding_model is None
or state.answer_anchor_state is None
or not state.context_tokens
):
return
answer_index = _last_index(state.context_tokens, "<answer>")
if answer_index is None or answer_index <= 0:
return
context_ids = self._long_context_sparse_token_ids(state.context_tokens[:answer_index])
if len(context_ids) < SPARSE_CONTEXT_MIN_TOKENS:
return
query_id = context_ids[-1]
embeddings = np.asarray(self.embedding_model.embeddings, dtype=np.float32)
if embeddings.ndim != 2 or embeddings.shape[0] == 0:
return
selector = HashedSparseAttention(
embeddings,
k_neighbors=min(SPARSE_CONTEXT_TOP_K, len(context_ids)),
hash_bits=SPARSE_CONTEXT_HASH_BITS,
probe_radius=SPARSE_CONTEXT_PROBE_RADIUS,
candidate_multiplier=SPARSE_CONTEXT_CANDIDATE_MULTIPLIER,
)
token_ids = np.asarray(context_ids, dtype=np.int64)
selector.build_context_index(token_ids)
selection = selector.select_positions_cached(query_id)
if not selection.positions:
return
selected_ids = token_ids[np.asarray(selection.positions, dtype=np.int64)]
selected_embeddings = embeddings[selected_ids]
scores = np.asarray(selection.scores, dtype=np.float32)
scores -= float(scores.max())
weights = np.exp(scores)
weights /= max(float(weights.sum()), 1e-8)
sparse_embedding = weights @ selected_embeddings
blended_anchor = self._blend_sparse_embedding_into_combined_state(
state.answer_anchor_state,
sparse_embedding,
state_dim=self.config.state_dim,
embedding_dim=self.config.embedding_dim,
timescale_count=len(self.config.timescales),
blend=SPARSE_CONTEXT_TRACE_BLEND,
)
state.answer_anchor_state = blended_anchor
if state.context_tokens and state.context_tokens[-1] == "<answer>":
state.combined_state = blended_anchor.copy()
state.answer_matches = None
state.answer_start_matches = None
state.answer_sequence_matches = None
state.prompt_answer_prior = None
state.prompt_answer_start_prior = None
def _long_context_sparse_token_ids(self, tokens: Sequence[str]) -> list[int]:
assert self.embedding_model is not None
special_tokens = self.tokenizer.special_tokens if self.tokenizer is not None else set()
ids: list[int] = []
for token in tokens:
if token in special_tokens and token not in TOOL_PROTOCOL_TOKENS:
continue
token_id = self._token_id_for_token(token)
if token_id >= 0:
ids.append(token_id)
return ids
@staticmethod
def _blend_sparse_embedding_into_combined_state(
combined_state: Vector,
sparse_embedding: object,
*,
state_dim: int,
embedding_dim: int,
timescale_count: int,
blend: float,
) -> Vector:
if np is None:
return combined_state
state_array = np.asarray(combined_state, dtype=np.float32).copy()
sparse_array = np.asarray(sparse_embedding, dtype=np.float32)
if sparse_array.shape[0] != embedding_dim:
return combined_state
block_width = state_dim + embedding_dim
expected_width = block_width * timescale_count
if state_array.shape[0] != expected_width:
return combined_state
alpha = min(1.0, max(0.0, float(blend)))
for block_index in range(timescale_count):
trace_start = block_index * block_width + state_dim
trace_end = trace_start + embedding_dim
state_array[trace_start:trace_end] = (
(1.0 - alpha) * state_array[trace_start:trace_end]
+ alpha * sparse_array
)
return state_array.tolist()
def _masked_decode_state(self, state: DecodeState) -> Vector:
assert self.ternary_mask is not None
return apply_ternary_mask(state.combined_state, self.ternary_mask, self.ternary_scale)
def _masked_combined_state(self, combined_state: Vector) -> Vector:
assert self.ternary_mask is not None
return apply_ternary_mask(combined_state, self.ternary_mask, self.ternary_scale)
def _masked_decode_state_array(self, state: DecodeState) -> object:
assert np is not None
if self.ternary_mask_array is None:
return np.asarray(self._masked_decode_state(state), dtype=RUNTIME_ARRAY_DTYPE)
return (
np.asarray(state.combined_state, dtype=RUNTIME_ARRAY_DTYPE)
* self.ternary_scale
* self.ternary_mask_array
)
def _masked_combined_state_array(self, combined_state: Vector) -> object:
assert np is not None
if self.ternary_mask_array is None:
return np.asarray(self._masked_combined_state(combined_state), dtype=RUNTIME_ARRAY_DTYPE)
return (
np.asarray(combined_state, dtype=RUNTIME_ARRAY_DTYPE)
* self.ternary_scale
* self.ternary_mask_array
)
def _center_state_vector(self, state: Vector) -> Vector:
if not self.state_offset or len(self.state_offset) != len(state):
return state
return [value - self.state_offset[index] for index, value in enumerate(state)]
def _center_state_array(self, state: object) -> object:
assert np is not None
state_array = np.asarray(state, dtype=RUNTIME_ARRAY_DTYPE)
if self.state_offset_array is None or self.state_offset_array.shape != state_array.shape:
return state_array
return state_array - self.state_offset_array
def _zero_combined_state(self) -> Vector:
return [0.0 for _ in range(self._combined_state_width())]
def _combined_state_width(self) -> int:
return (self.config.state_dim + self.config.embedding_dim) * len(self.config.timescales)
def _derive_trace_token_weights_from_counts(self, token_counts: dict[str, float]) -> Vector:
assert self.embedding_model is not None
assert self.tokenizer is not None
counts = [
float(token_counts.get(token, 0.0))
for token in self.embedding_model.id_to_token
]
positive_counts = sorted(value for value in counts if value > 0.0)
reference = (
positive_counts[len(positive_counts) // 2]
if positive_counts
else 1.0
)
weights: Vector = []
for token, count in zip(self.embedding_model.id_to_token, counts):
if token in TOOL_PROTOCOL_TOKENS:
weights.append(1.0)
elif token in self.tokenizer.special_tokens:
weights.append(0.0)
elif count <= 0.0:
weights.append(1.0)
else:
weight = (reference / count) ** 0.75
weights.append(max(0.08, min(4.8, weight)))
return weights
def _token_id_for_token(self, token: str) -> int:
assert self.embedding_model is not None
token_id = self.embedding_model.token_to_id.get(token)
if token_id is None and token.lower() != token:
token_id = self.embedding_model.token_to_id.get(token.lower())
return int(token_id) if token_id is not None else -1
def _trace_embedding_from_token_id(
self,
embedding: Vector | object,
token_id: int,
) -> Vector | object:
if token_id < 0:
return embedding
if self.trace_embedding_table_array is not None:
return self.trace_embedding_table_array[token_id]
weight = self.trace_token_weights[token_id] if self.trace_token_weights is not None else 1.0
dimension = self.config.embedding_dim
if hasattr(embedding, "shape"):
trace_embedding = embedding * weight
for bucket_multiplier, bucket_offset, sign_multiplier, sign_offset in TRACE_IDENTITY_HASHES:
bucket = (token_id * bucket_multiplier + bucket_offset) % dimension
sign = 1.0 if ((token_id * sign_multiplier + sign_offset) & 1) == 0 else -1.0
trace_embedding[bucket] += weight * TRACE_IDENTITY_SCALE * sign
return trace_embedding
trace_values = [float(value) * weight for value in embedding]
for bucket_multiplier, bucket_offset, sign_multiplier, sign_offset in TRACE_IDENTITY_HASHES:
bucket = (token_id * bucket_multiplier + bucket_offset) % dimension
sign = 1.0 if ((token_id * sign_multiplier + sign_offset) & 1) == 0 else -1.0
trace_values[bucket] += weight * TRACE_IDENTITY_SCALE * sign
return trace_values
def _build_trace_embedding_table_array(self, embedding_array: object) -> object | None:
if np is None or self.trace_token_weights is None:
return None
values = np.asarray(embedding_array, dtype=np.float64)
if values.size == 0 or len(values.shape) != 2:
return None
weights = np.asarray(self.trace_token_weights, dtype=np.float64)
if weights.shape[0] != values.shape[0]:
return None
trace_values = values * weights[:, None]
if values.shape[1] <= 0:
return trace_values
token_ids = np.arange(values.shape[0], dtype=np.int64)
for bucket_multiplier, bucket_offset, sign_multiplier, sign_offset in TRACE_IDENTITY_HASHES:
buckets = ((token_ids * bucket_multiplier + bucket_offset) % values.shape[1]).astype(
np.int64,
copy=False,
)
signs = np.where(
((token_ids * sign_multiplier + sign_offset) & 1) == 0,
1.0,
-1.0,
)
np.add.at(trace_values, (token_ids, buckets), weights * TRACE_IDENTITY_SCALE * signs)
return trace_values
def _runtime_key_norms_array(
self,
key_array: object | None,
key_norms: list[float] | None,
) -> object | None:
assert np is not None
if key_norms is not None and len(key_norms) > 0:
return np.asarray(key_norms, dtype=RUNTIME_ARRAY_DTYPE)
if key_array is None:
return None
keys = np.asarray(key_array, dtype=RUNTIME_ARRAY_DTYPE)
if len(keys.shape) != 2 or keys.shape[0] == 0:
return None
return np.linalg.norm(keys, axis=1).astype(RUNTIME_ARRAY_DTYPE, copy=False)
def _runtime_vector_cache(self, cached: object | None, length: int) -> object | None:
assert np is not None
if cached is None or not hasattr(cached, "shape"):
return None
array = np.asarray(cached, dtype=RUNTIME_ARRAY_DTYPE)
if len(array.shape) != 1 or int(array.shape[0]) != int(length):
return None
return array
def _runtime_matrix_cache(
self,
cached: object | None,
rows: int,
width: int,
) -> object | None:
assert np is not None
if cached is None or not hasattr(cached, "shape"):
return None
array = np.asarray(cached, dtype=RUNTIME_ARRAY_DTYPE)
if (
len(array.shape) != 2
or int(array.shape[0]) != int(rows)
or int(array.shape[1]) != int(width)
):
return None
return array
def _refresh_numeric_caches(self) -> None:
if np is None:
self.ternary_mask_array = None
self.readout_weights_array = None
self.readout_bias_array = None
self.prompt_answer_weights_array = None
self.prompt_answer_bias_array = None
self.prompt_answer_start_weights_array = None
self.prompt_answer_start_bias_array = None
self.trace_token_weights_array = None
self.trace_embedding_table_array = None
self.preference_bias_array = None
self.preference_valid_mask_array = None
self.state_offset_array = None
self.associative_keys_array = None
self.associative_key_norms_array = None
self.associative_values_array = None
self.associative_valid_mask_array = None
self.answer_keys_array = None
self.answer_key_norms_array = None
self.answer_similarity_keys_array = None
self.answer_similarity_key_norms_array = None
self.answer_similarity_mask_array = None
self.answer_values_array = None
self.answer_valid_mask_array = None
self.answer_start_keys_array = None
self.answer_start_key_norms_array = None
self.answer_start_similarity_keys_array = None
self.answer_start_similarity_key_norms_array = None
self.answer_start_values_array = None
self.answer_start_valid_mask_array = None
self.answer_sequence_keys_array = None
self.answer_sequence_key_norms_array = None
self.answer_sequence_similarity_keys_array = None
self.answer_sequence_similarity_key_norms_array = None
self.answer_sequence_prompt_tokens_array = None
self.answer_sequence_tokens_array = None
self.answer_sequence_prompt_weight_maps = None
self.answer_sequence_prompt_weight_norms = None
self.answer_sequence_prompt_bigram_sets = None
self.answer_sequence_prompt_trigram_sets = None
self.answer_sequence_prompt_number_sets = None
self.answer_sequence_prompt_inverted_index = None
self._refresh_answer_sequence_prompt_overlap_cache()
self.prompt_overlap_valid_token_mask_array = None
return
cached_associative_key_norms_array = self.associative_key_norms_array
cached_answer_key_norms_array = self.answer_key_norms_array
cached_answer_similarity_keys_array = self.answer_similarity_keys_array
cached_answer_similarity_key_norms_array = self.answer_similarity_key_norms_array
cached_answer_start_key_norms_array = self.answer_start_key_norms_array
cached_answer_start_similarity_keys_array = self.answer_start_similarity_keys_array
cached_answer_start_similarity_key_norms_array = self.answer_start_similarity_key_norms_array
cached_answer_sequence_key_norms_array = self.answer_sequence_key_norms_array
cached_answer_sequence_similarity_keys_array = self.answer_sequence_similarity_keys_array
cached_answer_sequence_similarity_key_norms_array = self.answer_sequence_similarity_key_norms_array
self.ternary_mask_array = (
np.asarray(self.ternary_mask, dtype=RUNTIME_ARRAY_DTYPE)
if self.ternary_mask is not None
else None
)
self.readout_weights_array = (
np.asarray(self.readout_weights, dtype=RUNTIME_ARRAY_DTYPE)
if self.readout_weights is not None
else None
)
self.readout_bias_array = (
np.asarray(self.readout_bias, dtype=RUNTIME_ARRAY_DTYPE)
if self.readout_bias is not None
else None
)
self.prompt_answer_weights_array = (
np.asarray(self.prompt_answer_weights, dtype=RUNTIME_ARRAY_DTYPE)
if self.prompt_answer_weights is not None
and len(self.prompt_answer_weights) > 0
else None
)
self.prompt_answer_bias_array = (
np.asarray(self.prompt_answer_bias, dtype=RUNTIME_ARRAY_DTYPE)
if self.prompt_answer_bias is not None
else None
)
self.prompt_answer_start_weights_array = (
np.asarray(self.prompt_answer_start_weights, dtype=RUNTIME_ARRAY_DTYPE)
if self.prompt_answer_start_weights is not None
and len(self.prompt_answer_start_weights) > 0
else None
)
self.prompt_answer_start_bias_array = (
np.asarray(self.prompt_answer_start_bias, dtype=RUNTIME_ARRAY_DTYPE)
if self.prompt_answer_start_bias is not None
else None
)
self.trace_token_weights_array = (
np.asarray(self.trace_token_weights, dtype=RUNTIME_ARRAY_DTYPE)
if self.trace_token_weights is not None
else None
)
trace_embedding_table = (
self._build_trace_embedding_table_array(self.embedding_model.embeddings)
if self.embedding_model is not None and self.trace_token_weights is not None
else None
)
self.trace_embedding_table_array = (
trace_embedding_table.astype(RUNTIME_ARRAY_DTYPE, copy=False)
if trace_embedding_table is not None
else None
)
self.preference_bias_array = (
np.asarray(self.preference_bias, dtype=RUNTIME_ARRAY_DTYPE)
if self.preference_bias is not None
else None
)
self.preference_valid_mask_array = (
np.asarray(
[
self._eligible_preference_token(token)
for token in self.embedding_model.id_to_token
],
dtype=bool,
)
if self.embedding_model is not None and self.tokenizer is not None
else None
)
self.state_offset_array = (
np.asarray(self.state_offset, dtype=RUNTIME_ARRAY_DTYPE)
if self.state_offset is not None
else None
)
self.associative_keys_array = (
np.asarray(self.associative_keys, dtype=RUNTIME_ARRAY_DTYPE)
if self.associative_keys is not None and len(self.associative_keys) > 0
else None
)
associative_key_norms_cache = (
self._runtime_vector_cache(
cached_associative_key_norms_array,
int(self.associative_keys_array.shape[0]),
)
if self.associative_keys_array is not None
else None
)
self.associative_key_norms_array = (
associative_key_norms_cache
if associative_key_norms_cache is not None
else self._runtime_key_norms_array(
self.associative_keys_array,
self.associative_key_norms,
)
)
self.associative_values_array = (
np.asarray(self.associative_values, dtype=np.int64)
if self.associative_values is not None and len(self.associative_values) > 0
else None
)
self.associative_valid_mask_array = (
self.associative_values_array >= 0
if self.associative_values_array is not None
else None
)
self.answer_keys_array = (
np.asarray(self.answer_keys, dtype=RUNTIME_ARRAY_DTYPE)
if self.answer_keys is not None and len(self.answer_keys) > 0
else None
)
answer_key_norms_cache = (
self._runtime_vector_cache(
cached_answer_key_norms_array,
int(self.answer_keys_array.shape[0]),
)
if self.answer_keys_array is not None
else None
)
self.answer_key_norms_array = (
answer_key_norms_cache
if answer_key_norms_cache is not None
else self._runtime_key_norms_array(
self.answer_keys_array,
self.answer_key_norms,
)
)
self.answer_similarity_keys_array = None
self.answer_similarity_key_norms_array = None
self.answer_similarity_mask_array = None
if self.answer_keys_array is not None and len(self.answer_keys_array.shape) == 2:
width = int(self.answer_keys_array.shape[1])
block_width = self.config.state_dim + self.config.embedding_dim
expected_width = block_width * len(self.config.timescales)
if block_width > 0 and width == expected_width:
mask = np.zeros(width, dtype=RUNTIME_ARRAY_DTYPE)
for scale_index in range(len(self.config.timescales)):
start = scale_index * block_width + self.config.state_dim
end = start + self.config.embedding_dim
mask[start:end] = 1.0
self.answer_similarity_mask_array = mask
answer_similarity_keys_cache = self._runtime_matrix_cache(
cached_answer_similarity_keys_array,
int(self.answer_keys_array.shape[0]),
width,
)
answer_similarity_key_norms_cache = self._runtime_vector_cache(
cached_answer_similarity_key_norms_array,
int(self.answer_keys_array.shape[0]),
)
if (
answer_similarity_keys_cache is not None
and answer_similarity_key_norms_cache is not None
):
self.answer_similarity_keys_array = answer_similarity_keys_cache
self.answer_similarity_key_norms_array = answer_similarity_key_norms_cache
else:
self.answer_similarity_keys_array = self.answer_keys_array * mask[None, :]
self.answer_similarity_key_norms_array = np.linalg.norm(
self.answer_similarity_keys_array,
axis=1,
).astype(RUNTIME_ARRAY_DTYPE, copy=False)
self.answer_values_array = (
np.asarray(self.answer_values, dtype=np.int64)
if self.answer_values is not None and len(self.answer_values) > 0
else None
)
self.answer_valid_mask_array = (
self.answer_values_array >= 0
if self.answer_values_array is not None
else None
)
self.answer_start_keys_array = (
np.asarray(self.answer_start_keys, dtype=RUNTIME_ARRAY_DTYPE)
if self.answer_start_keys is not None and len(self.answer_start_keys) > 0
else None
)
answer_start_key_norms_cache = (
self._runtime_vector_cache(
cached_answer_start_key_norms_array,
int(self.answer_start_keys_array.shape[0]),
)
if self.answer_start_keys_array is not None
else None
)
self.answer_start_key_norms_array = (
answer_start_key_norms_cache
if answer_start_key_norms_cache is not None
else self._runtime_key_norms_array(
self.answer_start_keys_array,
self.answer_start_key_norms,
)
)
self.answer_start_similarity_keys_array = None
self.answer_start_similarity_key_norms_array = None
if (
self.answer_start_keys_array is not None
and len(self.answer_start_keys_array.shape) == 2
and self.answer_similarity_mask_array is not None
and int(self.answer_start_keys_array.shape[1]) == int(self.answer_similarity_mask_array.shape[0])
):
answer_start_similarity_keys_cache = self._runtime_matrix_cache(
cached_answer_start_similarity_keys_array,
int(self.answer_start_keys_array.shape[0]),
int(self.answer_start_keys_array.shape[1]),
)
answer_start_similarity_key_norms_cache = self._runtime_vector_cache(
cached_answer_start_similarity_key_norms_array,
int(self.answer_start_keys_array.shape[0]),
)
if (
answer_start_similarity_keys_cache is not None
and answer_start_similarity_key_norms_cache is not None
):
self.answer_start_similarity_keys_array = answer_start_similarity_keys_cache
self.answer_start_similarity_key_norms_array = answer_start_similarity_key_norms_cache
else:
self.answer_start_similarity_keys_array = (
self.answer_start_keys_array * self.answer_similarity_mask_array[None, :]
)
self.answer_start_similarity_key_norms_array = np.linalg.norm(
self.answer_start_similarity_keys_array,
axis=1,
).astype(RUNTIME_ARRAY_DTYPE, copy=False)
self.answer_start_values_array = (
np.asarray(self.answer_start_values, dtype=np.int64)
if self.answer_start_values is not None and len(self.answer_start_values) > 0
else None
)
self.answer_start_valid_mask_array = (
self.answer_start_values_array >= 0
if self.answer_start_values_array is not None
else None
)
self.answer_sequence_keys_array = (
np.asarray(self.answer_sequence_keys, dtype=RUNTIME_ARRAY_DTYPE)
if self.answer_sequence_keys is not None and len(self.answer_sequence_keys) > 0
else None
)
answer_sequence_key_norms_cache = (
self._runtime_vector_cache(
cached_answer_sequence_key_norms_array,
int(self.answer_sequence_keys_array.shape[0]),
)
if self.answer_sequence_keys_array is not None
else None
)
self.answer_sequence_key_norms_array = (
answer_sequence_key_norms_cache
if answer_sequence_key_norms_cache is not None
else self._runtime_key_norms_array(
self.answer_sequence_keys_array,
self.answer_sequence_key_norms,
)
)
self.answer_sequence_similarity_keys_array = None
self.answer_sequence_similarity_key_norms_array = None
if (
self.answer_sequence_keys_array is not None
and len(self.answer_sequence_keys_array.shape) == 2
and self.answer_similarity_mask_array is not None
and int(self.answer_sequence_keys_array.shape[1]) == int(self.answer_similarity_mask_array.shape[0])
):
answer_sequence_similarity_keys_cache = self._runtime_matrix_cache(
cached_answer_sequence_similarity_keys_array,
int(self.answer_sequence_keys_array.shape[0]),
int(self.answer_sequence_keys_array.shape[1]),
)
answer_sequence_similarity_key_norms_cache = self._runtime_vector_cache(
cached_answer_sequence_similarity_key_norms_array,
int(self.answer_sequence_keys_array.shape[0]),
)
if (
answer_sequence_similarity_keys_cache is not None
and answer_sequence_similarity_key_norms_cache is not None
):
self.answer_sequence_similarity_keys_array = answer_sequence_similarity_keys_cache
self.answer_sequence_similarity_key_norms_array = answer_sequence_similarity_key_norms_cache
else:
self.answer_sequence_similarity_keys_array = (
self.answer_sequence_keys_array * self.answer_similarity_mask_array[None, :]
)
self.answer_sequence_similarity_key_norms_array = np.linalg.norm(
self.answer_sequence_similarity_keys_array,
axis=1,
).astype(RUNTIME_ARRAY_DTYPE, copy=False)
self.answer_sequence_tokens_array = (
np.asarray(self.answer_sequence_tokens, dtype=np.int64)
if self.answer_sequence_tokens is not None and len(self.answer_sequence_tokens) > 0
else None
)
self.answer_sequence_prompt_tokens_array = (
np.asarray(self.answer_sequence_prompt_tokens, dtype=np.int64)
if self.answer_sequence_prompt_tokens is not None
and len(self.answer_sequence_prompt_tokens) > 0
else None
)
self.prompt_overlap_valid_token_mask_array = None
if not self._defer_answer_sequence_prompt_overlap_cache():
self._refresh_answer_sequence_prompt_overlap_cache()
else:
self._refresh_answer_sequence_prompt_overlap_cache()
def _defer_answer_sequence_prompt_overlap_cache(self) -> bool:
if self.answer_sequence_prompt_tokens is None:
return False
try:
row_count = len(self.answer_sequence_prompt_tokens)
except TypeError:
return False
return (
row_count > ANSWER_SEQUENCE_EAGER_OVERLAP_CACHE_LIMIT
and np is not None
and self.answer_sequence_prompt_tokens_array is not None
)
def _prompt_overlap_valid_token_mask(self) -> object | None:
if np is None or self.embedding_model is None:
return None
if (
self.prompt_overlap_valid_token_mask_array is not None
and int(self.prompt_overlap_valid_token_mask_array.shape[0]) == len(self.embedding_model.id_to_token)
):
return self.prompt_overlap_valid_token_mask_array
mask = np.fromiter(
(
not self._should_skip_prompt_overlap_token(token)
for token in self.embedding_model.id_to_token
),
dtype=bool,
count=len(self.embedding_model.id_to_token),
)
self.prompt_overlap_valid_token_mask_array = mask
return mask
def _answer_prompt_row_ids_from_array(self) -> tuple[dict[int, list[int]], list[list[int]] | None] | None:
if (
np is None
or self.answer_sequence_prompt_tokens_array is None
or self.trace_token_weights is None
or self.embedding_model is None
):
return None
rows = np.asarray(self.answer_sequence_prompt_tokens_array, dtype=np.int64)
if len(rows.shape) != 2 or rows.size == 0:
return {}, [] if rows.shape[0] <= ANSWER_SEQUENCE_EAGER_OVERLAP_CACHE_LIMIT else None
vocab_size = len(self.trace_token_weights)
if vocab_size <= 0:
return {}, [] if rows.shape[0] <= ANSWER_SEQUENCE_EAGER_OVERLAP_CACHE_LIMIT else None
valid_token_mask = self._prompt_overlap_valid_token_mask()
if valid_token_mask is None:
return None
bounded = (rows >= 0) & (rows < vocab_size)
clipped = np.clip(rows, 0, max(0, vocab_size - 1))
bounded &= valid_token_mask[clipped]
row_positions, column_positions = np.nonzero(bounded)
if row_positions.size == 0:
empty_rows = [[] for _ in range(int(rows.shape[0]))] if rows.shape[0] <= ANSWER_SEQUENCE_EAGER_OVERLAP_CACHE_LIMIT else None
return {}, empty_rows
token_values = rows[row_positions, column_positions].astype(np.int64, copy=False)
order = np.lexsort((row_positions, token_values))
token_values = token_values[order]
row_positions = row_positions[order]
unique = np.ones(token_values.shape[0], dtype=bool)
unique[1:] = (token_values[1:] != token_values[:-1]) | (row_positions[1:] != row_positions[:-1])
token_values = token_values[unique]
row_positions = row_positions[unique]
boundaries = np.flatnonzero(token_values[1:] != token_values[:-1]) + 1
token_groups = np.split(token_values, boundaries)
row_groups = np.split(row_positions, boundaries)
inverted = {
int(token_group[0]): row_group.astype(np.int64, copy=False).tolist()
for token_group, row_group in zip(token_groups, row_groups)
if token_group.size
}
if rows.shape[0] > ANSWER_SEQUENCE_EAGER_OVERLAP_CACHE_LIMIT:
return inverted, None
row_id_lists: list[list[int]] = [[] for _ in range(int(rows.shape[0]))]
for token_id, row_index in zip(token_values.tolist(), row_positions.tolist()):
row_id_lists[int(row_index)].append(int(token_id))
return inverted, row_id_lists
def _refresh_answer_sequence_prompt_overlap_cache(self) -> None:
self.answer_sequence_prompt_weight_maps = None
self.answer_sequence_prompt_weight_norms = None
self.answer_sequence_prompt_bigram_sets = None
self.answer_sequence_prompt_trigram_sets = None
self.answer_sequence_prompt_number_sets = None
self.answer_sequence_prompt_inverted_index = None
self.answer_sequence_prompt_specificity = None
if self.answer_sequence_prompt_tokens is None or self.trace_token_weights is None:
return
array_index = self._answer_prompt_row_ids_from_array()
if array_index is not None:
inverted, row_id_lists = array_index
total_rows = (
int(self.answer_sequence_prompt_tokens_array.shape[0])
if self.answer_sequence_prompt_tokens_array is not None
else len(row_id_lists or [])
)
else:
inverted = {}
row_id_lists = []
for row in self.answer_sequence_prompt_tokens:
row_values = row.tolist() if hasattr(row, "tolist") else row
row_ids: list[int] = []
for raw_token_id in row_values:
token_id = int(raw_token_id)
if token_id < 0 or token_id >= len(self.trace_token_weights):
continue
if self.embedding_model is not None and self._should_skip_prompt_overlap_token(
self.embedding_model.id_to_token[token_id]
):
continue
row_ids.append(token_id)
sequence_index = len(row_id_lists)
for token_id in set(row_ids):
inverted.setdefault(token_id, []).append(sequence_index)
row_id_lists.append(row_ids)
total_rows = len(row_id_lists)
specificity = {
token_id: self._prompt_overlap_token_specificity(len(indices), total_rows)
for token_id, indices in inverted.items()
}
self.answer_sequence_prompt_inverted_index = inverted
self.answer_sequence_prompt_specificity = specificity
if total_rows > ANSWER_SEQUENCE_EAGER_OVERLAP_CACHE_LIMIT:
return
if row_id_lists is None:
return
weight_maps: list[dict[int, float]] = []
weight_norms: list[float] = []
bigram_sets: list[set[tuple[int, int]]] = []
trigram_sets: list[set[tuple[int, int, int]]] = []
number_sets: list[set[str]] = []
for row_index, row_ids in enumerate(row_id_lists):
row_weights: dict[int, float] = {}
for token_id in row_ids:
row_weights[token_id] = max(
row_weights.get(token_id, 0.0),
float(self.trace_token_weights[token_id]) * specificity.get(token_id, 1.0),
)
weight_maps.append(row_weights)
weight_norms.append(sum(value * value for value in row_weights.values()) ** 0.5)
bigram_sets.append(
{
(row_ids[index], row_ids[index + 1])
for index in range(len(row_ids) - 1)
}
)
trigram_sets.append(
{
(row_ids[index], row_ids[index + 1], row_ids[index + 2])
for index in range(len(row_ids) - 2)
}
)
raw_row = self.answer_sequence_prompt_tokens[row_index]
raw_values = raw_row.tolist() if hasattr(raw_row, "tolist") else raw_row
raw_ids = [
int(value)
for value in raw_values
if 0 <= int(value) < len(self.embedding_model.id_to_token)
]
number_sets.append(self._number_strings_from_token_ids(raw_ids))
self.answer_sequence_prompt_weight_maps = weight_maps
self.answer_sequence_prompt_weight_norms = weight_norms
self.answer_sequence_prompt_bigram_sets = bigram_sets
self.answer_sequence_prompt_trigram_sets = trigram_sets
self.answer_sequence_prompt_number_sets = number_sets
@staticmethod
def _prompt_overlap_token_specificity(document_frequency: int, total_documents: int) -> float:
if document_frequency <= 0 or total_documents <= 0:
return 1.0
coverage = min(1.0, document_frequency / total_documents)
return max(0.02, 1.0 - (coverage ** 0.5))
def _number_strings_from_token_ids(self, token_ids: list[int]) -> set[str]:
assert self.embedding_model is not None
tokens = [
self.embedding_model.id_to_token[token_id]
for token_id in token_ids
if 0 <= token_id < len(self.embedding_model.id_to_token)
]
return self._number_strings_from_tokens(tokens)
def _number_strings_from_tokens(self, tokens: list[str]) -> set[str]:
numbers: set[str] = set()
current = ""
for token in tokens:
if self.tokenizer is not None and token in self.tokenizer.special_tokens:
if current:
numbers.add(current)
current = ""
continue
rendered = self._render_token(token)
digits = "".join(character for character in rendered if character.isdigit())
starts_number = self._starts_new_word(token) if self.tokenizer is not None else True
if digits and starts_number:
if current:
numbers.add(current)
current = digits
elif digits and current:
current += digits
else:
if current:
numbers.add(current)
current = ""
if current:
numbers.add(current)
return numbers
@staticmethod
def _numeric_prompt_can_match(query_numbers: set[str], row_numbers: set[str]) -> bool:
if not query_numbers:
return True
if not row_numbers:
return False
return query_numbers.issubset(row_numbers)
def _vector_answer_sequence_candidate_indices(
self,
query_token_ids: object,
) -> list[int] | None:
if (
np is None
or self.answer_sequence_prompt_tokens_array is None
or not hasattr(self.answer_sequence_prompt_tokens_array, "shape")
):
return None
query_ids = np.asarray(list(query_token_ids), dtype=np.int64)
if query_ids.size == 0:
return []
prompt_array = self.answer_sequence_prompt_tokens_array
if len(prompt_array.shape) != 2 or prompt_array.shape[0] == 0:
return None
mask = np.isin(prompt_array, query_ids).any(axis=1)
return [int(index) for index in np.flatnonzero(mask)]
def _vector_answer_sequence_local_frequency(
self,
token_id: int,
candidate_indices: list[int],
) -> int | None:
if (
np is None
or self.answer_sequence_prompt_tokens_array is None
or not hasattr(self.answer_sequence_prompt_tokens_array, "shape")
or not candidate_indices
):
return None
rows = self.answer_sequence_prompt_tokens_array[
np.asarray(candidate_indices, dtype=np.int64)
]
return int(np.any(rows == int(token_id), axis=1).sum())
def _apply_readout_fast(self, state: Vector) -> Vector:
if self.readout_weights_array is None or np is None:
assert self.readout_weights is not None
centered_state = self._center_state_vector(state)
logits = apply_readout(self.readout_weights, centered_state)
if self.readout_bias:
logits = [
value + self.readout_bias[index]
for index, value in enumerate(logits)
]
return logits
state_array = np.asarray(state, dtype=RUNTIME_ARRAY_DTYPE)
if self.state_offset_array is not None and self.state_offset_array.shape == state_array.shape:
state_array = state_array - self.state_offset_array
logits = self.readout_weights_array @ state_array
if self.readout_bias_array is not None and self.readout_bias_array.shape == logits.shape:
logits = logits + self.readout_bias_array
return logits.tolist()
def _apply_readout_array(self, state: object) -> object:
assert np is not None
assert self.readout_weights_array is not None
state_array = np.asarray(state, dtype=RUNTIME_ARRAY_DTYPE)
if self.state_offset_array is not None and self.state_offset_array.shape == state_array.shape:
state_array = state_array - self.state_offset_array
logits = self.readout_weights_array @ state_array
if self.readout_bias_array is not None and self.readout_bias_array.shape == logits.shape:
logits = logits + self.readout_bias_array
return logits
def _step_hidden_states(
self,
hidden_states: list[Vector],
context_traces: list[Vector],
token: str,
) -> tuple[list[Vector], list[Vector], Vector]:
assert self.embedding_model is not None
assert self.tokenizer is not None
token_id = self._token_id_for_token(token)
embedding = self.embedding_model.vector(token)
trace_embedding = self._trace_embedding_from_token_id(embedding, token_id)
return self._step_hidden_states_from_embedding(
hidden_states,
context_traces,
embedding,
trace_embedding=trace_embedding,
)
def _step_hidden_states_from_embedding(
self,
hidden_states: list[Vector],
context_traces: list[Vector],
embedding: Vector | object,
*,
trace_embedding: Vector | object | None = None,
) -> tuple[list[Vector], list[Vector], Vector]:
assert self.memory_units is not None
if trace_embedding is None:
trace_embedding = embedding
if np is not None and hidden_states and hasattr(hidden_states[0], "shape"):
embedding_array = (
embedding
if hasattr(embedding, "shape")
else np.asarray(embedding, dtype=np.float64)
)
trace_embedding_array = (
trace_embedding
if hasattr(trace_embedding, "shape")
else np.asarray(trace_embedding, dtype=np.float64)
)
drive = analytical_embedding_drive_fast(embedding_array, self.config.state_dim)
next_states: list[Vector] = []
next_traces: list[Vector] = []
combined_state: Vector = []
for unit, state, trace in zip(self.memory_units, hidden_states, context_traces):
next_state = unit.step_vector_fast(state, drive)
decay = 1.0 / (1.0 + unit.timescale)
next_trace = trace + ((1.0 - decay) * trace_embedding_array)
next_states.append(next_state)
next_traces.append(next_trace)
combined_state.extend(next_state.tolist())
combined_state.extend(next_trace.tolist())
return next_states, next_traces, combined_state
embedding_vector = embedding.tolist() if hasattr(embedding, "tolist") else embedding
trace_embedding_vector = (
trace_embedding.tolist()
if hasattr(trace_embedding, "tolist")
else trace_embedding
)
drive = analytical_embedding_drive(embedding_vector, self.config.state_dim)
next_states: list[Vector] = []
next_traces: list[Vector] = []
combined_state: Vector = []
for unit, state, trace in zip(self.memory_units, hidden_states, context_traces):
next_state = unit.step_vector(state, drive)
decay = 1.0 / (1.0 + unit.timescale)
next_trace = [
previous + ((1.0 - decay) * value)
for previous, value in zip(trace, trace_embedding_vector)
]
next_states.append(next_state)
next_traces.append(next_trace)
combined_state.extend(next_state)
combined_state.extend(next_trace)
return next_states, next_traces, combined_state
def _one_hot(self, token: str) -> Vector:
assert self.embedding_model is not None
return self._one_hot_from_id(self.embedding_model.token_to_id.get(token, -1))
def _one_hot_from_id(self, token_id: int) -> Vector:
assert self.embedding_model is not None
vector = [0.0 for _ in self.embedding_model.id_to_token]
if token_id >= 0:
vector[token_id] = 1.0
return vector
def _blend_probabilities(
self,
base: Vector,
answer: Vector,
associative: Vector,
transition: Vector,
copy: Vector,
source_evidence: Vector,
preference: Vector,
*,
transition_order: int | None,
generated_count: int = 0,
answer_locked: bool = False,
answer_guided_start: bool = False,
copy_guided_start: bool = False,
) -> tuple[Vector, dict[str, float]]:
base_weight = FAST_BASE_BLEND
answer_weight = FAST_ANSWER_BLEND
associative_weight = FAST_ASSOCIATIVE_BLEND
transition_weight = FAST_TRANSITION_BLEND
copy_weight = FAST_COPY_BLEND
source_evidence_weight = FAST_SOURCE_EVIDENCE_BLEND
preference_weight = FAST_PREFERENCE_BLEND
source_grounded = any(value > 0.0 for value in source_evidence)
if answer_locked:
base_weight *= 0.005
answer_weight *= 250.0
associative_weight *= 0.05
transition_weight *= 0.005
copy_weight *= 0.005
source_evidence_weight *= 0.05
preference_weight *= 0.05
elif answer_guided_start:
base_weight *= 0.45
answer_weight *= 3.1
associative_weight *= 0.2
transition_weight *= 0.35
copy_weight *= 0.2
source_evidence_weight *= 1.1
preference_weight *= 0.2
elif copy_guided_start:
base_weight *= 0.55
answer_weight *= 0.35
associative_weight *= 0.4
transition_weight *= 0.35
copy_weight *= 4.5
preference_weight *= 0.6
elif generated_count > 0:
answer_weight *= 0.32
transition_weight *= 2.0
copy_weight *= 0.75
source_evidence_weight *= 0.85
if source_grounded:
base_weight *= 0.45
answer_weight *= 0.35
associative_weight *= 0.50
transition_weight *= 0.25
copy_weight *= 0.50
source_evidence_weight *= 3.50
if source_grounded:
base_weight *= 0.60
answer_weight *= 0.35
associative_weight *= 0.50
transition_weight *= 0.80
copy_weight *= 0.20
source_evidence_weight *= 1.80
else:
source_evidence_weight = 0.0
if transition_order is None:
answer_weight *= 1.1
associative_weight *= 0.75
copy_weight += 0.02
elif transition_order <= 2:
answer_weight *= 1.15
associative_weight *= 0.65
transition_weight *= 0.55
copy_weight += 0.01
elif transition_order >= 5:
transition_weight *= 1.25
sources: list[tuple[str, float, Vector]] = [("base", base_weight, base)]
if any(value > 0.0 for value in answer):
sources.append(("answer", answer_weight, answer))
if any(value > 0.0 for value in associative):
sources.append(("associative", associative_weight, associative))
if any(value > 0.0 for value in transition):
sources.append(("transition", transition_weight, transition))
if any(value > 0.0 for value in copy):
sources.append(("copy", copy_weight, copy))
if any(value > 0.0 for value in source_evidence):
sources.append(("source_evidence", source_evidence_weight, source_evidence))
if any(value > 0.0 for value in preference):
sources.append(("preference", preference_weight, preference))
total_weight = sum(weight for _, weight, _ in sources)
blended = [0.0 for _ in base]
blend_weights: dict[str, float] = {}
for name, weight, source in sources:
normalized_weight = weight / total_weight if total_weight else 0.0
blend_weights[name] = normalized_weight
for index, value in enumerate(source):
blended[index] += normalized_weight * value
return _normalize_vector(blended), blend_weights
def _blend_probability_arrays(
self,
base: object,
answer: object,
associative: object,
transition: object,
copy: object,
source_evidence: object,
preference: object,
*,
transition_order: int | None,
generated_count: int = 0,
answer_locked: bool = False,
answer_guided_start: bool = False,
copy_guided_start: bool = False,
) -> tuple[object, dict[str, float]]:
assert np is not None
base_weight = FAST_BASE_BLEND
answer_weight = FAST_ANSWER_BLEND
associative_weight = FAST_ASSOCIATIVE_BLEND
transition_weight = FAST_TRANSITION_BLEND
copy_weight = FAST_COPY_BLEND
source_evidence_weight = FAST_SOURCE_EVIDENCE_BLEND
preference_weight = FAST_PREFERENCE_BLEND
source_grounded = bool(np.any(source_evidence > 0.0))
if answer_locked:
base_weight *= 0.005
answer_weight *= 250.0
associative_weight *= 0.05
transition_weight *= 0.005
copy_weight *= 0.005
source_evidence_weight *= 0.05
preference_weight *= 0.05
elif answer_guided_start:
base_weight *= 0.45
answer_weight *= 3.1
associative_weight *= 0.2
transition_weight *= 0.35
copy_weight *= 0.2
source_evidence_weight *= 1.1
preference_weight *= 0.2
elif copy_guided_start:
base_weight *= 0.55
answer_weight *= 0.35
associative_weight *= 0.4
transition_weight *= 0.35
copy_weight *= 4.5
preference_weight *= 0.6
elif generated_count > 0:
answer_weight *= 0.32
transition_weight *= 2.0
copy_weight *= 0.75
source_evidence_weight *= 0.85
if source_grounded:
base_weight *= 0.45
answer_weight *= 0.35
associative_weight *= 0.50
transition_weight *= 0.25
copy_weight *= 0.50
source_evidence_weight *= 3.50
if source_grounded:
base_weight *= 0.60
answer_weight *= 0.35
associative_weight *= 0.50
transition_weight *= 0.80
copy_weight *= 0.20
source_evidence_weight *= 1.80
else:
source_evidence_weight = 0.0
if transition_order is None:
answer_weight *= 1.1
associative_weight *= 0.75
copy_weight += 0.02
elif transition_order <= 2:
answer_weight *= 1.15
associative_weight *= 0.65
transition_weight *= 0.55
copy_weight += 0.01
elif transition_order >= 5:
transition_weight *= 1.25
sources: list[tuple[str, float, object]] = [("base", base_weight, base)]
if np.any(answer > 0.0):
sources.append(("answer", answer_weight, answer))
if np.any(associative > 0.0):
sources.append(("associative", associative_weight, associative))
if np.any(transition > 0.0):
sources.append(("transition", transition_weight, transition))
if np.any(copy > 0.0):
sources.append(("copy", copy_weight, copy))
if np.any(source_evidence > 0.0):
sources.append(("source_evidence", source_evidence_weight, source_evidence))
if np.any(preference > 0.0):
sources.append(("preference", preference_weight, preference))
total_weight = sum(weight for _, weight, _ in sources)
blended = np.zeros_like(base, dtype=np.float64)
blend_weights: dict[str, float] = {}
for name, weight, source in sources:
normalized_weight = weight / total_weight if total_weight else 0.0
blend_weights[name] = normalized_weight
blended += normalized_weight * source
total = float(blended.sum())
if total <= 0.0:
return base, blend_weights
return blended / total, blend_weights
def _score_associative_matches(
self,
state: Vector,
*,
limit: int = ASSOCIATIVE_TOP_K,
) -> list[tuple[float, int, int]]:
if (
self.associative_keys is None
or self.associative_values is None
or len(self.associative_keys) == 0
or len(self.associative_values) == 0
):
return []
if (
np is not None
and
self.associative_keys_array is not None
and self.associative_key_norms_array is not None
and self.associative_values_array is not None
and self.associative_valid_mask_array is not None
and limit > 0
):
state_array = self._center_state_array(state).astype(self.associative_keys_array.dtype, copy=False)
state_norm = float(np.linalg.norm(state_array))
if state_norm == 0.0:
return []
numerators = self.associative_keys_array @ state_array
denominators = self.associative_key_norms_array * state_norm
valid_mask = self.associative_valid_mask_array & (denominators > 0.0)
if np.any(valid_mask):
scores = np.zeros_like(numerators, dtype=self.associative_keys_array.dtype)
np.divide(numerators, denominators, out=scores, where=valid_mask)
positive_positions = np.flatnonzero(valid_mask & (scores > 0.0))
if positive_positions.size:
selected_positions = positive_positions
if positive_positions.size > limit:
partition = np.argpartition(scores[positive_positions], -limit)[-limit:]
selected_positions = positive_positions[partition]
ordered_positions = selected_positions[np.argsort(scores[selected_positions])[::-1]]
return [
(
float(scores[position]),
int(self.associative_values_array[position]),
int(position),
)
for position in ordered_positions
]
if self.associative_key_norms is None or len(self.associative_key_norms) == 0:
return []
state = self._center_state_vector(state)
state_norm = norm(state)
if state_norm == 0.0:
return []
scored: list[tuple[float, int, int]] = []
for example_index, (key, key_norm, token_id) in enumerate(
zip(self.associative_keys, self.associative_key_norms, self.associative_values)
):
if token_id < 0:
continue
denominator = state_norm * key_norm
if denominator == 0.0:
continue
similarity = dot(state, key) / denominator
if similarity > 0.0:
scored.append((similarity, token_id, example_index))
scored.sort(key=lambda item: item[0], reverse=True)
return scored[:limit]
def _associative_prior_from_matches(
self,
matches: list[tuple[float, int, int]],
) -> Vector:
assert self.embedding_model is not None
if not matches:
return [0.0 for _ in self.embedding_model.id_to_token]
prior = [0.0 for _ in self.embedding_model.id_to_token]
for similarity, token_id, _ in matches[:ASSOCIATIVE_TOP_K]:
prior[token_id] += similarity
return _normalize_vector(prior)
def _associative_prior(self, state: Vector) -> Vector:
return self._associative_prior_from_matches(self._score_associative_matches(state))
def _score_answer_matches(
self,
answer_anchor_state: Vector | None,
*,
limit: int = ANSWER_TOP_K,
) -> list[tuple[float, int, int]]:
return self._score_prompt_anchor_matches(
answer_anchor_state,
self.answer_keys,
self.answer_key_norms,
self.answer_values,
self.answer_keys_array,
self.answer_key_norms_array,
self.answer_values_array,
self.answer_valid_mask_array,
self.answer_similarity_keys_array,
self.answer_similarity_key_norms_array,
self.answer_similarity_mask_array,
limit=limit,
)
def _score_answer_start_matches(
self,
answer_anchor_state: Vector | None,
*,
limit: int = ANSWER_START_TOP_K,
) -> list[tuple[float, int, int]]:
matches = self._score_prompt_anchor_matches(
answer_anchor_state,
self.answer_start_keys,
self.answer_start_key_norms,
self.answer_start_values,
self.answer_start_keys_array,
self.answer_start_key_norms_array,
self.answer_start_values_array,
self.answer_start_valid_mask_array,
self.answer_start_similarity_keys_array,
self.answer_start_similarity_key_norms_array,
self.answer_similarity_mask_array,
limit=limit,
)
if matches:
return matches
return self._score_prompt_anchor_matches(
answer_anchor_state,
self.answer_start_keys,
self.answer_start_key_norms,
self.answer_start_values,
self.answer_start_keys_array,
self.answer_start_key_norms_array,
self.answer_start_values_array,
self.answer_start_valid_mask_array,
None,
None,
None,
limit=limit,
)
def _score_answer_sequence_matches(
self,
answer_anchor_state: Vector | None,
context_tokens: list[str],
*,
limit: int = ANSWER_START_TOP_K,
) -> list[tuple[float, int, int]]:
if (
answer_anchor_state is None
or self.answer_sequence_keys is None
or self.answer_sequence_key_norms is None
or self.answer_sequence_tokens is None
):
return []
values = list(range(len(self.answer_sequence_tokens)))
values_array = np.arange(len(values), dtype=np.int64) if np is not None else None
anchor_matches = self._score_prompt_anchor_matches(
answer_anchor_state,
self.answer_sequence_keys,
self.answer_sequence_key_norms,
values,
self.answer_sequence_keys_array,
self.answer_sequence_key_norms_array,
values_array,
values_array >= 0 if values_array is not None else None,
self.answer_sequence_similarity_keys_array,
self.answer_sequence_similarity_key_norms_array,
self.answer_similarity_mask_array,
limit=max(limit * 4, limit),
)
overlap_scores = self._answer_sequence_prompt_overlap_scores(context_tokens)
if overlap_scores is None:
return anchor_matches[:limit]
if not overlap_scores:
return []
best_overlap = max(overlap_scores.values()) if overlap_scores else 0.0
overlap_floor = max(0.16, best_overlap * 0.90)
focused_overlap_scores = {
sequence_index: overlap
for sequence_index, overlap in overlap_scores.items()
if overlap >= overlap_floor
}
if not focused_overlap_scores:
focused_overlap_scores = overlap_scores
focused_indices = set(focused_overlap_scores)
merged: dict[int, float] = {}
for similarity, sequence_index, _ in anchor_matches:
if sequence_index not in focused_indices:
continue
merged[sequence_index] = max(merged.get(sequence_index, 0.0), 0.20 * similarity)
for sequence_index, overlap in focused_overlap_scores.items():
merged[sequence_index] = merged.get(sequence_index, 0.0) + (0.80 * overlap)
ranked = [
(score, sequence_index, sequence_index)
for sequence_index, score in merged.items()
if score > 0.0
]
ranked.sort(key=lambda item: item[0], reverse=True)
return ranked[:limit]
def _answer_sequence_prompt_overlap_scores(
self,
context_tokens: list[str],
) -> dict[int, float] | None:
if (
self.embedding_model is None
or self.answer_sequence_prompt_tokens is None
or self.trace_token_weights is None
):
return None
answer_boundary = _last_index(context_tokens, "<answer>")
prompt_tokens = (
context_tokens[:answer_boundary]
if answer_boundary is not None
else context_tokens
)
if (
self.answer_sequence_prompt_specificity is None
and not self._defer_answer_sequence_prompt_overlap_cache()
):
self._refresh_answer_sequence_prompt_overlap_cache()
specificity_map = self.answer_sequence_prompt_specificity or {}
query_weights: dict[int, float] = {}
query_specificity: dict[int, float] = {}
query_segment_multipliers: dict[int, float] = {}
query_content_weight = 0.0
query_ids: list[int] = []
primary_query_ids: list[int] = []
inside_tool_evidence = False
prompt_segment_index = 0
for token in prompt_tokens:
if token in {"<tool_result>", "<source>"}:
inside_tool_evidence = True
continue
if token == "<final>":
inside_tool_evidence = False
continue
if self.tokenizer is not None and token in self.tokenizer.special_tokens:
continue
if self._is_structural_punctuation_token(token):
prompt_segment_index += 1
continue
if self._should_skip_prompt_overlap_token(token):
continue
token_id = self.embedding_model.token_to_id.get(token)
if token_id is None:
continue
query_ids.append(token_id)
specificity = specificity_map.get(token_id, 1.0)
evidence_multiplier = 0.35 if inside_tool_evidence else 1.0
segment_multiplier = evidence_multiplier / (1.0 + prompt_segment_index)
weight = specificity * segment_multiplier
query_weights[token_id] = max(
query_weights.get(token_id, 0.0),
weight,
)
query_specificity[token_id] = max(
query_specificity.get(token_id, 0.0),
specificity,
)
query_segment_multipliers[token_id] = max(
query_segment_multipliers.get(token_id, 0.0),
segment_multiplier,
)
if not inside_tool_evidence:
primary_query_ids.append(token_id)
if specificity >= 0.20:
query_content_weight += weight
if not query_weights:
return None
full_query_token_ids = set(query_ids)
primary_query_token_ids = set(primary_query_ids)
has_tool_evidence = any(token in {"<tool_result>", "<source>"} for token in prompt_tokens)
query_norm = sum(value * value for value in query_weights.values()) ** 0.5
if query_norm <= 0.0:
return None
query_bigrams = {
(query_ids[index], query_ids[index + 1])
for index in range(len(query_ids) - 1)
}
query_trigrams = {
(query_ids[index], query_ids[index + 1], query_ids[index + 2])
for index in range(len(query_ids) - 2)
}
query_numbers = self._number_strings_from_tokens(prompt_tokens)
def ordered_ngram_score(
query_grams: set[tuple[int, ...]],
row_grams: set[tuple[int, ...]],
) -> float:
if not query_grams or not row_grams:
return 0.0
overlap = len(query_grams & row_grams)
if overlap <= 0:
return 0.0
return overlap / ((len(query_grams) * len(row_grams)) ** 0.5)
def prompt_length_fit(row_token_count: int) -> float:
query_token_count = len(full_query_token_ids)
if query_token_count <= 0 or row_token_count <= 0:
return 1.0
if row_token_count <= query_token_count:
return 1.0
extra_fraction = (row_token_count - query_token_count) / row_token_count
return max(0.25, 1.0 - extra_fraction)
cached_maps = self.answer_sequence_prompt_weight_maps
cached_norms = self.answer_sequence_prompt_weight_norms
cached_bigrams = self.answer_sequence_prompt_bigram_sets
cached_trigrams = self.answer_sequence_prompt_trigram_sets
cached_numbers = self.answer_sequence_prompt_number_sets
cached_index = self.answer_sequence_prompt_inverted_index
if (
cached_maps is not None
and cached_norms is not None
and cached_bigrams is not None
and cached_trigrams is not None
and cached_numbers is not None
and len(cached_maps) == len(self.answer_sequence_prompt_tokens)
):
candidate_indices: set[int] | range
if cached_index is not None:
candidates: set[int] = set()
ranked_query_ids = sorted(
query_weights,
key=lambda token_id: specificity_map.get(token_id, 1.0),
reverse=True,
)
distinctive_query_ids = [
token_id
for token_id in ranked_query_ids
if specificity_map.get(token_id, 1.0) >= 0.75
] or ranked_query_ids[:4]
for token_id in distinctive_query_ids:
candidates.update(cached_index.get(token_id, ()))
candidate_indices = candidates if candidates else range(len(cached_maps))
else:
candidate_indices = range(len(cached_maps))
candidate_indices = list(candidate_indices)
if cached_index is not None and candidate_indices:
candidate_set = set(candidate_indices)
local_query_weights: dict[int, float] = {}
local_query_specificity: dict[int, float] = {}
local_query_content_weight = 0.0
for token_id in query_weights:
local_frequency = len(candidate_set & set(cached_index.get(token_id, ())))
if local_frequency <= 0:
continue
specificity = self._prompt_overlap_token_specificity(
local_frequency,
len(candidate_indices),
)
weight = specificity * query_segment_multipliers.get(token_id, 1.0)
local_query_weights[token_id] = weight
local_query_specificity[token_id] = specificity
if specificity >= 0.20:
local_query_content_weight += weight
local_query_norm = sum(value * value for value in local_query_weights.values()) ** 0.5
if local_query_norm > 0.0:
query_weights = local_query_weights
query_specificity = local_query_specificity
query_norm = local_query_norm
scores: dict[int, float] = {}
for sequence_index in candidate_indices:
row_weights = cached_maps[sequence_index]
if not row_weights:
continue
if query_numbers and not self._numeric_prompt_can_match(
query_numbers,
cached_numbers[sequence_index],
):
continue
matched_content_weight = sum(
query_weights[token_id]
for token_id in query_weights.keys() & row_weights.keys()
if query_specificity.get(token_id, 0.0) >= 0.20
)
row_token_coverage = len(query_weights.keys() & row_weights.keys()) / max(
1,
len(row_weights),
)
full_query_coverage = len(full_query_token_ids & row_weights.keys()) / max(
1,
len(full_query_token_ids),
)
primary_query_coverage = len(primary_query_token_ids & row_weights.keys()) / max(
1,
len(primary_query_token_ids),
)
if (
has_tool_evidence
and len(primary_query_token_ids) >= 3
and primary_query_coverage < 0.45
and row_token_coverage < 0.75
):
continue
partial_query_floor = 0.60 if len(full_query_token_ids) < 8 else 0.50
if (
len(full_query_token_ids) >= 5
and full_query_coverage <= partial_query_floor
and row_token_coverage < 0.75
):
continue
if (
len(full_query_token_ids) >= 12
and full_query_coverage < 0.45
and row_token_coverage <= 0.75
):
continue
if (
query_content_weight > 0.0
and matched_content_weight / query_content_weight < 0.40
and row_token_coverage < 0.75
and full_query_coverage < 0.60
):
continue
query_coverage = (
matched_content_weight / query_content_weight
if query_content_weight > 0.0
else row_token_coverage
)
numerator = sum(
query_weights[token_id] * row_weights[token_id]
for token_id in query_weights.keys() & row_weights.keys()
)
if numerator <= 0.0:
continue
row_norm = cached_norms[sequence_index]
if row_norm <= 0.0:
continue
token_score = numerator / (query_norm * row_norm)
bigram_score = ordered_ngram_score(
query_bigrams,
cached_bigrams[sequence_index],
)
trigram_score = ordered_ngram_score(
query_trigrams,
cached_trigrams[sequence_index],
)
scores[sequence_index] = (
(0.35 * token_score)
+ (0.35 * query_coverage)
+ (0.15 * bigram_score)
+ (0.15 * trigram_score)
) * prompt_length_fit(len(row_weights))
return scores
vector_candidate_indices: list[int] | None = None
if cached_index is not None:
candidate_set: set[int] = set()
ranked_query_ids = sorted(
query_weights,
key=lambda token_id: specificity_map.get(token_id, 1.0),
reverse=True,
)
distinctive_query_ids = [
token_id
for token_id in ranked_query_ids
if specificity_map.get(token_id, 1.0) >= 0.75
] or ranked_query_ids[:4]
for token_id in distinctive_query_ids:
candidate_set.update(cached_index.get(token_id, ()))
if not candidate_set:
for token_id in ranked_query_ids:
candidate_set.update(cached_index.get(token_id, ()))
if candidate_set:
break
if not candidate_set:
candidate_indices = range(len(self.answer_sequence_prompt_tokens))
else:
candidate_indices = sorted(candidate_set)
local_query_weights: dict[int, float] = {}
local_query_specificity: dict[int, float] = {}
local_query_content_weight = 0.0
candidate_count = len(candidate_indices)
for token_id in query_weights:
local_frequency = len(candidate_set & set(cached_index.get(token_id, ())))
if local_frequency <= 0:
continue
specificity = self._prompt_overlap_token_specificity(
local_frequency,
candidate_count,
)
local_query_weights[token_id] = specificity * query_segment_multipliers.get(token_id, 1.0)
local_query_specificity[token_id] = specificity
if specificity >= 0.20:
local_query_content_weight += local_query_weights[token_id]
local_query_norm = sum(value * value for value in local_query_weights.values()) ** 0.5
if local_query_norm > 0.0:
query_weights = local_query_weights
query_specificity = local_query_specificity
query_norm = local_query_norm
elif self._defer_answer_sequence_prompt_overlap_cache():
vector_candidate_indices = self._vector_answer_sequence_candidate_indices(
query_weights.keys()
)
if vector_candidate_indices is not None:
if not vector_candidate_indices:
return {}
candidate_indices = vector_candidate_indices
local_query_weights = {}
local_query_specificity = {}
local_query_content_weight = 0.0
candidate_count = len(vector_candidate_indices)
for token_id in query_weights:
local_frequency = self._vector_answer_sequence_local_frequency(
token_id,
vector_candidate_indices,
)
if local_frequency is None or local_frequency <= 0:
continue
specificity = self._prompt_overlap_token_specificity(
local_frequency,
candidate_count,
)
local_query_weights[token_id] = specificity * query_segment_multipliers.get(token_id, 1.0)
local_query_specificity[token_id] = specificity
if specificity >= 0.20:
local_query_content_weight += local_query_weights[token_id]
local_query_norm = sum(value * value for value in local_query_weights.values()) ** 0.5
if local_query_norm > 0.0:
query_weights = local_query_weights
query_specificity = local_query_specificity
query_norm = local_query_norm
else:
candidate_indices = range(len(self.answer_sequence_prompt_tokens))
valid_token_mask = self._prompt_overlap_valid_token_mask()
scores: dict[int, float] = {}
for sequence_index in candidate_indices:
row = self.answer_sequence_prompt_tokens[sequence_index]
row_values = row.tolist() if hasattr(row, "tolist") else row
row_weights: dict[int, float] = {}
row_ids: list[int] = []
raw_row_ids: list[int] = []
for raw_token_id in row_values:
token_id = int(raw_token_id)
if token_id < 0 or token_id >= len(self.trace_token_weights):
continue
raw_row_ids.append(token_id)
if valid_token_mask is not None:
if token_id >= len(valid_token_mask) or not bool(valid_token_mask[token_id]):
continue
elif self._should_skip_prompt_overlap_token(
self.embedding_model.id_to_token[token_id]
):
continue
row_ids.append(token_id)
row_weights[token_id] = max(
row_weights.get(token_id, 0.0),
specificity_map.get(token_id, 1.0),
)
if not row_weights:
continue
if query_numbers and not self._numeric_prompt_can_match(
query_numbers,
self._number_strings_from_token_ids(raw_row_ids),
):
continue
matched_content_weight = sum(
query_weights[token_id]
for token_id in query_weights.keys() & row_weights.keys()
if query_specificity.get(token_id, 0.0) >= 0.20
)
row_token_coverage = len(query_weights.keys() & row_weights.keys()) / max(
1,
len(row_weights),
)
full_query_coverage = len(full_query_token_ids & row_weights.keys()) / max(
1,
len(full_query_token_ids),
)
primary_query_coverage = len(primary_query_token_ids & row_weights.keys()) / max(
1,
len(primary_query_token_ids),
)
if (
has_tool_evidence
and len(primary_query_token_ids) >= 3
and primary_query_coverage < 0.45
and row_token_coverage < 0.75
):
continue
partial_query_floor = 0.60 if len(full_query_token_ids) < 8 else 0.30
if (
len(full_query_token_ids) >= 5
and full_query_coverage <= partial_query_floor
and row_token_coverage < 0.75
):
continue
if (
len(full_query_token_ids) >= 12
and full_query_coverage < 0.25
and row_token_coverage <= 0.75
):
continue
if (
query_content_weight > 0.0
and matched_content_weight / query_content_weight < 0.25
and row_token_coverage < 0.75
and full_query_coverage < 0.60
):
continue
query_coverage = (
matched_content_weight / query_content_weight
if query_content_weight > 0.0
else row_token_coverage
)
numerator = sum(
query_weights[token_id] * row_weights[token_id]
for token_id in query_weights.keys() & row_weights.keys()
)
if numerator <= 0.0:
continue
row_norm = sum(value * value for value in row_weights.values()) ** 0.5
if row_norm > 0.0:
token_score = numerator / (query_norm * row_norm)
row_bigrams = {
(row_ids[index], row_ids[index + 1])
for index in range(len(row_ids) - 1)
}
row_trigrams = {
(row_ids[index], row_ids[index + 1], row_ids[index + 2])
for index in range(len(row_ids) - 2)
}
bigram_score = ordered_ngram_score(query_bigrams, row_bigrams)
trigram_score = ordered_ngram_score(query_trigrams, row_trigrams)
scores[sequence_index] = (
(0.35 * token_score)
+ (0.35 * query_coverage)
+ (0.15 * bigram_score)
+ (0.15 * trigram_score)
) * prompt_length_fit(len(row_weights))
return scores
def _score_prompt_anchor_matches(
self,
answer_anchor_state: Vector | None,
keys: object | None,
key_norms_list: object | None,
values: object | None,
keys_array: object | None,
key_norms_array: object | None,
values_array: object | None,
valid_mask_array: object | None,
similarity_keys_array: object | None,
similarity_key_norms_array: object | None,
similarity_mask_array: object | None,
*,
limit: int,
) -> list[tuple[float, int, int]]:
if (
answer_anchor_state is None
or keys is None
or key_norms_list is None
or values is None
):
return []
if (
np is not None
and keys_array is not None
and key_norms_array is not None
and values_array is not None
and valid_mask_array is not None
and limit > 0
):
key_array = keys_array
key_norms = key_norms_array
if (
similarity_keys_array is not None
and similarity_key_norms_array is not None
and similarity_mask_array is not None
):
state_array = self._center_state_array(
self._masked_combined_state_array(answer_anchor_state)
).astype(keys_array.dtype, copy=False)
state_array = state_array * similarity_mask_array
key_array = similarity_keys_array
key_norms = similarity_key_norms_array
else:
state_array = self._center_state_array(answer_anchor_state).astype(
keys_array.dtype,
copy=False,
)
state_norm = float(np.linalg.norm(state_array))
if state_norm == 0.0:
return []
numerators = key_array @ state_array
denominators = key_norms * state_norm
valid_mask = valid_mask_array & (denominators > 0.0)
if np.any(valid_mask):
scores = np.zeros_like(numerators, dtype=key_array.dtype)
np.divide(numerators, denominators, out=scores, where=valid_mask)
positive_positions = np.flatnonzero(valid_mask & (scores > 0.0))
if positive_positions.size:
selected_positions = positive_positions
if positive_positions.size > limit:
partition = np.argpartition(scores[positive_positions], -limit)[-limit:]
selected_positions = positive_positions[partition]
ordered_positions = selected_positions[np.argsort(scores[selected_positions])[::-1]]
return [
(
float(scores[position]),
int(values_array[position]),
int(position),
)
for position in ordered_positions
]
if similarity_mask_array is not None:
state = self._center_state_vector(self._masked_combined_state(answer_anchor_state))
else:
state = self._center_state_vector(answer_anchor_state)
state_norm = norm(state)
if state_norm == 0.0:
return []
scored: list[tuple[float, int, int]] = []
for example_index, (key, key_norm, token_id) in enumerate(
zip(keys, key_norms_list, values)
):
if token_id < 0:
continue
denominator = state_norm * key_norm
if denominator == 0.0:
continue
similarity = dot(state, key) / denominator
if similarity > 0.0:
scored.append((similarity, token_id, example_index))
scored.sort(key=lambda item: item[0], reverse=True)
return scored[:limit]
def _answer_prior_from_matches(
self,
matches: list[tuple[float, int, int]],
generated_tokens: list[str],
) -> Vector:
assert self.embedding_model is not None
if not matches:
return [0.0 for _ in self.embedding_model.id_to_token]
prior = [0.0 for _ in self.embedding_model.id_to_token]
generated_ids = {
self.embedding_model.token_to_id[token]
for token in generated_tokens
if token in self.embedding_model.token_to_id
}
for similarity, token_id, _ in matches[:ANSWER_TOP_K]:
token = self.embedding_model.id_to_token[token_id]
if not self._allowed_generation_token(token, generated_tokens):
continue
if token_id in generated_ids:
prior[token_id] += similarity * 0.35
else:
prior[token_id] += similarity
return _normalize_vector(prior)
def _answer_start_matches_from_sequences(
self,
matches: list[tuple[float, int, int]],
) -> list[tuple[float, int, int]]:
if not matches or self.answer_sequence_tokens is None:
return []
start_matches: list[tuple[float, int, int]] = []
for similarity, sequence_index, example_index in matches[:ANSWER_START_TOP_K]:
if sequence_index >= len(self.answer_sequence_tokens):
continue
row = self.answer_sequence_tokens[sequence_index]
token_ids = [
int(value)
for value in (row.tolist() if hasattr(row, "tolist") else row)
if int(value) >= 0
]
if token_ids:
start_matches.append((similarity, token_ids[0], example_index))
return start_matches
def _answer_sequence_prior_from_matches(
self,
matches: list[tuple[float, int, int]],
generated_tokens: list[str],
*,
temperature: float = 0.0,
) -> Vector:
assert self.embedding_model is not None
if not matches or self.answer_sequence_tokens is None:
return [0.0 for _ in self.embedding_model.id_to_token]
generated_ids = [
self.embedding_model.token_to_id[token]
for token in generated_tokens
if token in self.embedding_model.token_to_id
]
prior = [0.0 for _ in self.embedding_model.id_to_token]
best_similarity = matches[0][0]
if best_similarity >= 0.9:
floor_delta = 0.14 if temperature >= ANSWER_SEQUENCE_CREATIVE_TEMPERATURE else 0.02
match_floor = best_similarity - floor_delta
else:
match_floor = 0.0
for similarity, sequence_index, _ in matches[:ANSWER_START_TOP_K]:
if similarity < ANSWER_SEQUENCE_MATCH_FLOOR:
continue
if similarity < match_floor:
continue
token_ids = self._answer_sequence_token_row(sequence_index)
if not token_ids:
continue
next_token_id = self._next_sequence_token_id(token_ids, generated_ids)
if next_token_id is None:
continue
token = self.embedding_model.id_to_token[next_token_id]
if self._allowed_answer_sequence_token(token, generated_tokens):
prior[next_token_id] += max(1e-9, similarity - match_floor)
return _normalize_vector(prior)
def _answer_sequence_token_row(self, sequence_index: int) -> list[int]:
if sequence_index < 0 or self.answer_sequence_tokens is None:
return []
if self.answer_sequence_token_id_rows is not None:
if sequence_index >= len(self.answer_sequence_token_id_rows):
return []
return self.answer_sequence_token_id_rows[sequence_index]
if (
np is not None
and hasattr(self.answer_sequence_tokens, "shape")
and len(self.answer_sequence_tokens.shape) == 2
):
if sequence_index >= int(self.answer_sequence_tokens.shape[0]):
return []
row = np.asarray(self.answer_sequence_tokens[sequence_index])
return [int(value) for value in row.tolist() if int(value) >= 0]
try:
row = self.answer_sequence_tokens[sequence_index]
except (IndexError, TypeError):
return []
return self._answer_token_ids_from_row(row)
def _filter_avoided_answer_sequence_matches(
self,
matches: list[tuple[float, int, int]] | None,
avoid_token_sequences: Sequence[Sequence[str]] | None,
) -> list[tuple[float, int, int]]:
if (
not matches
or not avoid_token_sequences
or self.embedding_model is None
or self.answer_sequence_tokens is None
):
return list(matches or [])
token_to_id = self.embedding_model.token_to_id
avoided_id_sequences: set[tuple[int, ...]] = set()
for sequence in avoid_token_sequences:
ids: list[int] = []
for token in sequence:
token_id = token_to_id.get(token)
if token_id is None:
ids = []
break
ids.append(token_id)
if ids:
avoided_id_sequences.add(tuple(ids))
if not avoided_id_sequences:
return list(matches)
sequence_rows = self._answer_sequence_token_rows()
filtered: list[tuple[float, int, int]] = []
for match in matches:
_, sequence_index, _ = match
if sequence_index >= len(sequence_rows):
filtered.append(match)
continue
if tuple(sequence_rows[sequence_index]) in avoided_id_sequences:
continue
filtered.append(match)
return filtered
def _answer_sequence_token_rows(self) -> list[list[int]]:
if self.answer_sequence_token_id_rows is not None:
return self.answer_sequence_token_id_rows
rows: list[list[int]] = []
if (
np is not None
and self.answer_sequence_tokens is not None
and hasattr(self.answer_sequence_tokens, "shape")
and len(self.answer_sequence_tokens.shape) == 2
):
token_rows = np.asarray(self.answer_sequence_tokens).tolist()
rows = [
[int(value) for value in row if int(value) >= 0]
for row in token_rows
]
elif self.answer_sequence_tokens is not None:
for row in self.answer_sequence_tokens:
rows.append(self._answer_token_ids_from_row(row))
self.answer_sequence_token_id_rows = rows
return rows
@staticmethod
def _answer_token_ids_from_row(row: object) -> list[int]:
values = row.tolist() if hasattr(row, "tolist") else row
if not isinstance(values, list):
return []
return [int(value) for value in values if int(value) >= 0]
@staticmethod
def _answer_fingerprint_from_token_ids(token_ids: list[int]) -> tuple[int, ...]:
payload = ",".join(str(token_id) for token_id in token_ids).encode("ascii")
digest = hashlib.blake2s(
payload,
digest_size=ANSWER_FINGERPRINT_WORDS * 4,
).digest()
return tuple(
int.from_bytes(
digest[index * 4 : (index + 1) * 4],
"little",
signed=True,
)
for index in range(ANSWER_FINGERPRINT_WORDS)
)
def _refresh_answer_fingerprint_hashes(self) -> None:
hashes: set[tuple[int, ...]] = set()
lengths: set[int] = set()
sequences_by_length: dict[int, set[tuple[int, ...]]] = {}
if self.answer_sequence_tokens is not None:
for token_ids in self._answer_sequence_token_rows():
if token_ids:
token_length = len(token_ids)
lengths.add(token_length)
sequences_by_length.setdefault(token_length, set()).add(tuple(token_ids))
hashes.add(self._answer_fingerprint_from_token_ids(token_ids))
self.answer_fingerprint_hashes = hashes
self.answer_fingerprint_token_lengths = lengths
self.answer_fingerprint_token_sequences_by_length = sequences_by_length
def _answer_fingerprint_tensor(self) -> list[list[int]]:
if self.answer_fingerprint_hashes is None:
self._refresh_answer_fingerprint_hashes()
return [
list(fingerprint)
for fingerprint in sorted(self.answer_fingerprint_hashes or set())
]
@staticmethod
def _coerce_answer_fingerprint_hashes(raw_fingerprints: object) -> set[tuple[int, ...]]:
rows = raw_fingerprints.tolist() if hasattr(raw_fingerprints, "tolist") else raw_fingerprints
hashes: set[tuple[int, ...]] = set()
if not isinstance(rows, list):
return hashes
for row in rows:
values = row.tolist() if hasattr(row, "tolist") else row
if not isinstance(values, list):
continue
fingerprint = tuple(int(value) for value in values)
if len(fingerprint) == ANSWER_FINGERPRINT_WORDS:
hashes.add(fingerprint)
return hashes
def _answer_fingerprint_lengths(self) -> set[int]:
if self.answer_fingerprint_token_lengths is not None:
return self.answer_fingerprint_token_lengths
lengths: set[int] = set()
if (
np is not None
and self.answer_sequence_tokens is not None
and hasattr(self.answer_sequence_tokens, "shape")
and len(self.answer_sequence_tokens.shape) == 2
):
token_matrix = np.asarray(self.answer_sequence_tokens)
length_values = np.sum(token_matrix >= 0, axis=1)
lengths = {
int(length)
for length in np.unique(length_values).tolist()
if int(length) > 0
}
elif self.answer_sequence_tokens is not None:
for token_ids in self._answer_sequence_token_rows():
if token_ids:
lengths.add(len(token_ids))
self.answer_fingerprint_token_lengths = lengths
return lengths
def _use_runtime_fingerprint_blacklist(self) -> bool:
if (
np is None
or self.answer_sequence_tokens is None
or not hasattr(self.answer_sequence_tokens, "shape")
or len(self.answer_sequence_tokens.shape) != 2
):
return False
return int(self.answer_sequence_tokens.shape[0]) > ANSWER_SEQUENCE_EAGER_OVERLAP_CACHE_LIMIT
def _answer_fingerprint_token_sequence_sets(self) -> dict[int, set[tuple[int, ...]]]:
if self.answer_fingerprint_token_sequences_by_length is not None:
return self.answer_fingerprint_token_sequences_by_length
sequences_by_length: dict[int, set[tuple[int, ...]]] = {}
lengths: set[int] = set()
if self.answer_sequence_tokens is not None:
for token_ids in self._answer_sequence_token_rows():
if token_ids:
token_length = len(token_ids)
lengths.add(token_length)
sequences_by_length.setdefault(token_length, set()).add(tuple(token_ids))
self.answer_fingerprint_token_lengths = lengths
self.answer_fingerprint_token_sequences_by_length = sequences_by_length
return sequences_by_length
def _token_ids_for_generated_tokens(self, generated_tokens: Sequence[str]) -> list[int] | None:
if self.embedding_model is None:
return None
token_ids: list[int] = []
for token in generated_tokens:
token_id = self.embedding_model.token_to_id.get(token)
if token_id is None:
return None
token_ids.append(token_id)
return token_ids
def _would_complete_blacklisted_answer(
self,
generated_tokens: list[str],
candidate: str,
) -> bool:
generated_token_ids = self._token_ids_for_generated_tokens(generated_tokens)
return self._would_complete_blacklisted_answer_ids(generated_token_ids, candidate)
def _would_complete_blacklisted_answer_ids(
self,
generated_token_ids: Sequence[int] | None,
candidate: str,
) -> bool:
if (
self.embedding_model is None
or not self.answer_fingerprint_hashes
or candidate not in self.embedding_model.token_to_id
or generated_token_ids is None
):
return False
candidate_id = self.embedding_model.token_to_id[candidate]
if self._is_terminal_punctuation_text(self._render_token(candidate)):
return False
candidate_length = len(generated_token_ids) + 1
if self._use_runtime_fingerprint_blacklist():
lengths = self._answer_fingerprint_lengths()
if lengths and candidate_length not in lengths:
return False
token_ids = [*generated_token_ids, candidate_id]
if not token_ids:
return False
return self._answer_fingerprint_from_token_ids(token_ids) in self.answer_fingerprint_hashes
sequence_sets = self._answer_fingerprint_token_sequence_sets()
candidate_sequences = sequence_sets.get(candidate_length)
if candidate_sequences is not None:
return (*generated_token_ids, candidate_id) in candidate_sequences
if self.answer_sequence_tokens is not None:
return False
lengths = self._answer_fingerprint_lengths()
if lengths and candidate_length not in lengths:
return False
token_ids = [*generated_token_ids, candidate_id]
if not token_ids:
return False
return self._answer_fingerprint_from_token_ids(token_ids) in self.answer_fingerprint_hashes
def _would_follow_blacklisted_answer_prefix_ids(
self,
generated_token_ids: Sequence[int] | None,
candidate: str,
*,
minimum_prefix_length: int = ANSWER_REPLAY_PREFIX_MIN_TOKENS,
) -> bool:
if (
self.embedding_model is None
or self.answer_sequence_tokens is None
or candidate not in self.embedding_model.token_to_id
or generated_token_ids is None
):
return False
candidate_id = self.embedding_model.token_to_id[candidate]
candidate_path = (*generated_token_ids, candidate_id)
if len(candidate_path) < minimum_prefix_length:
return False
prefix_sets = self._answer_sequence_prefix_sets(minimum_prefix_length)
return candidate_path in prefix_sets.get(len(candidate_path), set())
def _answer_sequence_prefix_sets(
self,
minimum_prefix_length: int = ANSWER_REPLAY_PREFIX_MIN_TOKENS,
) -> dict[int, set[tuple[int, ...]]]:
cached = self.answer_sequence_prefixes_by_length
if cached is not None:
return cached
prefixes: dict[int, set[tuple[int, ...]]] = {}
for token_ids in self._answer_sequence_token_rows():
for length in range(minimum_prefix_length, len(token_ids) + 1):
prefixes.setdefault(length, set()).add(tuple(token_ids[:length]))
self.answer_sequence_prefixes_by_length = prefixes
return prefixes
def _avoid_text_token_sequences(
self,
avoid_texts: Sequence[str] | None,
) -> list[list[str]]:
if not avoid_texts or self.tokenizer is None:
return []
sequences: list[list[str]] = []
seen: set[tuple[str, ...]] = set()
for text in avoid_texts:
if not isinstance(text, str) or not text.strip():
continue
tokens = [
token
for token in self.tokenizer.encode(text)
if token not in self.tokenizer.special_tokens
]
key = tuple(tokens)
if tokens and key not in seen:
seen.add(key)
sequences.append(tokens)
return sequences
@staticmethod
def _runtime_generation_history_key(context: str) -> str:
return " ".join(context.split()).casefold()
@staticmethod
def _runtime_history_enabled(context: str, *, temperature: float) -> bool:
if temperature < ANSWER_REPLAY_PREFIX_TEMPERATURE:
return False
lowered = context.casefold()
return "<source>" not in lowered and "<tool_result>" not in lowered
def _runtime_avoid_texts(
self,
context: str,
avoid_texts: Sequence[str] | None,
*,
temperature: float,
) -> list[str]:
combined: list[str] = []
seen: set[str] = set()
for text in avoid_texts or ():
cleaned = " ".join(str(text).split())
if cleaned and cleaned not in seen:
combined.append(cleaned)
seen.add(cleaned)
if not self._runtime_history_enabled(context, temperature=temperature):
return combined
history = self.runtime_generation_history.get(
self._runtime_generation_history_key(context),
[],
)
for text in history:
cleaned = " ".join(str(text).split())
if cleaned and cleaned not in seen:
combined.append(cleaned)
seen.add(cleaned)
return combined
def _remember_runtime_generation(
self,
context: str,
generated_text: str,
*,
temperature: float,
) -> None:
if not self._runtime_history_enabled(context, temperature=temperature):
return
cleaned = " ".join(generated_text.split())
if not cleaned:
return
key = self._runtime_generation_history_key(context)
history = [
existing
for existing in self.runtime_generation_history.get(key, [])
if existing != cleaned
]
history.append(cleaned)
self.runtime_generation_history[key] = history[-RUNTIME_GENERATION_HISTORY_LIMIT:]
@staticmethod
def _would_follow_avoided_sequence(
generated_tokens: list[str],
candidate: str,
avoid_token_sequences: Sequence[Sequence[str]] | None,
) -> bool:
if not avoid_token_sequences:
return False
prefix_length = len(generated_tokens) + 1
if prefix_length < AVOID_SEQUENCE_MIN_TOKENS:
return False
candidate_path = [*generated_tokens, candidate]
for sequence in avoid_token_sequences:
if prefix_length <= len(sequence) and list(sequence[:prefix_length]) == candidate_path:
return True
return False
def _should_stop_answer_sequence(
self,
decode_state: DecodeState,
generated_tokens: list[str],
) -> bool:
matches = decode_state.answer_sequence_matches
if matches is None:
matches = self._score_answer_sequence_matches(
decode_state.answer_anchor_state,
decode_state.context_tokens,
)
return self._answer_sequence_is_complete(generated_tokens, matches)
def _should_stop_after_answer_path_drift(
self,
decode_state: DecodeState,
generated_tokens: list[str],
) -> bool:
matches = decode_state.answer_sequence_matches
if matches is None:
matches = self._score_answer_sequence_matches(
decode_state.answer_anchor_state,
decode_state.context_tokens,
)
if not matches or matches[0][0] < ANSWER_SEQUENCE_MATCH_FLOOR:
return False
if self._answer_sequence_has_continuation(generated_tokens, matches):
return False
if self._generated_answer_ends_terminal_sentence(generated_tokens):
return True
return self._generated_word_count(generated_tokens) >= 14
def _generated_answer_ends_terminal_sentence(self, generated_tokens: list[str]) -> bool:
if not generated_tokens:
return False
rendered = self._render_token(generated_tokens[-1])
if not self._is_terminal_punctuation_text(rendered):
return False
return self._generated_word_count(generated_tokens) > 0
def _answer_decode_has_continuation(
self,
decode_state: DecodeState,
generated_tokens: list[str],
) -> bool:
matches = decode_state.answer_sequence_matches
if matches is None:
matches = self._score_answer_sequence_matches(
decode_state.answer_anchor_state,
decode_state.context_tokens,
)
return self._answer_sequence_has_continuation(generated_tokens, matches)
def _answer_sequence_is_complete(
self,
generated_tokens: list[str],
matches: list[tuple[float, int, int]],
) -> bool:
if (
self.embedding_model is None
or self.answer_sequence_tokens is None
or not generated_tokens
or not matches
):
return False
generated_ids = [
self.embedding_model.token_to_id[token]
for token in generated_tokens
if token in self.embedding_model.token_to_id
]
if not generated_ids:
return False
for similarity, sequence_index, _ in matches[:ANSWER_START_TOP_K]:
if similarity < ANSWER_SEQUENCE_MATCH_FLOOR or sequence_index >= len(self.answer_sequence_tokens):
continue
row = self.answer_sequence_tokens[sequence_index]
token_ids = [
int(value)
for value in (row.tolist() if hasattr(row, "tolist") else row)
if int(value) >= 0
]
if not token_ids:
continue
if len(generated_ids) >= len(token_ids) and generated_ids[: len(token_ids)] == token_ids:
return True
if (
self.answer_fingerprint_hashes
and len(generated_ids) + 1 == len(token_ids)
and generated_ids == token_ids[: len(generated_ids)]
and self._answer_fingerprint_from_token_ids(token_ids)
in self.answer_fingerprint_hashes
):
generated_tail = self._render_token(generated_tokens[-1])
if self._is_structural_punctuation_text(
generated_tail
) and not self._is_terminal_punctuation_text(generated_tail):
continue
final_token = self.embedding_model.id_to_token[token_ids[-1]]
if self._is_terminal_punctuation_text(self._render_token(final_token)):
continue
return True
return False
def _answer_sequence_has_continuation(
self,
generated_tokens: list[str],
matches: list[tuple[float, int, int]],
) -> bool:
if (
self.embedding_model is None
or self.answer_sequence_tokens is None
or not generated_tokens
or not matches
):
return False
generated_ids = [
self.embedding_model.token_to_id[token]
for token in generated_tokens
if token in self.embedding_model.token_to_id
]
if not generated_ids:
return False
for similarity, sequence_index, _ in matches[:ANSWER_START_TOP_K]:
if similarity < ANSWER_SEQUENCE_MATCH_FLOOR or sequence_index >= len(self.answer_sequence_tokens):
continue
row = self.answer_sequence_tokens[sequence_index]
token_ids = [
int(value)
for value in (row.tolist() if hasattr(row, "tolist") else row)
if int(value) >= 0
]
if not token_ids:
continue
next_token_id = self._next_sequence_token_id(token_ids, generated_ids)
if next_token_id is None:
continue
token = self.embedding_model.id_to_token[next_token_id]
if self._allowed_answer_sequence_token(token, generated_tokens):
return True
return False
def _next_sequence_token_id(
self,
token_ids: list[int],
generated_ids: list[int],
) -> int | None:
if not generated_ids:
return token_ids[0]
if len(generated_ids) >= len(token_ids):
return None
if token_ids[: len(generated_ids)] != generated_ids:
return None
return token_ids[len(generated_ids)]
def _transition_prior(self, context_tokens: list[str]) -> Vector:
prior, _ = self._transition_prior_with_order(context_tokens)
return prior
def _transition_prior_with_order(
self,
context_tokens: list[str],
) -> tuple[Vector, int | None]:
assert self.embedding_model is not None
if self.transition_id_tables:
for order in TRANSITION_ORDERS:
if len(context_tokens) < order:
continue
key_ids: list[int] = []
for token in context_tokens[-order:]:
token_id = self.embedding_model.token_to_id.get(token)
if token_id is None:
key_ids = []
break
key_ids.append(token_id)
if not key_ids:
continue
transitions = self._transition_tensor_lookup(order, key_ids)
if transitions is None:
transitions = self.transition_id_tables.get(order, {}).get(tuple(key_ids))
if not transitions:
continue
next_token_ids, probabilities = transitions
prior = [0.0 for _ in self.embedding_model.id_to_token]
for token_id, probability in zip(next_token_ids, probabilities):
token_index = int(token_id)
if 0 <= token_index < len(prior):
prior[token_index] = float(probability)
return _normalize_vector(prior), order
if not self.transition_tables:
return [0.0 for _ in self.embedding_model.id_to_token], None
for order in TRANSITION_ORDERS:
if len(context_tokens) < order:
continue
key = tuple(context_tokens[-order:])
transitions = self.transition_tables.get(order, {}).get(key)
if not transitions:
continue
prior = [0.0 for _ in self.embedding_model.id_to_token]
for token, probability in transitions.items():
token_id = self.embedding_model.token_to_id.get(token)
if token_id is not None:
prior[token_id] = probability
return _normalize_vector(prior), order
return [0.0 for _ in self.embedding_model.id_to_token], None
def _transition_prior_array_with_order(
self,
context_tokens: list[str],
) -> tuple[object, int | None]:
assert np is not None
assert self.embedding_model is not None
prior = np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
if self.transition_id_tables:
for order in TRANSITION_ORDERS:
if len(context_tokens) < order:
continue
key_ids: list[int] = []
for token in context_tokens[-order:]:
token_id = self.embedding_model.token_to_id.get(token)
if token_id is None:
key_ids = []
break
key_ids.append(token_id)
if not key_ids:
continue
transitions = self._transition_tensor_lookup(order, key_ids)
if transitions is None:
transitions = self.transition_id_tables.get(order, {}).get(tuple(key_ids))
if not transitions:
continue
next_token_ids, probabilities = transitions
token_ids_array = np.asarray(next_token_ids, dtype=np.int64)
probabilities_array = np.asarray(probabilities, dtype=np.float64)
valid = (
(token_ids_array >= 0)
& (token_ids_array < len(self.embedding_model.id_to_token))
& (probabilities_array > 0.0)
)
if np.any(valid):
prior[token_ids_array[valid]] = probabilities_array[valid]
total = float(prior.sum())
if total > 0.0:
prior /= total
return prior, order
return prior, None
if not self.transition_tables:
return prior, None
for order in TRANSITION_ORDERS:
if len(context_tokens) < order:
continue
key = tuple(context_tokens[-order:])
transitions = self.transition_tables.get(order, {}).get(key)
if not transitions:
continue
for token, probability in transitions.items():
token_id = self.embedding_model.token_to_id.get(token)
if token_id is not None:
prior[token_id] = probability
total = float(prior.sum())
if total > 0.0:
prior /= total
return prior, order
return prior, None
def _copy_prior(self, context_tokens: list[str]) -> Vector:
assert self.embedding_model is not None
assert self.tokenizer is not None
prior = [0.0 for _ in self.embedding_model.id_to_token]
decay = 0.82
answer_start = None
for index in range(len(context_tokens) - 1, -1, -1):
if context_tokens[index] == "<answer>":
answer_start = index + 1
break
source_tokens = (
context_tokens[: max(0, answer_start - 1)]
if answer_start is not None
else context_tokens
)
if not source_tokens:
return prior
for distance, token in enumerate(reversed(source_tokens)):
if token in self.tokenizer.special_tokens:
continue
if not self._eligible_copy_token(token):
continue
token_id = self.embedding_model.token_to_id.get(token)
if token_id is None:
continue
prior[token_id] += (decay**distance) * self._copy_token_distinctiveness(token)
return _normalize_vector(prior)
def _copy_prior_array(self, context_tokens: list[str]) -> object:
assert np is not None
assert self.embedding_model is not None
assert self.tokenizer is not None
prior = np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
decay = 0.82
answer_start = None
for index in range(len(context_tokens) - 1, -1, -1):
if context_tokens[index] == "<answer>":
answer_start = index + 1
break
source_tokens = (
context_tokens[: max(0, answer_start - 1)]
if answer_start is not None
else context_tokens
)
for distance, token in enumerate(reversed(source_tokens)):
if token in self.tokenizer.special_tokens:
continue
if not self._eligible_copy_token(token):
continue
token_id = self.embedding_model.token_to_id.get(token)
if token_id is None:
continue
prior[token_id] += (decay**distance) * self._copy_token_distinctiveness(token)
total = float(prior.sum())
if total > 0.0:
prior /= total
return prior
def _copy_token_distinctiveness(self, token: str) -> float:
rendered = self._render_token(token).strip()
if not rendered:
return 0.0
letters = sum(character.isalpha() for character in rendered)
digits = sum(character.isdigit() for character in rendered)
symbols = sum(
not character.isalnum() and not character.isspace()
for character in rendered
)
score = 1.0
if any(character.isupper() for character in rendered) and letters:
score += 0.8
if digits:
score += 0.9
if symbols:
score += 0.5
if len(rendered) >= 4:
score += 0.2
return score
def _prompt_copy_evidence_is_distinctive(self, context_tokens: list[str]) -> bool:
answer_start = None
for index in range(len(context_tokens) - 1, -1, -1):
if context_tokens[index] == "<answer>":
answer_start = index
break
prompt_tokens = context_tokens[:answer_start] if answer_start is not None else context_tokens
for token in prompt_tokens:
if self.tokenizer is not None and token in self.tokenizer.special_tokens:
continue
rendered = self._render_token(token).strip()
if any(character.isdigit() for character in rendered):
return True
if sum(character.isupper() for character in rendered) >= 2:
return True
return False
def _source_evidence_prior(
self,
context_tokens: list[str],
generated_tokens: list[str] | None = None,
) -> Vector:
assert self.embedding_model is not None
prior = [0.0 for _ in self.embedding_model.id_to_token]
for token_id, weight in self._source_evidence_token_weights(
context_tokens,
generated_tokens or [],
).items():
if 0 <= token_id < len(prior):
prior[token_id] += weight
return _normalize_vector(prior)
def _source_evidence_prior_array(
self,
context_tokens: list[str],
generated_tokens: list[str] | None = None,
) -> object:
assert np is not None
assert self.embedding_model is not None
prior = np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
for token_id, weight in self._source_evidence_token_weights(
context_tokens,
generated_tokens or [],
).items():
if 0 <= token_id < prior.size:
prior[token_id] += weight
total = float(prior.sum())
if total > 0.0:
prior /= total
return prior
def _source_evidence_token_weights(
self,
context_tokens: list[str],
generated_tokens: list[str],
) -> dict[int, float]:
if self.embedding_model is None or self.tokenizer is None:
return {}
segments = self._source_evidence_segments(context_tokens)
if not segments:
return {}
generated_ids = [
self.embedding_model.token_to_id[token]
for token in generated_tokens
if token in self.embedding_model.token_to_id
]
first_source_index = _first_index(context_tokens, "<source>")
query_tokens = (
context_tokens[:first_source_index]
if first_source_index is not None
else context_tokens
)
query_token_ids = {
self.embedding_model.token_to_id[token]
for token in query_tokens
if token in self.embedding_model.token_to_id
and token not in self.tokenizer.special_tokens
and self._eligible_copy_token(token)
}
weights: dict[int, float] = {}
def add_token(token: str, weight: float, *, allow_piece: bool = False) -> None:
if token in self.tokenizer.special_tokens:
return
if not allow_piece and not self._allowed_generation_token(token, generated_tokens):
return
if allow_piece:
rendered = self._render_token(token)
if not rendered or not rendered.strip():
return
elif not self._eligible_copy_token(token):
return
token_id = self.embedding_model.token_to_id.get(token)
if token_id is None:
return
weights[token_id] = weights.get(token_id, 0.0) + weight
for segment_tokens, segment_weight, segment_role in segments[-6:]:
if generated_ids and segment_role != "snippet":
continue
token_ids = [
self.embedding_model.token_to_id[token]
for token in segment_tokens
if token in self.embedding_model.token_to_id
]
aligned = False
if generated_ids and token_ids:
max_suffix = min(8, len(generated_ids), len(token_ids))
for suffix_length in range(max_suffix, 0, -1):
suffix = generated_ids[-suffix_length:]
for index in range(len(token_ids) - suffix_length):
if token_ids[index : index + suffix_length] != suffix:
continue
next_token_id = token_ids[index + suffix_length]
next_token = self.embedding_model.id_to_token[next_token_id]
add_token(
next_token,
segment_weight * (3.0 + suffix_length),
allow_piece=True,
)
aligned = True
if aligned:
break
if aligned:
continue
content_rank = 0
anchor_seen = False
segment_has_query_anchor = any(token_id in query_token_ids for token_id in token_ids)
for token in segment_tokens:
rendered = self._render_token(token)
if "://" in rendered or rendered.casefold().startswith("http"):
continue
if not self._eligible_copy_token(token):
continue
token_id = self.embedding_model.token_to_id.get(token)
if token_id is None:
continue
if segment_has_query_anchor:
in_query = token_id in query_token_ids
if in_query:
weight = segment_weight * 0.42
anchor_seen = True
elif anchor_seen:
weight = segment_weight * 2.10
else:
weight = segment_weight * 0.32
elif content_rank == 0:
weight = segment_weight * 4.0
elif content_rank == 1:
weight = segment_weight * 1.35
else:
weight = segment_weight * 0.65
weight *= 0.94 ** min(content_rank, 24)
add_token(token, weight)
content_rank += 1
return weights
def _source_evidence_segments(self, context_tokens: list[str]) -> list[tuple[list[str], float, str]]:
if self.tokenizer is None:
return []
answer_boundary = _last_index(context_tokens, "<answer>")
upper_bound = answer_boundary if answer_boundary is not None else len(context_tokens)
boundary_tokens = {"<source>", "<tool_result>", "<tool_call>", "<final>", "<answer>"}
segments: list[tuple[list[str], float, str]] = []
index = 0
while index < upper_bound:
if context_tokens[index] != "<source>":
index += 1
continue
start = index + 1
end = start
while (
end < upper_bound
and context_tokens[end] not in boundary_tokens
and self._render_token(context_tokens[end]) != "\n"
):
end += 1
source_tokens = context_tokens[start:end]
pipe_positions = [
position
for position, token in enumerate(source_tokens)
if self._render_token(token).strip() == "|"
]
if pipe_positions:
snippet_tokens = source_tokens[pipe_positions[-1] + 1 :]
if snippet_tokens:
segments.append((snippet_tokens, 1.0, "snippet"))
elif source_tokens:
segments.append((source_tokens, 0.90, "snippet"))
index = end + 1
return segments
def _source_evidence_is_complete(
self,
context_tokens: list[str],
generated_tokens: list[str],
) -> bool:
if (
self.embedding_model is None
or self.tokenizer is None
or self._generated_word_count(generated_tokens) < 5
):
return False
generated_ids = [
self.embedding_model.token_to_id[token]
for token in generated_tokens
if token in self.embedding_model.token_to_id
]
if not generated_ids:
return False
for segment_tokens, _, segment_role in self._source_evidence_segments(context_tokens):
if segment_role != "snippet":
continue
segment_ids = [
self.embedding_model.token_to_id[token]
for token in segment_tokens
if token in self.embedding_model.token_to_id
]
if len(generated_ids) > len(segment_ids):
continue
max_suffix = min(12, len(generated_ids), len(segment_ids))
for suffix_length in range(max_suffix, 4, -1):
suffix_ids = generated_ids[-suffix_length:]
for start in range(len(segment_ids) - suffix_length + 1):
if segment_ids[start : start + suffix_length] != suffix_ids:
continue
next_index = start + suffix_length
if next_index >= len(segment_ids):
return True
next_token = self.embedding_model.id_to_token[segment_ids[next_index]]
if self._source_punctuation_continues_numeric_span(
segment_ids,
next_index,
):
return False
if self._is_terminal_punctuation_text(self._render_token(next_token)):
return True
return False
def _source_evidence_has_continuation(
self,
context_tokens: list[str],
generated_tokens: list[str],
) -> bool:
if self.embedding_model is None or not generated_tokens:
return False
generated_ids = [
self.embedding_model.token_to_id[token]
for token in generated_tokens
if token in self.embedding_model.token_to_id
]
if not generated_ids:
return False
for segment_tokens, _, segment_role in self._source_evidence_segments(context_tokens):
if segment_role != "snippet":
continue
segment_ids = [
self.embedding_model.token_to_id[token]
for token in segment_tokens
if token in self.embedding_model.token_to_id
]
max_suffix = min(12, len(generated_ids), len(segment_ids))
for suffix_length in range(max_suffix, 0, -1):
suffix_ids = generated_ids[-suffix_length:]
for start in range(len(segment_ids) - suffix_length + 1):
if segment_ids[start : start + suffix_length] != suffix_ids:
continue
next_index = start + suffix_length
if next_index >= len(segment_ids):
return False
if self._source_punctuation_continues_numeric_span(
segment_ids,
next_index,
) or self._source_punctuation_continues_numeric_span(
segment_ids,
next_index - 1,
):
return True
next_token = self.embedding_model.id_to_token[segment_ids[next_index]]
return not self._is_terminal_punctuation_text(
self._render_token(next_token)
)
return False
def _source_evidence_next_token(
self,
context_tokens: list[str],
generated_tokens: list[str],
) -> str | None:
if self.embedding_model is None:
return None
for segment_tokens, _, segment_role in self._source_evidence_segments(context_tokens):
if segment_role != "snippet" or not segment_tokens:
continue
if not generated_tokens:
return segment_tokens[0]
segment_ids = [
self.embedding_model.token_to_id[token]
for token in segment_tokens
if token in self.embedding_model.token_to_id
]
generated_ids = [
self.embedding_model.token_to_id[token]
for token in generated_tokens
if token in self.embedding_model.token_to_id
]
if not segment_ids or not generated_ids:
continue
max_suffix = min(12, len(generated_ids), len(segment_ids))
for suffix_length in range(max_suffix, 0, -1):
suffix_ids = generated_ids[-suffix_length:]
for start in range(len(segment_ids) - suffix_length + 1):
if segment_ids[start : start + suffix_length] != suffix_ids:
continue
next_index = start + suffix_length
if next_index < len(segment_ids):
return self.embedding_model.id_to_token[segment_ids[next_index]]
return None
def _source_punctuation_continues_numeric_span(
self,
segment_ids: list[int],
punctuation_index: int,
) -> bool:
if self.embedding_model is None:
return False
if punctuation_index <= 0 or punctuation_index + 1 >= len(segment_ids):
return False
punctuation_text = self._render_token(
self.embedding_model.id_to_token[segment_ids[punctuation_index]]
).strip()
if not self._is_structural_punctuation_text(punctuation_text):
return False
previous_text = self._render_token(
self.embedding_model.id_to_token[segment_ids[punctuation_index - 1]]
)
next_text = self._render_token(
self.embedding_model.id_to_token[segment_ids[punctuation_index + 1]]
)
return any(character.isdigit() for character in previous_text) and any(
character.isdigit() for character in next_text
)
def _preference_prior(self) -> Vector:
assert self.embedding_model is not None
if not self.preference_bias or not any(value != 0.0 for value in self.preference_bias):
return [0.0 for _ in self.embedding_model.id_to_token]
eligible_indices = [
index
for index, token in enumerate(self.embedding_model.id_to_token)
if self.preference_bias[index] > 0.0 and self._eligible_preference_token(token)
]
if not eligible_indices:
return [0.0 for _ in self.embedding_model.id_to_token]
eligible_probabilities = self._calibrated_softmax(
[self.preference_bias[index] for index in eligible_indices]
)
prior = [0.0 for _ in self.embedding_model.id_to_token]
for index, probability in zip(eligible_indices, eligible_probabilities):
prior[index] = probability
return prior
def _preference_prior_array(self) -> object:
assert np is not None
assert self.embedding_model is not None
if self.preference_bias_array is None or not np.any(self.preference_bias_array != 0.0):
return np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
if self.preference_valid_mask_array is None or not np.any(self.preference_valid_mask_array):
return np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
positive_mask = self.preference_bias_array > 0.0
active_mask = self.preference_valid_mask_array & positive_mask
if not np.any(active_mask):
return np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
prior = np.zeros(len(self.embedding_model.id_to_token), dtype=np.float64)
prior[active_mask] = self._calibrated_softmax_array(
self.preference_bias_array[active_mask]
)
return prior
def _eligible_preference_token(self, token: str) -> bool:
assert self.tokenizer is not None
if token == self.tokenizer.unk_token or token in self.tokenizer.special_tokens:
return False
if not self._starts_new_word(token):
return False
rendered = self._render_token(token)
if not rendered.strip() or self._is_punctuation_piece(rendered):
return False
alphanumeric = "".join(character for character in rendered if character.isalnum())
return len(alphanumeric) >= 1
def _build_transition_tables(
self,
tokens: list[str],
) -> dict[int, dict[tuple[str, ...], dict[str, float]]]:
counts: dict[int, dict[tuple[str, ...], dict[str, int]]] = {
order: {} for order in sorted(TRANSITION_ORDERS)
}
for order in sorted(TRANSITION_ORDERS):
for index in range(order - 1, len(tokens) - 1):
key = tuple(tokens[index - order + 1 : index + 1])
nxt = tokens[index + 1]
bucket = counts[order].setdefault(key, {})
bucket[nxt] = bucket.get(nxt, 0) + 1
probabilities: dict[int, dict[tuple[str, ...], dict[str, float]]] = {
order: {} for order in sorted(TRANSITION_ORDERS)
}
for order, mapping in counts.items():
items = list(mapping.items())
items.sort(key=lambda item: (-sum(item[1].values()), item[0]))
if (
self.config.max_transition_contexts_per_order is not None
and self.config.max_transition_contexts_per_order >= 0
):
items = items[: self.config.max_transition_contexts_per_order]
for key, bucket in items:
next_items = sorted(bucket.items(), key=lambda item: (-item[1], item[0]))
if self.config.max_transition_next_tokens > 0:
next_items = next_items[: self.config.max_transition_next_tokens]
total = sum(value for _, value in next_items)
if total <= 0:
continue
probabilities[order][key] = {
token: value / total
for token, value in next_items
}
return probabilities
def _transition_table_tensors(self) -> dict[str, object]:
assert self.embedding_model is not None
if self.transition_tensor_cache is not None:
return {
"transition_orders": self.transition_tensor_cache["orders"],
"transition_key_offsets": self.transition_tensor_cache["key_offsets"],
"transition_key_token_ids": self.transition_tensor_cache["key_token_ids"],
"transition_next_offsets": self.transition_tensor_cache["next_offsets"],
"transition_next_token_ids": self.transition_tensor_cache["next_token_ids"],
"transition_next_probabilities": self.transition_tensor_cache["next_probabilities"],
}
if not self.transition_tables:
return {
"transition_orders": [],
"transition_key_offsets": [0],
"transition_key_token_ids": [],
"transition_next_offsets": [0],
"transition_next_token_ids": [],
"transition_next_probabilities": [],
}
token_to_id = self.embedding_model.token_to_id
orders: list[int] = []
key_offsets: list[int] = [0]
key_token_ids: list[int] = []
next_offsets: list[int] = [0]
next_token_ids: list[int] = []
next_probabilities: list[float] = []
for order in sorted(self.transition_tables):
mapping = self.transition_tables.get(order, {})
for key, transitions in mapping.items():
key_ids = [token_to_id.get(token, -1) for token in key]
if len(key_ids) != order or any(token_id < 0 for token_id in key_ids):
continue
next_items = [
(token_to_id[token], float(probability))
for token, probability in transitions.items()
if token in token_to_id and probability > 0.0
]
if not next_items:
continue
orders.append(order)
key_token_ids.extend(key_ids)
key_offsets.append(len(key_token_ids))
for token_id, probability in next_items:
next_token_ids.append(token_id)
next_probabilities.append(probability)
next_offsets.append(len(next_token_ids))
return {
"transition_orders": orders,
"transition_key_offsets": key_offsets,
"transition_key_token_ids": key_token_ids,
"transition_next_offsets": next_offsets,
"transition_next_token_ids": next_token_ids,
"transition_next_probabilities": next_probabilities,
}
def _deserialize_transition_id_tables_from_tensors(
self,
tensors: dict[str, object],
) -> dict[int, dict[tuple[int, ...], tuple[object, object]]] | None:
required = (
"transition_orders",
"transition_key_offsets",
"transition_key_token_ids",
"transition_next_offsets",
"transition_next_token_ids",
"transition_next_probabilities",
)
if any(name not in tensors for name in required):
return None
def _as_sequence(name: str) -> object:
value = tensors.get(name, [])
return value if hasattr(value, "shape") else list(value)
orders = _as_sequence("transition_orders")
key_offsets = _as_sequence("transition_key_offsets")
key_token_ids = _as_sequence("transition_key_token_ids")
next_offsets = _as_sequence("transition_next_offsets")
next_token_ids = _as_sequence("transition_next_token_ids")
next_probabilities = _as_sequence("transition_next_probabilities")
row_count = len(orders)
if row_count == 0:
return {order: {} for order in sorted(TRANSITION_ORDERS)}
if len(key_offsets) != row_count + 1 or len(next_offsets) != row_count + 1:
return None
if np is not None and hasattr(orders, "shape"):
self.transition_tensor_cache = {
"orders": orders,
"key_offsets": key_offsets,
"key_token_ids": key_token_ids,
"next_offsets": next_offsets,
"next_token_ids": next_token_ids,
"next_probabilities": next_probabilities,
"order_spans": {},
}
self.transition_built_orders = set()
return {order: {} for order in sorted(TRANSITION_ORDERS)}
tables: dict[int, dict[tuple[int, ...], tuple[object, object]]] = {
order: {} for order in sorted(TRANSITION_ORDERS)
}
for index in range(row_count):
order = int(orders[index])
key_start = int(key_offsets[index])
key_end = int(key_offsets[index + 1])
next_start = int(next_offsets[index])
next_end = int(next_offsets[index + 1])
key = tuple(int(token_id) for token_id in key_token_ids[key_start:key_end])
if len(key) != order or next_end <= next_start:
continue
tables.setdefault(order, {})[key] = (
next_token_ids[next_start:next_end],
next_probabilities[next_start:next_end],
)
return tables
def _serialize_transition_tables(self) -> dict[str, dict[str, dict[str, float]]]:
assert self.transition_tables is not None
return {
str(order): {
_encode_ngram_key(key): value
for key, value in mapping.items()
}
for order, mapping in self.transition_tables.items()
}
def _deserialize_transition_tables(
self,
payload: dict[str, dict[str, dict[str, float]]],
) -> dict[int, dict[tuple[str, ...], dict[str, float]]]:
tables: dict[int, dict[tuple[str, ...], dict[str, float]]] = {
order: {} for order in sorted(TRANSITION_ORDERS)
}
for order_text, mapping in payload.items():
order = int(order_text)
tables[order] = {
_decode_ngram_key(key): {
str(token): float(probability)
for token, probability in value.items()
}
for key, value in mapping.items()
}
return tables
def _transition_tensor_order_span(self, order: int) -> tuple[int, int] | None:
if np is None or self.transition_tensor_cache is None:
return None
spans = self.transition_tensor_cache.get("order_spans")
if isinstance(spans, dict) and order in spans:
return spans[order]
orders = self.transition_tensor_cache["orders"]
positions = np.flatnonzero(orders == order)
span = (
(int(positions[0]), int(positions[-1]) + 1)
if positions.size
else None
)
if isinstance(spans, dict):
spans[order] = span
return span
def _transition_tensor_lookup(
self,
order: int,
key_ids: list[int],
) -> tuple[object, object] | None:
if (
np is None
or self.transition_tensor_cache is None
or len(key_ids) != order
):
return None
span = self._transition_tensor_order_span(order)
if span is None:
return None
row_start, row_end = span
key_offsets = self.transition_tensor_cache["key_offsets"]
key_token_ids = self.transition_tensor_cache["key_token_ids"]
next_offsets = self.transition_tensor_cache["next_offsets"]
next_token_ids = self.transition_tensor_cache["next_token_ids"]
next_probabilities = self.transition_tensor_cache["next_probabilities"]
key_start = int(key_offsets[row_start])
key_end = int(key_offsets[row_end])
key_block = np.asarray(key_token_ids[key_start:key_end], dtype=np.int64)
row_count = row_end - row_start
if row_count <= 0 or key_block.size != row_count * order:
return None
keys = key_block.reshape(row_count, order)
query = np.asarray(key_ids, dtype=np.int64)
matches = np.flatnonzero(np.all(keys == query[None, :], axis=1))
if not matches.size:
return None
row = row_start + int(matches[0])
next_start = int(next_offsets[row])
next_end = int(next_offsets[row + 1])
if next_end <= next_start:
return None
return (
next_token_ids[next_start:next_end],
next_probabilities[next_start:next_end],
)
def _eligible_copy_token(self, token: str) -> bool:
rendered = self._render_token(token)
if not rendered.strip():
return False
if self._is_punctuation_piece(rendered):
return False
if not self._starts_new_word(token):
return False
alphanumeric = "".join(character for character in rendered if character.isalnum())
return len(alphanumeric) >= 2
def _allowed_generation_token(
self,
token: str,
generated_tokens: list[str],
context_tokens: list[str] | None = None,
) -> bool:
return self._allowed_generation_token_with_meta(
token,
self._generation_token_meta(token),
generated_tokens,
context_tokens,
)
def _allowed_generation_token_with_meta(
self,
token: str,
meta: GenerationTokenMeta,
generated_tokens: list[str],
context_tokens: list[str] | None = None,
) -> bool:
assert self.embedding_model is not None
assert self.tokenizer is not None
if token == self.tokenizer.unk_token:
return False
if token in self.tokenizer.special_tokens:
return self._allowed_tool_protocol_token(
token,
generated_tokens=generated_tokens,
context_tokens=context_tokens or [],
)
if len(self.embedding_model.id_to_token) < 1024:
return True
if meta.rendered == "\n":
return bool(generated_tokens)
if not meta.stripped:
return False
if meta.word_joiner:
return (
self._can_attach_word_joiner(generated_tokens)
or self._can_start_line_with_word_joiner(token, generated_tokens)
)
if meta.structural_punctuation:
return bool(generated_tokens) or self._can_start_answer_with_structural_punctuation(token)
if meta.structural_symbol:
return bool(generated_tokens) or meta.starts_new_word
if not meta.starts_new_word:
if not generated_tokens:
return False
previous_rendered = self._render_token(generated_tokens[-1])
return (
bool(previous_rendered)
and any(character.isalnum() for character in previous_rendered)
and bool(meta.alphanumeric)
)
return len(meta.alphanumeric) >= 1 or not meta.punctuation_piece
@staticmethod
def _allowed_tool_protocol_token(
token: str,
*,
generated_tokens: list[str],
context_tokens: list[str],
) -> bool:
if token not in TOOL_PROTOCOL_TOKENS:
return False
if token == "<tool_call>":
return (
ReframrModel._context_requests_tool_call(context_tokens)
and
"<tool_call>" not in generated_tokens
and "<tool_result>" not in generated_tokens
and "<source>" not in generated_tokens
)
if token in {"<tool_result>", "<source>"}:
return False
if token == "<final>":
return (
"<tool_result>" in context_tokens
or "<source>" in context_tokens
or "<final>" in context_tokens
)
return True
@staticmethod
def _context_requests_tool_call(context_tokens: list[str]) -> bool:
rendered_terms: list[str] = []
for token in context_tokens:
if token in TOOL_PROTOCOL_TOKENS or token.startswith("<"):
continue
normalized = token.replace("▁", " ").strip().casefold()
if not normalized:
continue
rendered_terms.append(normalized)
pieces = {
"".join(
character
for character in piece
if character.isalnum() or character in {"-", "."}
)
for piece in normalized.split()
}
if pieces & TOOL_CALL_CONTEXT_TERMS:
return True
joined = " ".join(rendered_terms)
compact = "".join(rendered_terms)
return any(
term in joined or term.replace("-", "") in compact
for term in TOOL_CALL_CONTEXT_TERMS
)
def _would_repeat_recent_pattern(
self,
candidate: str,
generated_tokens: list[str],
recent_rendered_words: list[str] | None = None,
) -> bool:
if len(generated_tokens) >= 2 and generated_tokens[-1] == candidate and generated_tokens[-2] == candidate:
return True
if len(generated_tokens) >= 2:
trigram = tuple(generated_tokens[-2:] + [candidate])
recent_tokens = generated_tokens[-12:]
for index in range(max(0, len(recent_tokens) - 4)):
if tuple(recent_tokens[index : index + 3]) == trigram:
return True
rendered_words = recent_rendered_words
if rendered_words is None:
rendered_words = self._recent_rendered_words(generated_tokens)
candidate_meta = self._generation_token_meta(candidate)
candidate_word = candidate_meta.rendered.casefold()
if (
rendered_words
and candidate_meta.starts_new_word
and any(character.isalnum() for character in candidate_word)
):
candidate_bigram = (rendered_words[-1], candidate_word)
recent_window = rendered_words[-10:]
recent_bigrams = {
(recent_window[index], recent_window[index + 1])
for index in range(len(recent_window) - 1)
}
if candidate_bigram in recent_bigrams:
return True
if (
len(candidate_word) > 2
and rendered_words[-10:].count(candidate_word) >= 2
and not candidate_meta.common_connector
):
return True
return False
@staticmethod
def _is_inside_tool_protocol_continuation(generated_tokens: list[str]) -> bool:
return any(token in TOOL_PROTOCOL_TOKENS for token in generated_tokens[-6:])
def _would_repeat_recent_phrase(
self,
candidate: str,
generated_tokens: list[str],
*,
recent_rendered_words: list[str] | None = None,
) -> bool:
if not self._starts_new_word(candidate):
return False
rendered_words = list(
recent_rendered_words
if recent_rendered_words is not None
else self._recent_rendered_words(generated_tokens)
)
candidate_word = self._render_token(candidate).casefold()
if not any(character.isalnum() for character in candidate_word):
return False
rendered_words.append(candidate_word)
recent_window = rendered_words[-48:]
for span in range(4, min(8, len(recent_window)) + 1):
suffix = tuple(recent_window[-span:])
earlier = recent_window[:-span]
for index in range(len(earlier) - span + 1):
if tuple(earlier[index : index + span]) == suffix:
return True
return False
def _recent_phrase_repeat_candidate_words(
self,
recent_rendered_words: list[str],
) -> set[str]:
repeat_candidates: set[str] = set()
base_window = recent_rendered_words[-47:]
max_span = min(8, len(base_window) + 1)
if max_span < 4:
return repeat_candidates
for span in range(4, max_span + 1):
prefix_length = span - 1
suffix_prefix = tuple(base_window[-prefix_length:])
earlier_length = len(base_window) - prefix_length
if earlier_length < span:
continue
for index in range(earlier_length - span + 1):
earlier_segment = base_window[index : index + span]
if tuple(earlier_segment[:-1]) == suffix_prefix:
candidate_word = earlier_segment[-1]
if any(character.isalnum() for character in candidate_word):
repeat_candidates.add(candidate_word)
return repeat_candidates
def _recent_rendered_words(self, generated_tokens: list[str]) -> list[str]:
rendered_words: list[str] = []
for token in generated_tokens:
if not self._starts_new_word(token):
continue
rendered = self._render_token(token).casefold()
if any(character.isalnum() for character in rendered):
rendered_words.append(rendered)
return rendered_words
def _select_generation_token(
self,
distribution: dict[str, float],
*,
context_tokens: list[str] | None = None,
generated_tokens: list[str] | None = None,
temperature: float = DEFAULT_GENERATION_TEMPERATURE,
top_k: int = DEFAULT_GENERATION_TOP_K,
top_p: float = DEFAULT_GENERATION_TOP_P,
repetition_penalty: float = DEFAULT_REPETITION_PENALTY,
preserve_dominant_candidates: bool = False,
avoid_token_sequences: Sequence[Sequence[str]] | None = None,
) -> str:
assert self.tokenizer is not None
generated_tokens = generated_tokens or []
candidates = self._prepare_generation_candidates(
distribution,
context_tokens=context_tokens or [],
generated_tokens=generated_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
repetition_penalty=repetition_penalty,
preserve_dominant_candidates=preserve_dominant_candidates,
avoid_token_sequences=avoid_token_sequences,
)
if candidates:
return self._sample_generation_candidate(
candidates,
context_tokens=context_tokens or [],
generated_tokens=generated_tokens,
stochastic=temperature > 0.0,
preserve_dominant_candidates=preserve_dominant_candidates,
)
for token, _ in sorted(distribution.items(), key=lambda item: item[1], reverse=True):
if token in self.tokenizer.special_tokens and token not in TOOL_PROTOCOL_TOKENS:
continue
if token == self.tokenizer.unk_token:
continue
if not self._allowed_generation_token(token, generated_tokens, context_tokens or []):
continue
if self._would_complete_blacklisted_answer(generated_tokens, token):
continue
return token
return ""
def _select_generation_token_from_array(
self,
probabilities: object,
*,
context_tokens: list[str],
generated_tokens: list[str],
temperature: float = DEFAULT_GENERATION_TEMPERATURE,
top_k: int = DEFAULT_GENERATION_TOP_K,
top_p: float = DEFAULT_GENERATION_TOP_P,
repetition_penalty: float = DEFAULT_REPETITION_PENALTY,
preserve_dominant_candidates: bool = False,
avoid_token_sequences: Sequence[Sequence[str]] | None = None,
) -> str:
assert np is not None
assert self.tokenizer is not None
assert self.embedding_model is not None
values = np.asarray(probabilities, dtype=np.float64)
if values.size == 0:
return ""
first_pool_size = min(values.size, max(top_k, 64))
if first_pool_size <= 0:
first_pool_size = min(values.size, 64)
expanded_pool_size = min(values.size, max(top_k * 4, 64))
pool_sizes: list[int] = []
for pool_size in (first_pool_size, expanded_pool_size, values.size):
if pool_size > 0 and pool_size not in pool_sizes:
pool_sizes.append(pool_size)
for pool_size in pool_sizes:
if pool_size < values.size:
candidate_indices = np.argpartition(values, -pool_size)[-pool_size:]
candidate_indices = candidate_indices[np.argsort(values[candidate_indices])[::-1]]
else:
candidate_indices = np.argsort(values)[::-1]
distribution: dict[str, float] = {}
for raw_index in candidate_indices:
index = int(raw_index)
score = float(values[index])
if score <= 0.0:
continue
token = self.embedding_model.id_to_token[index]
if (
token == self.tokenizer.unk_token
or token in self.tokenizer.special_tokens
and token not in TOOL_PROTOCOL_TOKENS
):
continue
distribution[token] = score
selected = self._select_generation_token(
distribution,
context_tokens=context_tokens,
generated_tokens=generated_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p,
repetition_penalty=repetition_penalty,
preserve_dominant_candidates=preserve_dominant_candidates,
avoid_token_sequences=avoid_token_sequences,
)
if selected:
return selected
return ""
def _prepare_generation_candidates(
self,
distribution: dict[str, float],
*,
context_tokens: list[str] | None = None,
generated_tokens: list[str],
temperature: float,
top_k: int,
top_p: float,
repetition_penalty: float,
preserve_dominant_candidates: bool = False,
avoid_token_sequences: Sequence[Sequence[str]] | None = None,
) -> list[tuple[str, float]]:
assert self.tokenizer is not None
assert self.embedding_model is not None
context_tokens = context_tokens or []
generated_word_count = self._generated_word_count(generated_tokens)
clause_words = self._words_since_clause_break(generated_tokens)
recent_rendered_words = self._recent_rendered_words(generated_tokens)
generated_token_ids = self._token_ids_for_generated_tokens(generated_tokens)
inside_tool_protocol = self._is_inside_tool_protocol_continuation(generated_tokens)
phrase_repeat_candidate_words = (
self._recent_phrase_repeat_candidate_words(recent_rendered_words)
if generated_word_count >= MIN_COMPLETE_ANSWER_WORDS and not inside_tool_protocol
else set()
)
prompt_content_tokens = [
token
for token in context_tokens
if token not in self.tokenizer.special_tokens
and self._generation_token_meta(token).starts_new_word
and self._generation_token_meta(token).alphanumeric
and not self._generation_token_meta(token).punctuation_piece
]
initial_prompt_content_token = (
prompt_content_tokens[0]
if len(prompt_content_tokens) > 1
else None
)
best_probability = max(distribution.values(), default=0.0)
has_uppercase_start_candidate = any(
probability > 0.0
and self._generation_token_meta(token).starts_new_word
and self._generation_token_meta(token).rendered[:1].isupper()
for token, probability in distribution.items()
)
adjusted: list[tuple[str, float]] = []
for token, probability in sorted(distribution.items(), key=lambda item: item[1], reverse=True):
if token in self.tokenizer.special_tokens and token not in TOOL_PROTOCOL_TOKENS:
continue
if token == self.tokenizer.unk_token or probability <= 0.0:
continue
meta = self._generation_token_meta(token)
allowed_by_general_filter = self._allowed_generation_token_with_meta(
token,
meta,
generated_tokens,
context_tokens,
)
if not allowed_by_general_filter:
dominant_learned_continuation = (
preserve_dominant_candidates
and best_probability > 0.0
and probability >= best_probability * 0.99
and self._allowed_answer_sequence_token(token, generated_tokens)
)
if not dominant_learned_continuation:
continue
if self._would_complete_blacklisted_answer_ids(generated_token_ids, token):
continue
repeats_recent_pattern = self._would_repeat_recent_pattern(
token,
generated_tokens,
recent_rendered_words=recent_rendered_words,
)
hard_phrase_loop = (
generated_word_count >= MIN_COMPLETE_ANSWER_WORDS
and not inside_tool_protocol
and meta.starts_new_word
and meta.rendered.casefold() in phrase_repeat_candidate_words
)
if hard_phrase_loop:
continue
if repeats_recent_pattern:
dominant_candidate_allowed = (
preserve_dominant_candidates
and best_probability > 0.0
and probability >= best_probability * 0.80
)
if not dominant_candidate_allowed:
continue
score = probability
if (
temperature >= ANSWER_REPLAY_PREFIX_TEMPERATURE
and not inside_tool_protocol
and self._would_follow_blacklisted_answer_prefix_ids(
generated_token_ids,
token,
)
):
score *= ANSWER_REPLAY_PREFIX_PENALTY
if (
temperature > 0.0
and self._would_follow_avoided_sequence(
generated_tokens,
token,
avoid_token_sequences,
)
):
score *= 0.12
rendered = meta.rendered
punctuation_token = meta.structural_punctuation
starts_new_word = meta.starts_new_word
alphanumeric = meta.alphanumeric
if (
not generated_tokens
and initial_prompt_content_token is not None
and token == initial_prompt_content_token
):
dominant_answer_candidate = (
preserve_dominant_candidates
and best_probability > 0.0
and probability >= best_probability * 0.80
)
if not dominant_answer_candidate:
continue
if (
not generated_tokens
and temperature > 0.0
and has_uppercase_start_candidate
and starts_new_word
and rendered[:1].islower()
and best_probability > 0.0
and probability < best_probability * 0.85
):
continue
if generated_tokens and starts_new_word and alphanumeric:
previous_alphanumeric = self._generation_token_meta(
generated_tokens[-1]
).alphanumeric
if previous_alphanumeric.casefold() == alphanumeric.casefold():
continue
common_connector = meta.common_connector
if (
starts_new_word
and len(alphanumeric) == 1
and not common_connector
):
score *= 0.08
recent_count = generated_tokens[-12:].count(token)
if recent_count > 0 and not common_connector:
score /= repetition_penalty ** (2 * recent_count)
if generated_tokens and token == generated_tokens[-1]:
score /= repetition_penalty**3
if generated_tokens and token in generated_tokens[-4:] and not common_connector:
score *= 0.35
if generated_tokens and not starts_new_word and self._starts_new_word(generated_tokens[-1]):
score *= 0.08
if not generated_tokens and punctuation_token:
if best_probability <= 0.0 or probability < best_probability * 0.80:
score *= 0.01
elif not generated_tokens and not starts_new_word:
score *= 0.02
if (
not generated_tokens
and temperature > 0.0
and has_uppercase_start_candidate
and starts_new_word
and rendered[:1].islower()
):
score *= 0.03
if punctuation_token:
if generated_tokens and self._is_structural_punctuation_token(generated_tokens[-1]):
score *= 0.05
if clause_words >= 6:
score *= 1.0 + min(1.4, 0.18 * (clause_words - 5))
elif generated_word_count >= 12:
score *= 1.1
if score > 0.0:
adjusted.append((token, score))
if not adjusted:
return []
adjusted.sort(key=lambda item: item[1], reverse=True)
if preserve_dominant_candidates:
top_score = adjusted[0][1]
second_score = adjusted[1][1] if len(adjusted) > 1 else 0.0
if top_score >= 0.5 and (
second_score <= 0.0
or top_score >= second_score * 1.2
or top_score - second_score >= 0.08
):
return [(adjusted[0][0], 1.0)]
effective_top_k = top_k
if (
temperature >= CREATIVE_EARLY_POOL_TEMPERATURE
and generated_word_count < CREATIVE_EARLY_POOL_WORD_LIMIT
and not inside_tool_protocol
and top_k > CREATIVE_EARLY_POOL_MAX
):
effective_top_k = CREATIVE_EARLY_POOL_MAX
if effective_top_k > 0:
adjusted = adjusted[:effective_top_k]
if 0.0 < top_p < 1.0:
kept: list[tuple[str, float]] = []
cumulative = 0.0
total = sum(score for _, score in adjusted)
for token, score in adjusted:
normalized = score / total if total else 0.0
kept.append((token, score))
cumulative += normalized
if cumulative >= top_p:
break
adjusted = kept
if temperature <= 0.0:
return [(adjusted[0][0], 1.0)]
exponent = 1.0 / temperature
tempered = [
(token, score**exponent)
for token, score in adjusted
if score > 0.0
]
total = sum(score for _, score in tempered)
if total <= 0.0:
return []
return [(token, score / total) for token, score in tempered]
def _sample_generation_candidate(
self,
candidates: list[tuple[str, float]],
*,
context_tokens: list[str],
generated_tokens: list[str],
stochastic: bool = False,
preserve_dominant_candidates: bool = False,
) -> str:
if not candidates:
return ""
if len(candidates) == 1:
return candidates[0][0]
top_probability = candidates[0][1]
second_probability = candidates[1][1]
top_has_clear_half_majority = top_probability >= 0.5 and (
second_probability <= 0.0
or top_probability - second_probability >= 0.02
)
if preserve_dominant_candidates and top_has_clear_half_majority:
return candidates[0][0]
decisive_stochastic_winner = stochastic and (
top_probability >= 0.985
or (
top_probability >= 0.96
and second_probability > 0.0
and top_probability >= second_probability * 20.0
)
or (
top_probability >= 0.90
and second_probability > 0.0
and top_probability >= second_probability * 40.0
)
or (
top_probability >= 0.90
and top_probability - second_probability >= 0.75
)
)
decisive_deterministic_winner = not stochastic and (
top_has_clear_half_majority
or (second_probability > 0.0 and top_probability >= second_probability * 2.5)
or (
top_probability >= 0.08
and second_probability > 0.0
and top_probability >= second_probability * 1.35
)
)
if decisive_stochastic_winner or decisive_deterministic_winner:
return candidates[0][0]
if stochastic:
threshold = random.random()
else:
seed_payload = "\u0002".join([*context_tokens, "<generated>", *generated_tokens, str(len(candidates))])
seed = int.from_bytes(hashlib.sha256(seed_payload.encode("utf-8")).digest()[:8], "big")
threshold = random.Random(seed).random()
cumulative = 0.0
for token, probability in candidates:
cumulative += probability
if threshold <= cumulative:
return token
return candidates[-1][0]
def _top_entries_from_vector(
self,
values: Vector,
limit: int,
) -> list[dict[str, object]]:
if limit <= 0:
return []
ranked = sorted(
enumerate(values),
key=lambda item: item[1],
reverse=True,
)
return [
self._token_entry(index, probability)
for index, probability in ranked[:limit]
if probability > 0.0
]
def _token_entry(
self,
index: int,
probability: float,
) -> dict[str, object]:
assert self.embedding_model is not None
token = self.embedding_model.id_to_token[index]
return {
"token": token,
"text": self._render_token(token),
"probability": probability,
}
def _build_reasoning_summary(
self,
transition_order: int | None,
blend_weights: dict[str, float],
) -> str:
dominant_source = max(blend_weights.items(), key=lambda item: item[1])[0] if blend_weights else "base"
if transition_order is not None:
transition_message = f" Transition prior is using order-{transition_order} context."
else:
transition_message = " Transition prior found no matching n-gram."
return (
"Generation is running on analytical state, recurrent traces, and corpus-derived token transitions."
f"{transition_message}"
f" Dominant blend source: {dominant_source}."
)
def _generated_word_count(self, tokens: list[str]) -> int:
count = 0
for token in tokens:
rendered = self._render_token(token)
if not any(character.isalnum() for character in rendered):
continue
if self._starts_new_word(token) or count == 0:
count += 1
return count
def _is_structural_punctuation_text(self, text: str) -> bool:
if len(text) != 1:
return False
if self._is_word_joiner_text(text):
return False
category = unicodedata.category(text)
return category.startswith("P")
def _is_structural_punctuation_token(self, token: str) -> bool:
return self._is_structural_punctuation_text(self._render_token(token))
def _is_structural_symbol_token(self, token: str) -> bool:
rendered = self._render_token(token)
return len(rendered) == 1 and unicodedata.category(rendered).startswith("S")
def _is_word_joiner_token(self, token: str) -> bool:
return self._is_word_joiner_text(self._render_token(token))
def _is_word_joiner_text(self, text: str) -> bool:
if len(text) != 1:
return False
category = unicodedata.category(text)
if category in ("Pc", "Pd", "Lm"):
return True
name = unicodedata.name(text, "")
return "APOSTROPHE" in name or (
"SINGLE" in name and "QUOTATION MARK" in name
)
def _can_start_line_with_word_joiner(self, token: str, generated_tokens: list[str]) -> bool:
rendered = self._render_token(token)
if len(rendered) != 1 or unicodedata.category(rendered) != "Pd":
return False
if not self._starts_new_word(token):
return False
return not generated_tokens or self._render_token(generated_tokens[-1]) == "\n"
def _can_start_answer_with_structural_punctuation(self, token: str) -> bool:
rendered = self._render_token(token)
if len(rendered) != 1 or not self._starts_new_word(token):
return False
return unicodedata.category(rendered) in ("Ps", "Pi")
def _is_common_connector_token(self, token: str) -> bool:
rendered = self._render_token(token)
return rendered.isalpha() and len(rendered) == 1 and rendered.islower()
def _can_attach_word_joiner(self, generated_tokens: list[str]) -> bool:
if not generated_tokens:
return False
rendered = self._render_token(generated_tokens[-1])
if not rendered:
return False
if any(character.isalnum() for character in rendered):
return True
if len(rendered) != 1:
return False
return unicodedata.category(rendered) in ("Ps", "Pi")
def _words_since_clause_break(self, tokens: list[str]) -> int:
assert self.tokenizer is not None
words = 0
for token in reversed(tokens):
if token in self.tokenizer.special_tokens:
continue
rendered = self._render_token(token)
if self._is_structural_punctuation_text(rendered):
break
if self._starts_new_word(token) and not self._is_punctuation_piece(rendered):
words += 1
return words
def _should_stop_generation(self, generated_tokens: list[str]) -> bool:
if not generated_tokens:
return False
if not self._is_terminal_punctuation_text(self._render_token(generated_tokens[-1])):
return False
word_count = self._generated_word_count(generated_tokens)
if word_count >= MIN_COMPLETE_ANSWER_WORDS:
return True
return (
word_count >= MIN_COMPLETE_MULTI_SENTENCE_WORDS
and self._terminal_sentence_count(generated_tokens) >= 2
)
def _terminal_sentence_count(self, tokens: list[str]) -> int:
return sum(
1
for token in tokens
if self._is_terminal_punctuation_text(self._render_token(token))
)
def _is_terminal_punctuation_text(self, text: str) -> bool:
stripped = text.strip()
if not stripped:
return False
terminal_character = stripped[-1]
if not self._is_structural_punctuation_text(terminal_character):
return False
return not self._is_word_joiner_text(terminal_character)
def _should_skip_prompt_overlap_token(self, token: str) -> bool:
rendered = self._render_token(token)
if not rendered.strip():
return True
if (
self.embedding_model is not None
and len(self.embedding_model.id_to_token) >= 1024
and not self._starts_new_word(token)
):
return True
if self._is_structural_punctuation_text(rendered):
return True
return rendered.strip().casefold() in PROMPT_ENVELOPE_TERMS
def _starts_new_word(self, token: str) -> bool:
assert self.tokenizer is not None
if token in self.tokenizer.special_tokens:
return True
if token.startswith(self.tokenizer.word_prefix):
return True
return len(token) == 1 and not token.isalnum() and not self._is_word_joiner_token(token)
def _generation_token_meta(self, token: str) -> GenerationTokenMeta:
cache = self.generation_token_meta_cache
if cache is None:
cache = {}
self.generation_token_meta_cache = cache
cached = cache.get(token)
if cached is not None:
return cached
rendered = self._render_token(token)
meta = GenerationTokenMeta(
rendered=rendered,
stripped=rendered.strip(),
starts_new_word=self._starts_new_word(token),
punctuation_piece=self._is_punctuation_piece(rendered),
structural_punctuation=self._is_structural_punctuation_token(token),
structural_symbol=self._is_structural_symbol_token(token),
word_joiner=self._is_word_joiner_token(token),
alphanumeric="".join(character for character in rendered if character.isalnum()),
common_connector=self._is_common_connector_token(token),
)
cache[token] = meta
return meta
def _decode_tokens(self, tokens: list[str]) -> str:
assert self.tokenizer is not None
return self.tokenizer.decode(
tokens,
preserve_special_tokens=TOOL_PROTOCOL_TOKENS,
)
@staticmethod
def _normalize_generated_tool_protocol_text(text: str, *, context: str | None = None) -> str:
marker = "<tool_call>"
call_index = text.find(marker)
if call_index < 0:
return text
cleaned = text[:]
for boundary in ("<tool_result>", "<source>", "<final>"):
boundary_index = cleaned.find(boundary, call_index + len(marker))
if boundary_index >= 0:
cleaned = cleaned[:boundary_index].rstrip()
second_call_index = cleaned.find(marker, call_index + len(marker))
if second_call_index >= 0:
cleaned = cleaned[:second_call_index].rstrip()
brace_start = cleaned.find("{", call_index)
if brace_start < 0:
return cleaned.strip()
depth = 0
in_string = False
escaped = False
last_top_level_comma: int | None = None
for index in range(brace_start, len(cleaned)):
character = cleaned[index]
if escaped:
escaped = False
continue
if in_string and character == "\\":
escaped = True
continue
if character == '"':
in_string = not in_string
continue
if in_string:
continue
if character == "{":
depth += 1
continue
if character == "}":
depth -= 1
if depth <= 0:
candidate = cleaned[: index + 1].strip()
return ReframrModel._repair_tool_call_payload_if_needed(
candidate,
context=context,
)
continue
if character == "," and depth == 1:
last_top_level_comma = index
if depth > 0:
if last_top_level_comma is not None:
candidate = cleaned[:last_top_level_comma].rstrip() + "}"
return ReframrModel._repair_tool_call_payload_if_needed(
candidate,
context=context,
)
candidate = cleaned.rstrip() + "}"
return ReframrModel._repair_tool_call_payload_if_needed(
candidate,
context=context,
)
return ReframrModel._repair_tool_call_payload_if_needed(
cleaned.strip(),
context=context,
)
@staticmethod
def _repair_tool_call_payload_if_needed(text: str, *, context: str | None = None) -> str:
marker = "<tool_call>"
if not text.startswith(marker):
return text
brace_start = text.find("{", len(marker))
if brace_start < 0:
return text
tool_name = text[len(marker) : brace_start].strip()
payload_text = text[brace_start:].strip()
try:
payload = json.loads(payload_text)
if isinstance(payload, dict) and tool_name == "web.search":
repaired_query = ReframrModel._repair_search_query_from_context_if_weak(
str(payload.get("query", "")),
context,
)
if repaired_query is not None:
payload["query"] = repaired_query
return f"{marker} {tool_name} {json.dumps(payload, ensure_ascii=False)}"
return text
except (TypeError, json.JSONDecodeError):
pass
body = payload_text.strip()
if body.startswith("{"):
body = body[1:]
if body.endswith("}"):
body = body[:-1]
body = " ".join(body.replace('"', "").split())
if not tool_name or not body:
return text
if tool_name == "web.search":
payload = {
"query": ReframrModel._repair_search_query_from_context_if_weak(
body,
context,
)
or body
}
else:
payload = {"input": body}
return f"{marker} {tool_name} {json.dumps(payload, ensure_ascii=False)}"
@staticmethod
def _repair_search_query_from_context_if_weak(
query: str,
context: str | None,
) -> str | None:
cleaned_query = " ".join(query.replace("{", " ").replace("}", " ").split())
normalized_words = [
word.strip(" \t\r\n:,.;!?\"'()[]{}").casefold()
for word in cleaned_query.split()
if word.strip(" \t\r\n:,.;!?\"'()[]{}")
]
unique_content_words = {
word
for word in normalized_words
if word not in {"query", "web.search", "tool_call"}
}
lowered_query = cleaned_query.casefold()
weak = (
len(unique_content_words) < 3
or lowered_query.startswith("query:")
or "web.search" in lowered_query
or any(
marker in lowered_query
for marker in ("<tool", "<source>", "<final>", "according to")
)
)
if not weak:
return None
context_query = ReframrModel._search_query_from_context(context or "")
return context_query or None
@staticmethod
def _search_query_from_context(context: str) -> str:
if not context:
return ""
before_tool_result = context.split("<tool_result>", 1)[0]
before_final = before_tool_result.split("<final>", 1)[0]
lines = [line.strip() for line in before_final.splitlines() if line.strip()]
if not lines:
lines = [before_final.strip()]
latest_user = ""
for line in lines:
lowered = line.casefold()
if lowered.startswith("user:"):
latest_user = line.split(":", 1)[1].strip()
elif lowered.startswith("question:"):
latest_user = line.split(":", 1)[1].strip()
if not latest_user:
latest_user = lines[-1]
for prefix in ("User:", "Question:", "Prompt:", "Context:"):
if latest_user.casefold().startswith(prefix.casefold()):
latest_user = latest_user[len(prefix) :].strip()
cleaned = " ".join(latest_user.split())
return cleaned.strip(" \t\r\n\"'")
@staticmethod
def _finalize_generated_text(text: str) -> str:
stripped = text.rstrip()
if not stripped:
return stripped
if stripped.startswith("<tool_call>"):
return stripped
stripped = ReframrModel._remove_separator_punctuation_before_boundary(stripped)
if stripped and ReframrModel._is_separator_punctuation(stripped[-1:]):
stripped = stripped[:-1].rstrip()
if not stripped:
return stripped
if (
ReframrModel._is_surface_punctuation(stripped[:1])
or ReframrModel._is_surface_punctuation(stripped[-1:])
):
return stripped
if any(character.isalnum() for character in stripped[-8:]):
return f"{stripped}."
return stripped
@staticmethod
def _remove_separator_punctuation_before_boundary(text: str) -> str:
cleaned: list[str] = []
for character in text:
if (
ReframrModel._is_separator_punctuation(character)
and cleaned
and ReframrModel._is_separator_punctuation(cleaned[-1])
):
cleaned.pop()
cleaned.append(character)
return "".join(cleaned)
@staticmethod
def _is_surface_punctuation(character: str) -> bool:
return len(character) == 1 and unicodedata.category(character).startswith("P")
@staticmethod
def _is_separator_punctuation(character: str) -> bool:
return (
ReframrModel._is_surface_punctuation(character)
and unicodedata.bidirectional(character) == "CS"
)
def _render_token(self, token: str) -> str:
assert self.tokenizer is not None
if token.startswith(self.tokenizer.word_prefix):
return token[len(self.tokenizer.word_prefix) :]
return token
def _require_fit(self) -> None:
if (
self.tokenizer is None
or self.embedding_model is None
or self.memory_units is None
or self.readout_weights is None
or self.ternary_mask is None
or self.associative_keys is None
or (
self.associative_key_norms is None
and self.associative_key_norms_array is None
)
or self.associative_values is None
or self.transition_tables is None
):
raise RuntimeError("Call fit() before using the REFRAMR model.")
def _ensure_numeric_caches(self) -> None:
if np is None:
return
if self.readout_weights_array is None:
self._refresh_numeric_caches()
|