Text Classification
Transformers
English
cortex
decision-intelligence
system-1
typed-decisions
dynamic-memory
Eval Results (legacy)
Instructions to use siddiVinayaka/Cortex-System-One with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use siddiVinayaka/Cortex-System-One with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="siddiVinayaka/Cortex-System-One")# pip install -U transformers accelerate # Load model directly from transformers import Cortex model = Cortex.from_pretrained("siddiVinayaka/Cortex-System-One", device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 60,934 Bytes
b92a420 | 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 | """
Nexus β Simplified Transformer Architecture
=============================================
Clean 20-layer transformer with integrated neural memory.
Architecture (brain-inspired):
Embed β Memory β [Layers 0-6] β Memory β [Layers 7-13] β Memory β [Layers 14-19] β Output
β input sensory β bridge processing β bridge output
context update update
Components:
- GQA Attention (heads=16, kv_heads=4) + Flash Attention 2
- SwiGLU FFN (2.67Γ expansion)
- GlobalNeuralMemory at 3 strategic bridge points
- YaRN RoPE for context extension
- MTP head for multi-token prediction training
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Optional, List, Tuple, Dict, Any, Union
from v3_modules import YaRNRotaryEmbedding, MTPHead, HyperConnection, RMSNorm
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# BASIC BUILDING BLOCKS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def apply_rotary_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
"""Apply rotary position embeddings. x: [B, H, S, D]"""
d = x.shape[-1]
x1, x2 = x[..., : d // 2], x[..., d // 2 :]
cos = cos.unsqueeze(0).unsqueeze(0)
sin = sin.unsqueeze(0).unsqueeze(0)
return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
class SwiGLU(nn.Module):
"""SwiGLU FFN β the standard modern FFN choice."""
def __init__(self, dim: int, hidden_dim: Optional[int] = None,
num_layers: int = 1, layer_id: int = 0):
super().__init__()
if hidden_dim is None:
hidden_dim = int(2.67 * dim)
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
self.w2 = nn.Linear(dim, hidden_dim, bias=False)
self.w3 = nn.Linear(hidden_dim, dim, bias=False)
self.layer_id = layer_id
self.inner_norm = RMSNorm(hidden_dim)
# Standard init for w1, w2
nn.init.normal_(self.w1.weight, std=0.02)
nn.init.normal_(self.w2.weight, std=0.02)
# Scale down the output projection to stabilize deep residuals
std_proj = 0.02 / math.sqrt(2 * num_layers)
nn.init.normal_(self.w3.weight, std=std_proj)
def forward(self, x: torch.Tensor) -> torch.Tensor:
hidden = F.silu(self.w1(x)) * self.w2(x)
hidden_normed = self.inner_norm(hidden)
return self.w3(hidden_normed)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# GQA ATTENTION β Grouped Query Attention with Flash Attention 2
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class Attention(nn.Module):
"""Grouped Query Attention with KV cache and Flash Attention 2 support."""
def __init__(self, dim: int, num_heads: int = 16, num_kv_heads: int = 4,
num_layers: int = 20, layer_id: int = 0, attn_scale: float = 1.0):
super().__init__()
self.num_heads = num_heads
self.num_kv_heads = num_kv_heads
self.head_dim = dim // num_heads
self.n_rep = num_heads // num_kv_heads
self.q = nn.Linear(dim, num_heads * self.head_dim, bias=False)
self.k = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False)
self.v = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False)
self.out = nn.Linear(num_heads * self.head_dim, dim, bias=False)
self.layer_id = layer_id
self.attn_scale = attn_scale
self.inner_norm = RMSNorm(num_heads * self.head_dim)
self.q_norm = RMSNorm(self.head_dim)
self.k_norm = RMSNorm(self.head_dim)
# Standard init for q, k, v
for layer in (self.q, self.k, self.v):
nn.init.normal_(layer.weight, std=0.02)
# Scale down output projection
std_proj = 0.02 / math.sqrt(2 * num_layers)
nn.init.normal_(self.out.weight, std=std_proj)
self._flash_available = False
try:
import flash_attn
self._flash_available = True
except ImportError:
pass
def forward(
self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
past_kv=None, use_flash: bool = False, is_causal: Optional[bool] = None,
) -> Tuple[torch.Tensor, Any]:
B, S, D = x.shape
q = self.q(x).view(B, S, self.num_heads, self.head_dim)
k = self.k(x).view(B, S, self.num_kv_heads, self.head_dim)
v = self.v(x).view(B, S, self.num_kv_heads, self.head_dim).transpose(1, 2)
q = self.q_norm(q).transpose(1, 2)
k = self.k_norm(k).transpose(1, 2)
q = apply_rotary_emb(q, cos, sin)
k = apply_rotary_emb(k, cos, sin)
# KV cache
if past_kv is not None:
if hasattr(past_kv, 'update'):
k, v = past_kv.update(k, v)
else:
past_k, past_v = past_kv
k = torch.cat([past_k, k], dim=2)
v = torch.cat([past_v, v], dim=2)
new_past_kv = past_kv if hasattr(past_kv, 'update') else (k, v)
if is_causal is None:
is_causal = (past_kv is None)
# Flash Attention 2
if use_flash and self._flash_available:
from flash_attn import flash_attn_func
q_fa = q.transpose(1, 2)
if self.n_rep > 1:
k_fa = k.repeat_interleave(self.n_rep, dim=1).transpose(1, 2)
v_fa = v.repeat_interleave(self.n_rep, dim=1).transpose(1, 2)
else:
k_fa, v_fa = k.transpose(1, 2), v.transpose(1, 2)
orig_dtype = q_fa.dtype
scale = self.attn_scale / math.sqrt(self.head_dim)
attn = flash_attn_func(
q_fa.to(torch.bfloat16), k_fa.to(torch.bfloat16),
v_fa.to(torch.bfloat16), causal=is_causal, softmax_scale=scale,
).to(orig_dtype).reshape(B, S, -1)
else:
# PyTorch SDPA (also very fast)
if self.n_rep > 1:
k_s = k.repeat_interleave(self.n_rep, dim=1)
v_s = v.repeat_interleave(self.n_rep, dim=1)
else:
k_s, v_s = k, v
scale = self.attn_scale / math.sqrt(self.head_dim)
attn = F.scaled_dot_product_attention(q, k_s, v_s, is_causal=is_causal, scale=scale)
attn = attn.transpose(1, 2).reshape(B, S, -1)
attn_normed = self.inner_norm(attn)
return self.out(attn_normed), new_past_kv
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# TRANSFORMER BLOCK β Attention + FFN with pre-norm residuals & HyperConnections
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class TransformerBlock(nn.Module):
"""Single transformer layer: RMSNorm β Attention β RMSNorm β SwiGLU."""
def __init__(self, dim: int, num_heads: int = 16, num_kv_heads: int = 4,
num_layers: int = 20, layer_id: int = 0, use_flash: bool = False,
attn_scale: float = 1.0):
super().__init__()
self.attn_norm = RMSNorm(dim)
self.attn = Attention(dim, num_heads, num_kv_heads, num_layers, layer_id, attn_scale=attn_scale)
self.ffn_norm = RMSNorm(dim)
self.ffn = SwiGLU(dim, num_layers=num_layers, layer_id=layer_id)
# Hyper connections
self.hyper_attn = HyperConnection(dim, n_streams=2)
self.hyper_ffn = HyperConnection(dim, n_streams=2)
self.use_flash = use_flash
def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor,
past_kv=None, is_causal: Optional[bool] = None) -> Tuple[torch.Tensor, Any]:
# Attention with residual
attn_out, new_kv = self.attn(
self.attn_norm(x), cos, sin, past_kv, use_flash=self.use_flash, is_causal=is_causal)
h = self.hyper_attn(x, attn_out) # learnable residual
# FFN with residual
ffn_out = self.ffn(self.ffn_norm(h))
h = self.hyper_ffn(h, ffn_out) # second learnable residual
return h, new_kv
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CROSS ATTENTION β For Neural Memory read/write
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class CrossAttention(nn.Module):
"""Cross-attention for memory read/write operations."""
def __init__(self, dim: int, num_heads: int = 16, num_kv_heads: int = 4):
super().__init__()
self.num_heads = num_heads
self.num_kv_heads = num_kv_heads
self.head_dim = dim // num_heads
self.n_rep = num_heads // num_kv_heads
self.q = nn.Linear(dim, num_heads * self.head_dim, bias=False)
self.k = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False)
self.v = nn.Linear(dim, num_kv_heads * self.head_dim, bias=False)
self.out = nn.Linear(num_heads * self.head_dim, dim, bias=False)
# Standard init for q, k, v
for layer in (self.q, self.k, self.v):
nn.init.normal_(layer.weight, std=0.02)
# Standard scale for out projection
nn.init.normal_(self.out.weight, std=0.02)
def forward(self, x: torch.Tensor, context: torch.Tensor) -> torch.Tensor:
B, S, _ = x.shape
_, S_ctx, _ = context.shape
q = self.q(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2)
k = self.k(context).view(B, S_ctx, self.num_kv_heads, self.head_dim).transpose(1, 2)
v = self.v(context).view(B, S_ctx, self.num_kv_heads, self.head_dim).transpose(1, 2)
if self.n_rep > 1:
k = k.repeat_interleave(self.n_rep, dim=1)
v = v.repeat_interleave(self.n_rep, dim=1)
attn = F.scaled_dot_product_attention(q, k, v)
return self.out(attn.transpose(1, 2).reshape(B, S, -1))
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# GLOBAL NEURAL MEMORY β Persistent memory that learns across the sequence
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class GlobalNeuralMemory(nn.Module):
"""Persistent cognitive memory with task-driven read/write routing.
Loss v2 does not impose a generic "memory must be used" or diversity target.
Instead, the downstream decision objective supplies utility signals for the
read intervention, the memory write, and final reflection.
"""
def __init__(self, dim: int, num_slots: int = 128, heads: int = 16,
retain_floor: float = 0.5, write_scale: float = 0.3,
role: str = "generic"):
super().__init__()
self.num_slots = num_slots
self.dim = dim
self.role = role
self.memory_init = nn.Parameter(torch.randn(num_slots, dim) * 0.02)
self.norm_x = RMSNorm(dim)
self.norm_mem = RMSNorm(dim)
self.mem_norm = RMSNorm(dim)
self.read_attn = CrossAttention(dim, heads, max(1, heads // 4))
self.write_attn = CrossAttention(dim, heads, max(1, heads // 4))
# Read router: its gate is supervised by downstream task utility.
self.read_gate = nn.Sequential(
nn.Linear(dim * 2, dim),
nn.Sigmoid(),
)
nn.init.zeros_(self.read_gate[0].weight)
nn.init.constant_(self.read_gate[0].bias, 0.0)
self.write_scale = write_scale
self.retain_floor = retain_floor
# Write admission router: its gate is supervised by future-example
# utility. Slot contents are trained directly through downstream loss.
self.affinity_gate = nn.Sequential(
nn.Linear(dim * 2, dim),
nn.Sigmoid(),
)
nn.init.zeros_(self.affinity_gate[0].weight)
nn.init.constant_(self.affinity_gate[0].bias, 0.0)
# Retention is learned through the task gradient through new_memory.
self.gate = nn.Sequential(
nn.Linear(dim, dim),
nn.Sigmoid(),
)
nn.init.zeros_(self.gate[0].weight)
target_retention = min(retain_floor + 0.3, 0.9)
if retain_floor == 0.3:
target_retention = 0.6
elif retain_floor == 0.5:
target_retention = 0.7
elif retain_floor == 0.7:
target_retention = 0.8
bias_val = math.log(target_retention / (1.0 - target_retention))
nn.init.constant_(self.gate[0].bias, bias_val)
self.last_read_gate: Optional[torch.Tensor] = None
self.last_write_mask: Optional[torch.Tensor] = None
def init_memory(self, batch_size: int, device: torch.device) -> torch.Tensor:
return self.memory_init.unsqueeze(0).expand(batch_size, -1, -1).clone()
def forward(
self,
x: torch.Tensor,
memory_state: torch.Tensor,
domain_id: Optional[int] = None,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
x_norm = self.norm_x(x)
memory_state = memory_state + (self.memory_init * 0.0).unsqueeze(0)
mem_norm = self.norm_mem(memory_state)
# Read intervention: gated additive residual injection from memory.
read_out = self.read_attn(x_norm, mem_norm)
gate = self.read_gate(torch.cat([x, read_out], dim=-1))
read_delta = gate * read_out
x_new = x + read_delta
if not (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling()):
self.last_read_gate = gate.detach()
# Write intervention.
mem_query = mem_norm + self.memory_init.unsqueeze(0)
mem_update = self.write_attn(mem_query, x_norm)
affinity = self.affinity_gate(torch.cat([mem_norm, mem_update], dim=-1))
# Unified Cognitive Memory:
# Full capacity across all slots without artificial domain quadrant walls,
# exactly as trained during pretraining (30B tokens / 153k steps).
forget = self.gate(memory_state).clamp(self.retain_floor, 0.95)
candidate = forget * memory_state + (1.0 - forget) * (self.write_scale * mem_update)
new_memory = affinity * candidate + (1.0 - affinity) * memory_state
new_memory = self.mem_norm(new_memory)
if not (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling()):
self.last_write_mask = affinity.detach()
lb_loss = torch.zeros((), device=x.device, dtype=x.dtype)
return x_new, new_memory, lb_loss, gate, affinity, read_delta, forget
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# KV CACHE β Simple flat KV cache for inference
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class KVCache:
"""Simple KV cache for autoregressive inference."""
def __init__(self, num_layers: int):
self.num_layers = num_layers
self.kvs: List[Any] = [None] * num_layers
def get_past_len(self) -> int:
"""Get the sequence length of cached keys."""
for kv in self.kvs:
if kv is not None:
if hasattr(kv, 'seq_len'):
return kv.seq_len
return kv[0].shape[2]
return 0
def update(self, layer_idx: int, new_kv):
self.kvs[layer_idx] = new_kv
def reset(self):
self.kvs = [None] * self.num_layers
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# DYNAMIC SYSTEM 1 DECISION HEAD
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ---------------------------------------------------------------------------
# Dynamic Decision Head
# ---------------------------------------------------------------------------
class DynamicDecisionHead(nn.Module):
"""
Laya-Aligned Non-Causal Transformer Decision Head with GELU Non-Linear Scorer.
Clean, minimal, high-capacity, zero artificial heuristics:
1. Task & Domain Conditioning: type_emb(3, D) + domain_emb(16, D)
2. Non-Causal Bidirectional Comparator: [Q_cond, C_1, ..., C_K] -> TransformerEncoderLayer
3. Exact Laya Non-Linear Scorer: LayerNorm -> Linear(D, D) -> GELU -> Linear(D, 1)
Zero memory cross-attention, zero artificial scaling, zero distractor subtraction heuristics.
"""
def __init__(
self,
dim: int = 1280,
num_layers: int = 2,
heads: int = 16,
dropout: float = 0.10,
**kwargs,
):
super().__init__()
self.dim = dim
self.num_layers = num_layers if num_layers is not None else 2
# 1. Task & Domain Conditioning
self.type_emb = nn.Embedding(3, dim)
nn.init.normal_(self.type_emb.weight, std=0.02)
self.domain_emb = nn.Embedding(16, dim)
nn.init.normal_(self.domain_emb.weight, std=0.02)
# 2. 2-Layer Non-Causal Bidirectional Transformer Comparator (Exact Laya head_layers=2)
if self.num_layers > 0:
encoder_layer = nn.TransformerEncoderLayer(
d_model=dim,
nhead=heads,
dim_feedforward=4 * dim,
dropout=dropout,
batch_first=True,
norm_first=True, # Pre-LN
)
self.transformer = nn.TransformerEncoder(
encoder_layer,
num_layers=self.num_layers,
enable_nested_tensor=False,
)
for layer in self.transformer.layers:
nn.init.orthogonal_(layer.self_attn.out_proj.weight, gain=1.0)
nn.init.orthogonal_(layer.linear1.weight, gain=1.0)
nn.init.orthogonal_(layer.linear2.weight, gain=1.0)
else:
self.transformer = None
# 3. Causal Context Fusion (Solves Causal Option Blindness)
# Pre-LN normalizations and projection to inject global sequence summary Q
# into candidate vectors before entering comparator and scoring.
self.query_proj = nn.Linear(dim, dim)
nn.init.orthogonal_(self.query_proj.weight, gain=1.0)
nn.init.zeros_(self.query_proj.bias)
self.cand_norm = nn.LayerNorm(dim)
self.query_norm = nn.LayerNorm(dim)
self.fusion_norm = nn.LayerNorm(dim)
# 4. Exact Laya Non-Linear Scorer (LayerNorm -> Linear(D, D) -> GELU -> Linear(D, 1), NO DROPOUT)
self.scorer = nn.Sequential(
nn.LayerNorm(dim),
nn.Linear(dim, dim),
nn.GELU(),
nn.Linear(dim, 1),
)
for m in self.scorer.modules():
if isinstance(m, nn.Linear):
nn.init.orthogonal_(m.weight, gain=1.0)
if m.bias is not None:
nn.init.zeros_(m.bias)
def forward(
self,
global_context: Optional[torch.Tensor] = None,
candidate_hidden: Optional[torch.Tensor] = None,
candidate_mask: Optional[torch.Tensor] = None,
primitive_id: Optional[Any] = None,
domain_id: Optional[Any] = None,
sequence_context: Optional[torch.Tensor] = None,
candidate_positions: Optional[torch.Tensor] = None,
return_ablated: bool = False,
**kwargs,
) -> Any:
device = candidate_hidden.device if candidate_hidden is not None else sequence_context.device
B = candidate_hidden.size(0) if candidate_hidden is not None else sequence_context.size(0)
target_dtype = sequence_context.dtype if sequence_context is not None else (candidate_hidden.dtype if candidate_hidden is not None else torch.float32)
if primitive_id is not None:
p_idx = primitive_id if isinstance(primitive_id, torch.Tensor) else torch.tensor([primitive_id] * B, device=device)
p_idx = p_idx.to(device=device, dtype=torch.long).view(-1).clamp(0, 2)
if p_idx.numel() == 1 and B > 1:
p_idx = p_idx.expand(B)
t_emb = self.type_emb(p_idx)
else:
t_emb = torch.zeros((B, self.dim), device=device, dtype=target_dtype)
if domain_id is not None:
d_idx = domain_id if isinstance(domain_id, torch.Tensor) else torch.tensor([domain_id] * B, device=device)
d_idx = d_idx.to(device=device, dtype=torch.long).view(-1).clamp(0, 15)
if d_idx.numel() == 1 and B > 1:
d_idx = d_idx.expand(B)
d_emb = self.domain_emb(d_idx)
else:
d_emb = torch.zeros((B, self.dim), device=device, dtype=target_dtype)
cond = t_emb + d_emb # [B, D]
# 2. Extract Candidate representations via vectorized mean-pooling if not provided
if candidate_hidden is None:
if sequence_context is not None and candidate_positions is not None:
if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2:
prefix = torch.cat(
[
torch.zeros(B, 1, sequence_context.size(-1), device=device, dtype=sequence_context.dtype),
torch.cumsum(sequence_context, dim=1),
],
dim=1,
)
s = candidate_positions[:, :, 0].clamp(0, sequence_context.size(1) - 1)
e = candidate_positions[:, :, 1].clamp(0, sequence_context.size(1) - 1)
e = torch.maximum(s, e)
s_idx = s.unsqueeze(-1).expand(-1, -1, sequence_context.size(-1))
e_idx = (e + 1).unsqueeze(-1).expand(-1, -1, sequence_context.size(-1))
sum_s = torch.gather(prefix, dim=1, index=s_idx)
sum_e = torch.gather(prefix, dim=1, index=e_idx)
counts = (e - s + 1).unsqueeze(-1).float().clamp_min(1.0)
candidate_hidden = ((sum_e - sum_s) / counts).to(sequence_context.dtype)
else:
pos_idx = candidate_positions[:, :, -1] if candidate_positions.ndim == 3 else candidate_positions
pos_idx = pos_idx.clamp(0, sequence_context.size(1) - 1)
idx = pos_idx.unsqueeze(-1).expand(-1, -1, sequence_context.size(-1))
candidate_hidden = torch.gather(sequence_context, dim=1, index=idx)
else:
raise ValueError("candidate_hidden or (sequence_context and candidate_positions) must be provided.")
B, K, D = candidate_hidden.shape
if global_context is None:
global_context = sequence_context[:, -1, :] if sequence_context is not None else candidate_hidden.mean(dim=1)
# 3. Solves Causal Option Blindness:
# Candidate k was extracted from option k's token span in the causal autoregressive backbone.
# Early options (e.g. Option A) never attended to later options (B, C, D) in the backbone.
# Here, we inject the contextualized query Q (the final sequence token which HAS causally
# attended to the entire state, instructions, and all options) into each candidate vector:
Q_norm = self.query_norm(global_context + cond) # [B, D]
Q_proj = self.query_proj(Q_norm).unsqueeze(1) # [B, 1, D]
cand_injected = self.cand_norm(candidate_hidden + Q_proj + cond.unsqueeze(1)) # [B, K, D]
# 4. Form interaction sequence [Q_cond, C_1_cond, C_2_cond, ..., C_K_cond]
tokens = torch.cat([Q_norm.unsqueeze(1), cand_injected], dim=1) # [B, 1 + K, D]
# 5. Bidirectional Non-Causal Transformer Comparator (Exact Laya head_layers=2)
if self.transformer is not None:
if candidate_mask is not None:
q_mask = torch.zeros((B, 1), dtype=torch.bool, device=device)
pad_mask = torch.cat([q_mask, ~candidate_mask.bool().to(device)], dim=1)
else:
pad_mask = None
tokens_out = self.transformer(tokens, src_key_padding_mask=pad_mask)
Q_out = tokens_out[:, 0:1, :] # [B, 1, D]
cand_out = tokens_out[:, 1:, :] # [B, K, D]
else:
Q_out = Q_norm.unsqueeze(1)
cand_out = cand_injected
# 6. Contrastive Query-Candidate Scorer (Contextual Query Fused with Candidate)
# Evaluates the interaction between the contextualized query Q_out and each candidate cand_out
fused_cand = self.fusion_norm(cand_out + Q_out) # [B, K, D]
logits = self.scorer(fused_cand).squeeze(-1).float() # [B, K]
if candidate_mask is not None:
logits = logits.masked_fill(~candidate_mask.bool().to(device), -1e4)
if return_ablated:
return logits, logits
return logits
# Alias for backwards compatibility
StreamlinedDynamicDecisionHead = DynamicDecisionHead
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# NEXUS β The Main Model
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class Nexus(nn.Module):
"""Nexus β Clean transformer with neural memory.
Architecture:
Embed β Memoryβ β [Layer 0-6] β Memoryβ β [Layer 7-13] β Memoryβ β [Layer 14-19] β Head
Brain analogy:
Memoryβ = "What do I already know about this input?" (hippocampal retrieval)
Layers 0-6 = Sensory cortex (perception, pattern recognition)
Memoryβ = "Update what I've learned from perception" (hippocampal encoding)
Layers 7-13 = Association cortex (reasoning, integration)
Memoryβ = "Consolidate reasoning into memory" (hippocampal consolidation)
Layers 14-19 = Motor cortex (output generation)
"""
def __init__(
self,
vocab_size: int = 100_277,
dim: int = 1280,
heads: int = 16,
kv_heads: int = 4,
num_layers: int = 20,
memory_slots: int = 128,
use_flash: bool = False,
mtp_depths: int = 1,
decision_layers: int = 2,
decision_dropout: float = 0.10,
):
super().__init__()
self.dim = dim
self.heads = heads
self.num_layers = num_layers
# ββ Embedding ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.embed = nn.Embedding(vocab_size, dim)
nn.init.normal_(self.embed.weight, std=0.01)
# Domain Conditioning for Core Model & Neural Memory
self.domain_emb = nn.Embedding(16, dim)
nn.init.normal_(self.domain_emb.weight, std=0.02)
head_dim = dim // heads
self.rope = YaRNRotaryEmbedding(
head_dim, max_seq_len=8192,
original_max_len=2048, yarn_scale=8.0)
# ββ Transformer Layers βββββββββββββββββββββββββββββββββββββββββββββββ
self.layers = nn.ModuleList([
TransformerBlock(dim, heads, kv_heads, num_layers, i, use_flash, attn_scale=self.rope.attn_scale)
for i in range(num_layers)
])
# ββ Neural Memory (called at 3 strategic bridge points) ββββββββββββββ
# Step 9: Hierarchical Memory Specialization
memory_configs = [
{"slots": 32, "retain_floor": 0.3, "write_scale": 0.5, "role": "lexical"},
{"slots": 64, "retain_floor": 0.5, "write_scale": 0.3, "role": "semantic"},
{"slots": 128, "retain_floor": 0.7, "write_scale": 0.35, "role": "reasoning"},
]
self.memory = nn.ModuleList([
GlobalNeuralMemory(
dim,
num_slots=cfg["slots"],
heads=heads,
retain_floor=cfg["retain_floor"],
write_scale=cfg["write_scale"],
role=cfg["role"]
)
for cfg in memory_configs
])
# Legacy module retained only for pure-checkpoint compatibility.
# It is frozen and unused by Nexus Loss v2.
self.memory_predictor = nn.Linear(dim, dim, bias=False)
nn.init.normal_(self.memory_predictor.weight, std=0.01)
# Memory bridge schedule: after which layers to call memory
# Bridges shifted slightly deeper: [3, 10, 17]
self.memory_bridges = [3, 10, 17]
# ββ MTP Head ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.mtp_heads = nn.ModuleList([MTPHead(dim) for _ in range(mtp_depths)])
# ββ Output ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
self.norm = RMSNorm(dim)
# Output Reflection: lets the final layers read the newly written memory
# This ties the memory writing mechanism to the LM loss.
self.final_memory_read = CrossAttention(dim, heads, max(1, heads // 4))
self.final_memory_scale = nn.Parameter(torch.tensor(0.50))
self.final_memory_gate = nn.Linear(dim, 1)
nn.init.zeros_(self.final_memory_gate.weight)
nn.init.constant_(self.final_memory_gate.bias, 0.0) # Starts at gate=0.5
self.head = nn.Linear(dim, vocab_size, bias=False)
self.head.weight = self.embed.weight # Weight tying
# --- Dynamic System 1 Decision Head ---
# Candidate-count agnostic. It scores an arbitrary number K of
# candidate representations, rather than hard-coding 5 classes.
self.system1_head = DynamicDecisionHead(dim, num_layers=decision_layers, dropout=decision_dropout)
# Attention-weighted candidate span pooling: zero-initialized for exact mean-pooling equivalence at step 0
self.span_attn = nn.Linear(dim, 1, bias=False)
nn.init.zeros_(self.span_attn.weight)
self.use_system1_head = False
# Gradient checkpointing toggle (reduces activation VRAM by 85-90% during training)
self.gradient_checkpointing = True
# ββ Print summary βββββββββββββββββββββββββββββββββββββββββββββββββββ
total_params = sum(p.numel() for p in self.parameters())
print(f"[OK] Nexus initialized: {total_params:,} parameters ({total_params/1e9:.3f}B)")
print(f" Architecture: {num_layers} layers (dim={dim}, heads={heads}, kv_heads={kv_heads})")
print(f" Memory: {[c['slots'] for c in memory_configs]} slots Γ {dim}d at bridges {self.memory_bridges}")
print(f" FFN: SwiGLU ({int(2.67 * dim)}d hidden)")
print(f" MTP Heads: {mtp_depths}")
attn_desc = "FlashAttention-2 (Tri Dao)" if use_flash else "PyTorch Fused SDPA (Mem-Efficient Kernel for T4/SM75)"
print(f" Attention: {attn_desc}")
def project_logits(self, hidden: torch.Tensor) -> torch.Tensor:
return self.head(self.norm(hidden))
def forward(
self,
x: torch.Tensor,
memory_state: Optional[List[torch.Tensor]] = None,
kv_cache: Optional[KVCache] = None,
targets: Optional[torch.Tensor] = None,
return_intermediates: bool = False,
last_token_only: bool = False,
candidate_positions: Optional[torch.Tensor] = None,
candidate_mask: Optional[torch.Tensor] = None,
seq_lens: Optional[torch.Tensor] = None,
domain_id: Optional[int] = None,
primitive_id: Optional[Any] = None,
task_id: Optional[Any] = None,
disable_memory: Optional[bool] = None,
is_causal: Optional[bool] = None,
memory_only: bool = False,
**kwargs: Any,
) -> Any:
B, S = x.shape
h = self.embed(x)
# ββ Domain Conditioning for Core Model & Neural Memory βββββββββββββββ
if domain_id is not None:
if isinstance(domain_id, int):
d_idx = torch.tensor([domain_id] * B, device=x.device, dtype=torch.long)
elif isinstance(domain_id, torch.Tensor):
d_idx = domain_id.to(x.device, dtype=torch.long).view(-1)
if d_idx.numel() == 1 and B > 1:
d_idx = d_idx.expand(B)
else:
d_idx = torch.zeros(B, device=x.device, dtype=torch.long)
d_emb = self.domain_emb(d_idx.clamp(0, 15)).unsqueeze(1) # [B, 1, D]
h = h + d_emb
# ββ Memory Bypass Configuration βββββββββββββββββββββββββββββββββββββ
disable_mem = disable_memory if disable_memory is not None else getattr(self, "disable_memory", False)
# ββ Attention Causal Mode βββββββββββββββββββββββββββββββββββββββββββ
# Native causal masking matching 30B-token pretraining inductive bias.
if is_causal is not None:
causal_mode = is_causal
else:
causal_mode = (kv_cache is None)
# ββ RoPE ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
past_len = kv_cache.get_past_len() if kv_cache else 0
total_len = past_len + S
cos_full, sin_full = self.rope(h, total_len)
cos = cos_full[past_len:total_len]
sin = sin_full[past_len:total_len]
# ββ Initialize memory ββββββββββββββββββββββββββββββββββββββββββββββ
if not disable_mem and memory_state is None:
memory_state = [mem.init_memory(B, h.device) for mem in self.memory]
# ββ Forward through layers with memory bridges βββββββββββββββββββββ
bridge_idx = 0
new_memory_state = []
read_gates = []
read_deltas = []
write_masks = []
forget_gates = []
memory_deltas = []
for i, layer in enumerate(self.layers):
# Memory bridge BEFORE this layer group starts.
if not disable_mem and i in self.memory_bridges:
old_mem = memory_state[bridge_idx]
h, m_state, lb_loss, r_gate, affinity, read_delta, f_gate = self.memory[bridge_idx](
h, old_mem, domain_id=domain_id
)
new_memory_state.append(m_state)
read_gates.append(r_gate)
read_deltas.append(read_delta)
write_masks.append(affinity)
forget_gates.append(f_gate)
memory_deltas.append(m_state - old_mem)
bridge_idx += 1
# Transformer layer (with activation checkpointing during training to reduce VRAM by 85-90%)
pkv = kv_cache.kvs[i] if kv_cache else None
if self.training and kv_cache is None and getattr(self, "gradient_checkpointing", True):
from torch.utils.checkpoint import checkpoint
def _create_layer_forward(layer_module, causal_flag):
def _layer_forward(*inputs):
out_hidden, _ = layer_module(*inputs, is_causal=causal_flag)
return out_hidden
return _layer_forward
h = checkpoint(_create_layer_forward(layer, causal_mode), h, cos, sin, None, use_reentrant=False)
new_kv = None
else:
h, new_kv = layer(h, cos, sin, pkv, is_causal=causal_mode)
if kv_cache:
kv_cache.update(i, new_kv)
# ββ Output / Reflection βββββββββββββββββββββββββββββββββββββββββββ
h_normed = self.norm(h)
candidate_hidden = None
candidate_hidden_pre_reflection = None
reflection = None
reflection_gate = None
reflection_delta = None
memory_context = None
reflection_cand = None
mem_logits = None
refl_logits = None
global_context = None
ablated_logits = None
pre_reflection_h_normed = h_normed
if not disable_mem and new_memory_state:
# Reflection reads the CURRENT example's freshly written memory.
all_mem = torch.cat(new_memory_state, dim=1)
reflection = self.final_memory_read(h_normed, all_mem)
reflection_gate = 0.20 + 0.80 * torch.sigmoid(self.final_memory_gate(h_normed))
reflection_delta = reflection_gate * self.final_memory_scale * reflection
h = h + reflection_delta
h_normed = self.norm(h)
if (getattr(self, "use_system1_head", False) and not memory_only) or candidate_positions is not None:
if candidate_positions is None:
raise ValueError(
"Dynamic System 1 head requires candidate_positions "
"with shape [B,K]. Pass one position per option."
)
if candidate_positions.ndim not in (2, 3):
raise ValueError(
"candidate_positions must have shape [B,K] (single token) or [B,K,2] (spans), "
f"got {tuple(candidate_positions.shape)}"
)
if candidate_positions.shape[0] != B:
raise ValueError(
"candidate_positions batch dimension must match input batch: "
f"{candidate_positions.shape[0]} vs {B}"
)
if candidate_positions.dtype != torch.long:
candidate_positions = candidate_positions.long()
if candidate_positions.device != h_normed.device:
candidate_positions = candidate_positions.to(h_normed.device)
# Vectorized candidate extraction on GPU:
# When candidate_positions is [B, K, 2] (spans), compute exact span mean-pooling via prefix sum.
# When candidate_positions is [B, K] (single tokens), gather directly.
if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2:
# Attention-Weighted Candidate Span Extraction:
# Weights individual tokens in each option span via learned attention.
# Zero-initialized at step 0 to produce uniform 1/L weights (exact zero-drift match to mean pooling).
# During training, concentrates candidate representations onto decisive action verbs and condition clauses.
s = candidate_positions[:, :, 0].clamp(0, h_normed.size(1) - 1)
e = candidate_positions[:, :, 1].clamp(0, h_normed.size(1) - 1)
e = torch.maximum(s, e)
s_idx = s.unsqueeze(-1).expand(-1, -1, h_normed.size(-1))
e_idx = (e + 1).unsqueeze(-1).expand(-1, -1, h_normed.size(-1))
counts = (e - s + 1).unsqueeze(-1).float().clamp_min(1.0)
if hasattr(self, "span_attn"):
# Vectorized prefix-sum attention weighting over candidate spans:
# w_t = exp(span_attn(h_t))
# cand_k = sum_{t=s}^e (w_t * h_t) / sum_{t=s}^e w_t
# At step 0, span_attn.weight is 0 => w_t=1 => cand_k is exact mean pooling.
w = torch.exp(self.span_attn(h_normed).clamp(-10.0, 10.0))
wh = w * h_normed
w_prefix = torch.cat(
[torch.zeros(B, 1, 1, device=h_normed.device, dtype=h_normed.dtype),
torch.cumsum(w, dim=1)],
dim=1
)
wh_prefix = torch.cat(
[torch.zeros(B, 1, h_normed.size(-1), device=h_normed.device, dtype=h_normed.dtype),
torch.cumsum(wh, dim=1)],
dim=1
)
s_idx_1 = s.unsqueeze(-1)
e_idx_1 = (e + 1).unsqueeze(-1)
w_sum = torch.gather(w_prefix, dim=1, index=e_idx_1) - torch.gather(w_prefix, dim=1, index=s_idx_1)
wh_sum = torch.gather(wh_prefix, dim=1, index=e_idx) - torch.gather(wh_prefix, dim=1, index=s_idx)
candidate_hidden = (wh_sum / w_sum.clamp_min(1e-6)).to(h_normed.dtype)
else:
prefix = torch.cat(
[torch.zeros(B, 1, h_normed.size(-1), device=h_normed.device, dtype=h_normed.dtype),
torch.cumsum(h_normed, dim=1)],
dim=1
)
sum_s = torch.gather(prefix, dim=1, index=s_idx)
sum_e = torch.gather(prefix, dim=1, index=e_idx)
candidate_hidden = ((sum_e - sum_s) / counts).to(h_normed.dtype)
else:
pos_idx = candidate_positions[:, :, -1] if candidate_positions.ndim == 3 else candidate_positions
pos_idx = pos_idx.clamp(0, h_normed.size(1) - 1)
gather_idx = pos_idx.unsqueeze(-1).expand(-1, -1, h_normed.size(-1))
candidate_hidden = torch.gather(h_normed, dim=1, index=gather_idx)
# Preserve the unreflected candidate representation for the
# contrastive reflection objective. Passing the post-reflection
# candidate here would count reflection twice in its own target.
if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2:
pre_prefix = torch.cat(
[torch.zeros(B, 1, pre_reflection_h_normed.size(-1), device=pre_reflection_h_normed.device, dtype=pre_reflection_h_normed.dtype),
torch.cumsum(pre_reflection_h_normed, dim=1)], dim=1
)
pre_s_sum = torch.gather(pre_prefix, dim=1, index=s_idx)
pre_e_sum = torch.gather(pre_prefix, dim=1, index=e_idx)
candidate_hidden_pre_reflection = ((pre_e_sum - pre_s_sum) / counts).to(pre_reflection_h_normed.dtype)
else:
candidate_hidden_pre_reflection = torch.gather(
pre_reflection_h_normed, dim=1, index=gather_idx
)
# Multi-Module Cognitive Context Extraction:
# 1. Consolidated memory reasoning context (from Bridge 2 reasoning memory across all slots)
if new_memory_state and len(new_memory_state) > 0:
last_mem = new_memory_state[-1]
if last_mem.dim() == 3 and last_mem.size(1) > 0:
memory_context = last_mem.mean(dim=1)
# Vectorized Candidate-Level Reflection Extraction from reflection_delta:
# Enables true reflection telemetry and contrastive reflection verification without zero-placeholders.
if reflection_delta is not None and candidate_positions is not None:
if candidate_positions.ndim == 3 and candidate_positions.shape[-1] == 2:
refl_prefix = torch.cat(
[torch.zeros(B, 1, reflection_delta.size(-1), device=reflection_delta.device, dtype=reflection_delta.dtype),
torch.cumsum(reflection_delta, dim=1)],
dim=1
)
sum_s_r = torch.gather(refl_prefix, dim=1, index=s_idx)
sum_e_r = torch.gather(refl_prefix, dim=1, index=e_idx)
reflection_cand = ((sum_e_r - sum_s_r) / counts).to(reflection_delta.dtype)
else:
reflection_cand = torch.gather(reflection_delta, dim=1, index=gather_idx)
else:
reflection_cand = None
if seq_lens is not None:
batch_indices = torch.arange(B, device=h_normed.device)
last_indices = (seq_lens - 1).clamp_min(0)
global_context = h_normed[batch_indices, last_indices]
else:
global_context = h_normed[:, -1, :] # [B,D]
# Direct 3rd Neural Memory Block (Bridge 2, Layer 17: 128 slots) for Decision Head
mem3_slots = new_memory_state[-1] if (new_memory_state and len(new_memory_state) >= 3) else (torch.cat(new_memory_state, dim=1) if new_memory_state else None)
seq_mask = (torch.arange(S, device=h_normed.device).unsqueeze(0) < seq_lens.unsqueeze(1)) if seq_lens is not None else None
ablated_logits = None
if hasattr(self.system1_head, "forward"):
res = self.system1_head(
global_context,
candidate_hidden,
candidate_mask=candidate_mask,
primitive_id=primitive_id,
domain_id=domain_id,
memory_context=memory_context,
reflection_cand=reflection_cand,
memory_slots=mem3_slots,
sequence_context=h_normed,
sequence_mask=seq_mask,
candidate_positions=candidate_positions,
return_ablated=self.training,
)
if self.training:
logits, ablated_logits = res
else:
logits = res
else:
logits = self.system1_head(
global_context,
candidate_hidden,
candidate_mask=candidate_mask,
primitive_id=primitive_id,
memory_slots=all_memory_slots,
)
if last_token_only:
# Preserve the existing [B,1,K] interface expected by the
# training wrapper while keeping K dynamic.
logits = logits.unsqueeze(1)
if ablated_logits is not None:
ablated_logits = ablated_logits.unsqueeze(1)
else:
if last_token_only:
logits = self.head(h_normed[:, -1:, :])
else:
logits = self.head(h_normed)
# ββ MTP loss (multi-token prediction, training only) ββββββββββββββββ
mtp_loss = torch.tensor(0.0, device=h.device)
if targets is not None and self.training and len(self.mtp_heads) > 0:
mtp_losses = []
h_prev = h_normed
for d, mtp_head in enumerate(self.mtp_heads):
offset = d + 2 # predict token at position +2, +3, ...
if S <= offset:
break
tgt_ids = targets[:, d : -1]
tgt_embed = self.embed(tgt_ids)
h_prev_trunc = h_prev[:, : -1]
h_mtp = mtp_head(h_prev_trunc, tgt_embed)
labels = targets[:, d + 1 :]
if labels.shape[1] == 0:
break
# Memory-efficient chunked MTP logit & loss computation
loss_sum = torch.tensor(0.0, device=h_mtp.device)
h_mtp_flat = h_mtp.reshape(-1, h_mtp.size(-1))
labels_flat = labels.reshape(-1)
valid_tokens = (labels_flat != -1).sum()
chunk_size = 512 # Small chunk to prevent 100K vocab OOM
from torch.utils.checkpoint import checkpoint
# We use a static loop that torch.compile can unroll or trace
for start_idx in range(0, h_mtp_flat.size(0), chunk_size):
end_idx = min(start_idx + chunk_size, h_mtp_flat.size(0))
chunk_h = h_mtp_flat[start_idx:end_idx]
chunk_labels = labels_flat[start_idx:end_idx]
if self.training:
def _compute_chunk_loss(h, y):
return F.cross_entropy(self.head(h), y, ignore_index=-1, reduction='sum')
chunk_loss = checkpoint(_compute_chunk_loss, chunk_h, chunk_labels, use_reentrant=False)
else:
chunk_loss = F.cross_entropy(self.head(chunk_h), chunk_labels, ignore_index=-1, reduction='sum')
loss_sum = loss_sum + chunk_loss
loss_flat = loss_sum / valid_tokens.clamp(min=1)
mtp_losses.append(loss_flat)
h_prev = h_mtp
if mtp_losses:
mtp_loss = sum(mtp_losses) / len(mtp_losses)
# ββ Loss-v2 intervention telemetry βββββββββββββββββββββββββββββββββ
# The trainer converts these interventions into task-derived utility
# targets. No generic memory/predictor/diversity/coherence objective is
# computed inside the model.
if global_context is None:
global_context = h_normed[:, -1, :]
aux_dict = {
"read_gates": read_gates,
"read_deltas": read_deltas,
"write_masks": write_masks,
"forget_gates": forget_gates,
"memory_deltas": memory_deltas,
"reflection_gate": reflection_gate,
"reflection_delta": reflection_delta,
"candidate_hidden": candidate_hidden,
"candidate_hidden_pre_reflection": candidate_hidden_pre_reflection,
"memory_context": memory_context,
"reflection_cand": reflection_cand,
"global_context": global_context,
"fused_logits": logits,
"ablated_logits": ablated_logits,
# Backward compatibility for existing benchmark readers.
"refl_decision_logits": None,
"refl_sim": torch.zeros((), device=h.device, dtype=h.dtype),
"refl_ctx": torch.zeros((), device=h.device, dtype=h.dtype),
}
# ββ Return ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ponder = torch.tensor(1.0, device=h.device)
if targets is not None:
return logits, ponder, aux_dict, new_memory_state, mtp_loss, h_normed
elif return_intermediates:
return logits, ponder, aux_dict, new_memory_state, h_normed
return logits, ponder, aux_dict, new_memory_state
# Legacy memory-loss helpers intentionally removed from the active
# specialist objective. Routing supervision lives in the trainer.
def configure_optimizers(
self,
learning_rate: float,
weight_decay: float,
betas: Tuple[float, float] = (0.9, 0.95),
) -> torch.optim.AdamW:
decay, no_decay, hyper_decay = set(), set(), set()
for mn, m in self.named_modules():
for pn, _ in m.named_parameters(recurse=False):
fpn = f"{mn}.{pn}" if mn else pn
# HyperConnection alpha/beta get their own mild decay group
if isinstance(m, HyperConnection) and pn in ("alpha", "beta"):
hyper_decay.add(fpn)
elif pn.endswith("bias"):
no_decay.add(fpn)
elif pn.endswith("weight") and isinstance(m, (nn.Linear, nn.Embedding)):
decay.add(fpn)
else:
no_decay.add(fpn)
param_dict = dict(self.named_parameters())
optim_groups = [
{"params": [param_dict[p] for p in sorted(decay) if p in param_dict],
"weight_decay": weight_decay},
{"params": [param_dict[p] for p in sorted(no_decay) if p in param_dict],
"weight_decay": 0.0},
{"params": [param_dict[p] for p in sorted(hyper_decay) if p in param_dict],
"weight_decay": 0.01}, # mild decay to anchor alpha/beta near init
]
return torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, fused=torch.cuda.is_available())
# Backward-compatible alias so old checkpoint loading code still works
Cortex = Nexus
CortexV7 = Nexus
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# SANITY CHECK
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
print("Running Nexus sanity check β¦\n")
device = "cuda" if torch.cuda.is_available() else "cpu"
model = Nexus(
vocab_size = 100_277,
dim = 1280,
heads = 16,
kv_heads = 4,
num_layers = 20,
memory_slots = 128,
use_flash = True,
mtp_depths = 1,
).to(device)
# ββ Training forward pass ββββββββββββββββββββββββββββββββββββββββββββββ
print("\n[1] Training pass (batch=2, seq=64) β¦")
x = torch.randint(0, 100_277, (2, 64), device=device)
targets = torch.randint(0, 100_277, (2, 64), device=device)
model.train()
with torch.no_grad():
logits, ponder, aux, new_mem, mtp_loss, h_normed = model(x, targets=targets)
print(f" logits: {logits.shape} ponder: {ponder:.3f} mtp_loss: {mtp_loss:.4f}")
assert logits.shape == (2, 64, 100_277), f"Shape mismatch: {logits.shape}"
print(" [OK] Training pass OK")
# ββ Inference with KV cache ββββββββββββββββββββββββββββββββββββββββββββ
print("\n[2] Inference with KV cache (prefill 16 + generate 8) β¦")
model.eval()
cache = KVCache(num_layers=20)
prompt = torch.randint(0, 100_277, (1, 16), device=device)
with torch.no_grad():
logits_pre, _, _, mem, *_ = model(prompt, kv_cache=cache)
print(f" Prefill: {logits_pre.shape}, cache len: {cache.get_past_len()}")
next_token = logits_pre[:, -1, :].argmax(-1, keepdim=True)
for step in range(8):
with torch.no_grad():
logits_step, _, _, mem, *_ = model(next_token, memory_state=mem, kv_cache=cache)
next_token = logits_step[:, -1, :].argmax(-1, keepdim=True)
print(f" Generated 8 tokens. Cache len: {cache.get_past_len()}")
print(" [OK] KV Cache inference OK")
print(f"\n[OK] Nexus sanity check passed!")
print(f" {sum(p.numel() for p in model.parameters()):,} parameters")
print(f" Memory bridges at layers: {model.memory_bridges}")
|