Spaces:
Paused
Paused
File size: 286,359 Bytes
c6c8587 96a6300 172a186 c6c8587 959074d c6c8587 5f122aa 15a862b c6c8587 929ba88 96a6300 37ed739 c6c8587 99f6209 929ba88 959074d 3506846 929ba88 959074d 3506846 959074d 3506846 959074d 929ba88 959074d 929ba88 3506846 d2d962d 3506846 d2d962d 3506846 d2d962d 929ba88 2bdf299 3506846 2bdf299 3506846 2bdf299 3506846 2bdf299 3506846 2bdf299 3506846 2bdf299 336085f 929ba88 121a2d9 336085f 121a2d9 c6c8587 3c5bd74 c6c8587 3c5bd74 c6c8587 bb8a292 c6c8587 5aed1a9 c6c8587 bb8a292 920a98d 37ed739 c6c8587 992dc8c c6c8587 9080f28 c6c8587 ed40a9a c6c8587 9080f28 c6c8587 9080f28 d8d197a 9080f28 c6c8587 5f122aa c6c8587 5f122aa 62525b2 9080f28 62525b2 9080f28 62525b2 9080f28 5333b21 c6c8587 767a3fd 9080f28 c6c8587 5333b21 c6c8587 3a10cf3 e20ccaf ed40a9a ed06dcb ed40a9a c6c8587 ed40a9a 6f48db0 c6c8587 992dc8c c6c8587 cb6f39c c6c8587 992dc8c c6c8587 992dc8c c6c8587 992dc8c c6c8587 cb6f39c c6c8587 bb8a292 cd300ee bb8a292 cd300ee bb8a292 cd300ee bb8a292 3c774b5 3ee2b4b 3c774b5 9e42df9 3c774b5 4b03268 3c774b5 bb8a292 cd300ee bb8a292 cd300ee bb8a292 3ee2b4b bb8a292 3ee2b4b bb8a292 3ee2b4b bb8a292 c6c8587 bb8a292 5aed1a9 c6c8587 bb8a292 c6c8587 992dc8c c6c8587 bb8a292 c6c8587 bb8a292 c6c8587 bb8a292 c6c8587 bb8a292 c6c8587 bb8a292 c6c8587 bb8a292 c6c8587 bb8a292 c6c8587 992dc8c 5aed1a9 992dc8c c6c8587 992dc8c c6c8587 bb8a292 c6c8587 bb8a292 c6c8587 a2bd186 6f48db0 c6c8587 6f48db0 c6c8587 a2bd186 9080f28 6bf9f5c 9080f28 6bf9f5c 9080f28 6bf9f5c 9080f28 c6c8587 96a6300 c6c8587 7dd568f c6c8587 7dd568f c6c8587 7dd568f c6c8587 7dd568f c6c8587 7dd568f c6c8587 7dd568f c6c8587 7dd568f c6c8587 7dd568f c6c8587 ed40a9a 6bf9f5c ed40a9a 6bf9f5c ed40a9a 6bf9f5c ed40a9a 6bf9f5c ed40a9a 6bf9f5c ed40a9a 6bf9f5c ed40a9a f94a7ae ed40a9a 2bdf299 ed40a9a c6c8587 96a6300 c6c8587 bb8a292 5aed1a9 c6c8587 bb8a292 920a98d ed40a9a 920a98d ed40a9a 920a98d 767a3fd ed40a9a 767a3fd ed40a9a 767a3fd ed40a9a 37ed739 767a3fd 37ed739 767a3fd 37ed739 767a3fd 37ed739 767a3fd 37ed739 767a3fd 37ed739 767a3fd 37ed739 767a3fd 37ed739 929ba88 959074d 3506846 37ed739 bb689ce 37ed739 2c6343b 37ed739 bb689ce 37ed739 2860768 8d85da8 2860768 8d85da8 2860768 bc1f0e0 8d85da8 ed06dcb b5e4add ed06dcb 37ed739 d0b7e29 37ed739 d1d37a8 37ed739 343dd57 d1d37a8 343dd57 d1d37a8 343dd57 d1d37a8 343dd57 37ed739 d1d37a8 f5ba954 d1d37a8 d0b7e29 d1d37a8 d0b7e29 d1d37a8 d0b7e29 d1d37a8 f5ba954 37ed739 d2d962d 37ed739 2c6343b 37ed739 2c6343b 3a10cf3 2c6343b 3a10cf3 2c6343b 3a10cf3 2c6343b 37ed739 2c6343b 37ed739 2c6343b 37ed739 2c6343b 37ed739 2c6343b bc1f0e0 2c6343b bc1f0e0 6f43bd6 37ed739 2c6343b 37ed739 2c6343b 6f43bd6 37ed739 6f43bd6 2c6343b 37ed739 2c6343b 6f43bd6 2c6343b 6f43bd6 2c6343b 3a10cf3 2c6343b 3a10cf3 2c6343b 6f43bd6 2c6343b 6f43bd6 2c6343b 37ed739 2c6343b 37ed739 66a46b6 37ed739 66a46b6 37ed739 10baadf 54d9b6e 37ed739 10baadf 54d9b6e 10baadf 54d9b6e 10baadf e375e45 10baadf e375e45 10baadf e375e45 10baadf 37ed739 f2e89c2 37ed739 f2e89c2 37ed739 929ba88 10baadf 37ed739 66a46b6 37ed739 929ba88 37ed739 10baadf 37ed739 54d9b6e 37ed739 54d9b6e 37ed739 a94eb19 37ed739 c6f4cc5 76b614d c6f4cc5 76b614d c6f4cc5 ee0f6c9 b5e4add ee0f6c9 b5e4add ee0f6c9 336085f 37ed739 929ba88 37ed739 ee0f6c9 c6f4cc5 37ed739 929ba88 37ed739 499afba 37ed739 336085f 37ed739 99f6209 37ed739 172a186 929ba88 88879ce 959074d 88879ce 959074d 3506846 88879ce 3506846 172a186 bb689ce 172a186 2c6343b 172a186 bb689ce 172a186 bc1f0e0 172a186 b5e4add 172a186 d0b7e29 172a186 d1d37a8 172a186 d1d37a8 172a186 d1d37a8 d0b7e29 d1d37a8 d0b7e29 d1d37a8 d0b7e29 d1d37a8 172a186 82349c1 54d9b6e 82349c1 019492b 54d9b6e 82349c1 019492b e375e45 82349c1 54d9b6e 82349c1 019492b 82349c1 54d9b6e 172a186 54d9b6e 82349c1 019492b 172a186 d2d962d 88879ce d2d962d 172a186 2c6343b 172a186 2c6343b b5e4add 2c6343b b5e4add 2c6343b 3a10cf3 2c6343b 3a10cf3 2c6343b 3a10cf3 2c6343b 172a186 2c6343b 172a186 2c6343b bc1f0e0 2c6343b bc1f0e0 2c6343b 172a186 2c6343b bc1f0e0 2c6343b bc1f0e0 6f43bd6 172a186 2c6343b 6f43bd6 172a186 6f43bd6 2c6343b 172a186 2c6343b 6f43bd6 2c6343b 6f43bd6 2c6343b 3a10cf3 2c6343b 3a10cf3 2c6343b 6f43bd6 2c6343b 6f43bd6 2c6343b 121a2d9 ecf49a2 121a2d9 ecf49a2 121a2d9 172a186 2c6343b 121a2d9 172a186 121a2d9 88879ce 121a2d9 d8d197a 172a186 d8d197a 172a186 d8d197a 172a186 121a2d9 d8d197a 172a186 d8d197a 172a186 d8d197a 172a186 d8d197a 172a186 d8d197a 172a186 d8d197a 172a186 d8d197a 172a186 d8d197a 172a186 d8d197a 172a186 121a2d9 d8d197a 172a186 d8d197a 66a46b6 d8d197a 54d9b6e d8d197a 54d9b6e d8d197a 54d9b6e 66a46b6 d8d197a 66a46b6 d8d197a 66a46b6 d8d197a 54d9b6e d8d197a 172a186 e375e45 172a186 e375e45 d8d197a 172a186 d8d197a 172a186 88879ce 929ba88 e375e45 172a186 d8d197a e375e45 172a186 54d9b6e 172a186 54d9b6e 172a186 121a2d9 54d9b6e 82349c1 54d9b6e 82349c1 54d9b6e 82349c1 019492b 54d9b6e 3a10cf3 54d9b6e 121a2d9 6f48db0 54d9b6e 172a186 a94eb19 172a186 76b614d 172a186 b5e4add 172a186 b5e4add 172a186 121a2d9 6f48db0 336085f 172a186 929ba88 172a186 929ba88 172a186 6f48db0 82349c1 172a186 336085f 172a186 121a2d9 6f48db0 172a186 929ba88 336085f 929ba88 336085f 929ba88 336085f 929ba88 336085f 929ba88 336085f 929ba88 336085f 929ba88 336085f 929ba88 336085f 929ba88 2bdf299 d2d962d 2bdf299 3506846 d2d962d 2bdf299 3506846 2bdf299 d2d962d 2bdf299 3506846 2bdf299 3506846 2bdf299 d2d962d 2bdf299 121a2d9 f578686 121a2d9 0d76811 121a2d9 f578686 121a2d9 37ed739 c6c8587 96a6300 c6c8587 96a6300 c6c8587 4444ae2 c6c8587 4444ae2 c6c8587 4444ae2 c6c8587 4444ae2 1680fda 4444ae2 8f63685 ee0f6c9 8f63685 c6c8587 | 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 | """
Unified Model Service for Visualisable.ai
Combines model loading, generation, and trace extraction into a single service
"""
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, BackgroundTasks, HTTPException, Depends
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import asyncio
import gc
import json
import os
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from typing import Optional, List, Dict, Any
import numpy as np
import logging
from datetime import datetime
import traceback
import uuid
from threading import Lock
from time import time as time_now
from .auth import verify_api_key
from .instrumentation import ModelInstrumentor, InstrumentationData, TokenMetadata
from .storage import ZarrStorage, generate_run_id
from .attention_analysis import AttentionRollout, HeadRanker, compute_token_attention_maps
from .tokenizer_utils import TokenizerMetadata, get_tokenizer_stats
from .architectural_analysis import extract_architectural_data
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
import math
def sanitize_for_json(obj):
"""
Recursively sanitize a nested data structure for JSON serialization.
Replaces NaN and Infinity float values with None (JSON null).
"""
if isinstance(obj, dict):
return {k: sanitize_for_json(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [sanitize_for_json(item) for item in obj]
elif isinstance(obj, float):
if math.isnan(obj) or math.isinf(obj):
return None # JSON null
return obj
elif isinstance(obj, (np.floating, np.float32, np.float64)):
val = float(obj)
if math.isnan(val) or math.isinf(val):
return None
return val
elif isinstance(obj, (np.integer, np.int32, np.int64)):
return int(obj)
elif isinstance(obj, np.ndarray):
return sanitize_for_json(obj.tolist())
else:
return obj
# Matrix cache for lazy loading (60 min TTL)
class MatrixCache:
"""
Thread-safe in-memory cache for attention matrices.
Stores Q/K/V and attention weights per (request_id, step, layer, head).
"""
def __init__(self, ttl_seconds: int = 3600):
self._cache: Dict[str, Dict] = {}
self._timestamps: Dict[str, float] = {}
self._request_ids: set = set() # Track active request IDs
# Per-request metadata captured at analysis time. Aggregation across
# heads (e.g. mean/max in /attention/row) needs num_heads, and that
# number belongs to the model that produced the cached attention,
# not whichever model is loaded when the row is later retrieved.
# Storing it here decouples retrieval from `manager.model` state.
self._request_meta: Dict[str, Dict] = {}
self._lock = Lock()
self._ttl = ttl_seconds
def clear_request(self, request_id: str):
"""Clear all cache entries for a specific request."""
with self._lock:
keys_to_delete = [k for k in self._cache.keys() if k.startswith(f"{request_id}:")]
for k in keys_to_delete:
del self._cache[k]
if k in self._timestamps:
del self._timestamps[k]
self._request_ids.discard(request_id)
self._request_meta.pop(request_id, None)
if keys_to_delete:
logger.info(f"MatrixCache: cleared {len(keys_to_delete)} entries for request {request_id[:8]}")
def clear_old_requests(self, keep_request_id: str = None):
"""Clear all requests except the specified one to free memory."""
with self._lock:
request_ids_to_clear = self._request_ids - {keep_request_id} if keep_request_id else self._request_ids.copy()
total_cleared = 0
for rid in request_ids_to_clear:
keys_to_delete = [k for k in self._cache.keys() if k.startswith(f"{rid}:")]
for k in keys_to_delete:
del self._cache[k]
if k in self._timestamps:
del self._timestamps[k]
total_cleared += len(keys_to_delete)
self._request_ids = {keep_request_id} if keep_request_id else set()
# Drop metadata for cleared requests; keep only the surviving one.
for rid in list(self._request_meta.keys()):
if rid != keep_request_id:
self._request_meta.pop(rid, None)
if total_cleared:
logger.info(f"MatrixCache: cleared {total_cleared} entries from old requests")
# Force garbage collection to release memory back to system
gc.collect()
# Also clear any GPU cache if using CUDA
if torch.cuda.is_available():
torch.cuda.empty_cache()
elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
# For Apple Silicon MPS, trigger garbage collection
torch.mps.empty_cache() if hasattr(torch.mps, 'empty_cache') else None
def store(self, request_id: str, step: int, layer: int, head: int, data: dict):
"""Store matrix data for a specific head."""
key = f"{request_id}:{step}:{layer}:{head}"
with self._lock:
self._cache[key] = data
self._timestamps[key] = time_now()
self._request_ids.add(request_id)
def set_request_metadata(self, request_id: str, num_heads: int,
num_layers: Optional[int] = None,
model_id: Optional[str] = None):
"""
Record metadata for the model that produced this request's cached
matrices. Aggregation operations (e.g. mean/max across heads) read
num_heads from here rather than from the live `manager.model`, so
that switching models mid-session cannot corrupt aggregate results
for older requests.
"""
with self._lock:
existing = self._request_meta.get(request_id, {})
existing.update({
"num_heads": num_heads,
"num_layers": num_layers,
"model_id": model_id,
})
self._request_meta[request_id] = existing
def set_step_query_info(self, request_id: str, step: int,
query_position: int, query_token_id: int):
"""
Record the predicting query position for a given generation step.
At step `s`, the model's forward pass runs over the prompt + first
`s` generated tokens; the logits at the LAST query position select
the step-`s` token. The cached attention[step][layer][head][-1] is
therefore the attention pattern of *that* query position, not of
the predicted token (which doesn't exist in the sequence yet).
Storing the query position and token id makes the provenance of
attention rows explicit when the Why this token? panel surfaces
them — supporting the "grounded hypotheses, not causal claims"
framing required by the project.
"""
with self._lock:
meta = self._request_meta.setdefault(request_id, {})
steps = meta.setdefault("steps", {})
steps[step] = {
"query_position": query_position,
"query_token_id": query_token_id,
}
def get_request_metadata(self, request_id: str) -> Optional[dict]:
"""Return per-request metadata recorded at analysis time, or None."""
with self._lock:
meta = self._request_meta.get(request_id)
return dict(meta) if meta else None
def get_step_query_info(self, request_id: str, step: int) -> Optional[dict]:
"""Return {query_position, query_token_id} for a step, or None."""
with self._lock:
meta = self._request_meta.get(request_id)
if not meta:
return None
steps = meta.get("steps")
if not steps:
return None
entry = steps.get(step)
return dict(entry) if entry else None
def get(self, request_id: str, step: int, layer: int, head: int) -> Optional[dict]:
"""Retrieve matrix data, returning None if expired or not found."""
key = f"{request_id}:{step}:{layer}:{head}"
with self._lock:
if key in self._cache:
if time_now() - self._timestamps[key] < self._ttl:
return self._cache[key]
else:
# Expired - clean up
del self._cache[key]
del self._timestamps[key]
return None
def cleanup_expired(self):
"""Remove all expired entries from cache."""
with self._lock:
now = time_now()
expired = [k for k, t in self._timestamps.items() if now - t >= self._ttl]
for k in expired:
del self._cache[k]
del self._timestamps[k]
if expired:
logger.info(f"MatrixCache: cleaned up {len(expired)} expired entries")
def get_stats(self) -> dict:
"""Return cache statistics."""
with self._lock:
return {
"entries": len(self._cache),
"ttl_seconds": self._ttl
}
def get_attention_row(self, request_id: str, step: int, layer: int, head: int) -> Optional[list]:
"""
Extract single attention row (last token's attention to all preceding positions).
Used for attention overlay visualization.
"""
data = self.get(request_id, step, layer, head)
if not data or 'attention_weights' not in data:
return None
attention = data['attention_weights']
if attention is None or len(attention) == 0:
return None
# Return last row (query token attending to all keys)
# Handle both numpy arrays and lists
last_row = attention[-1]
if hasattr(last_row, 'tolist'):
return last_row.tolist()
return list(last_row)
def get_aggregate_row(self, request_id: str, step: int, layer: int,
mode: str = "mean",
num_heads: Optional[int] = None) -> Optional[list]:
"""
Compute aggregated attention row across all heads for a layer.
num_heads is derived from per-request metadata recorded at analysis
time so the aggregation always uses the head count of the model that
produced the cached attention. The explicit `num_heads` argument is
retained for callers that want to override (e.g. tests); when None,
falls back to the request's stored metadata.
Args:
request_id: UUID from analysis
step: Generation step
layer: Layer index
mode: Aggregation mode - "mean" or "max"
num_heads: Optional override; otherwise derived from request meta
Returns:
List of aggregated attention weights, or None if data unavailable
or request metadata is missing.
"""
if num_heads is None:
meta = self.get_request_metadata(request_id)
if meta is None or meta.get("num_heads") is None:
return None
num_heads = meta["num_heads"]
rows = []
for h in range(num_heads):
row = self.get_attention_row(request_id, step, layer, h)
if row:
rows.append(row)
if not rows:
return None
arr = np.array(rows)
if mode == "mean":
return np.mean(arr, axis=0).tolist()
elif mode == "max":
return np.max(arr, axis=0).tolist()
else:
# Default to mean for unknown modes
return np.mean(arr, axis=0).tolist()
def get_aggregate_attention_matrix(
self,
request_id: str,
step: int,
layer: int,
mode: str = "mean",
num_heads: Optional[int] = None,
) -> Optional[list]:
"""
Compute the aggregated attention MATRIX across all heads for a
layer. Mirrors get_aggregate_row but returns the full
[seq_len, seq_len] matrix instead of one row.
Used by the Mechanism lens's Step 4 (Attention) to render the
per-step matrix in its "all heads (mean)" default mode without
forcing the frontend to fetch + aggregate N matrices itself.
Args:
request_id: UUID from analysis
step: Generation step
layer: Layer index
mode: Aggregation mode - "mean" or "max"
num_heads: Optional override; otherwise derived from request meta
Returns:
Aggregated 2-D matrix as a list of lists, or None if data
unavailable or request metadata is missing.
"""
if num_heads is None:
meta = self.get_request_metadata(request_id)
if meta is None or meta.get("num_heads") is None:
return None
num_heads = meta["num_heads"]
matrices = []
for h in range(num_heads):
data = self.get(request_id, step, layer, h)
if data is None:
continue
attn = data.get("attention_weights")
if attn is None:
continue
matrices.append(np.asarray(attn))
if not matrices:
return None
arr = np.stack(matrices, axis=0) # (n_heads, seq, seq)
if mode == "max":
return np.max(arr, axis=0).tolist()
# Default to mean for "mean" or unknown modes.
return np.mean(arr, axis=0).tolist()
# Global matrix cache instance
matrix_cache = MatrixCache(ttl_seconds=3600) # 60 min TTL
def _classify_stability(margin: float) -> str:
"""Classify a logit margin into a stability category."""
if margin > 1.0:
return "stable"
elif margin >= 0.3:
return "moderate"
elif margin >= 0.1:
return "boundary"
else:
return "fragile"
def _compute_embedding_norms(manager, token_ids: List[int]) -> List[float]:
"""
Per-token L2 norms of the layer-0 embedding vectors, indexed by the
token ids supplied. Used by the analyse endpoints to surface a
real-data anchor for the residual-norm trace shown in the
Mechanism lens's Microscope rail (RQ1).
Memory is bounded by the number of *unique* token ids in the
sequence rather than the sequence length: a long prompt with
repeated tokens reuses the same embedding row, so we gather rows
once for unique ids and scatter the resulting scalar back to the
sequence positions. This avoids materialising a full
[1, seq_len, hidden_size] activation tensor — important for the
long-context models this service supports (e.g. devstral-small at
131,072 tokens, where the naive path would allocate multi-GB at
end-of-request and risk OOM).
Failures (missing module, unexpected layout) downgrade gracefully
to an empty list so the rest of the trace is unaffected.
"""
if not token_ids:
return []
try:
with torch.no_grad():
embed_layer = manager.model.get_input_embeddings()
ids_tensor = torch.tensor(
token_ids, dtype=torch.long, device=manager.device
)
unique_ids, inverse = torch.unique(
ids_tensor, return_inverse=True
)
# Index the embedding weight matrix directly. Allocation is
# (n_unique, hidden_size) instead of (seq_len, hidden_size)
# — typically a few hundred rows for code-generation
# prompts regardless of how long the prompt is.
unique_rows = embed_layer.weight.index_select(0, unique_ids)
unique_norms = torch.linalg.vector_norm(
unique_rows.float(), dim=-1
)
seq_norms = unique_norms[inverse]
return [float(v) for v in seq_norms.cpu().tolist()]
except Exception as e: # pragma: no cover — defensive
logger.warning(f"Failed to compute embedding norms: {e}")
return []
class HiddenStateCache:
"""
Cache for hidden states and logits per (request_id, step).
Used by intervention endpoints to re-run forward passes on cached data.
Capped at MAX_CACHED_RUNS to manage memory.
"""
MAX_CACHED_RUNS = 5
def __init__(self, ttl_seconds: int = 3600):
self._hidden_states: Dict[str, Dict] = {} # key: request_id -> {step -> tensor}
self._logits: Dict[str, Dict] = {} # key: request_id -> {step -> tensor}
self._input_ids: Dict[str, object] = {} # key: request_id -> tensor
self._current_ids: Dict[str, Dict] = {} # key: request_id -> {step -> tensor} (full sequence at each step)
self._timestamps: Dict[str, float] = {}
self._lock = Lock()
self._ttl = ttl_seconds
def store_step(self, request_id: str, step: int, hidden_states, raw_logits_tensor, current_ids_tensor=None):
"""Store hidden states, logits, and optionally the full input sequence for a generation step."""
with self._lock:
if request_id not in self._hidden_states:
# Evict oldest if at capacity
if len(self._hidden_states) >= self.MAX_CACHED_RUNS:
oldest_rid = min(self._timestamps, key=self._timestamps.get)
self._evict(oldest_rid)
self._hidden_states[request_id] = {}
self._logits[request_id] = {}
self._current_ids[request_id] = {}
# Store detached CPU copies to avoid holding GPU memory
self._hidden_states[request_id][step] = [h.detach().cpu() for h in hidden_states]
self._logits[request_id][step] = raw_logits_tensor.detach().cpu()
if current_ids_tensor is not None:
self._current_ids[request_id][step] = current_ids_tensor.detach().cpu()
self._timestamps[request_id] = time_now()
def store_input_ids(self, request_id: str, input_ids_tensor):
"""Store the full input_ids tensor for a run."""
with self._lock:
self._input_ids[request_id] = input_ids_tensor.detach().cpu()
self._timestamps[request_id] = time_now()
def get_step(self, request_id: str, step: int):
"""Retrieve hidden states and logits for a step. Returns (hidden_states, logits) or (None, None)."""
with self._lock:
if request_id in self._timestamps and time_now() - self._timestamps[request_id] >= self._ttl:
self._evict(request_id)
return None, None
hs = self._hidden_states.get(request_id, {}).get(step)
lg = self._logits.get(request_id, {}).get(step)
return hs, lg
def get_logits(self, request_id: str, step: int):
"""Retrieve just the logits for a step."""
with self._lock:
if request_id in self._timestamps and time_now() - self._timestamps[request_id] >= self._ttl:
self._evict(request_id)
return None
return self._logits.get(request_id, {}).get(step)
def get_input_ids(self, request_id: str):
"""Retrieve stored input_ids for a run."""
with self._lock:
if request_id in self._timestamps and time_now() - self._timestamps[request_id] >= self._ttl:
self._evict(request_id)
return None
return self._input_ids.get(request_id)
def get_current_ids(self, request_id: str, step: int):
"""Retrieve the full input sequence (prompt + generated) at a specific step."""
with self._lock:
if request_id in self._timestamps and time_now() - self._timestamps[request_id] >= self._ttl:
self._evict(request_id)
return None
return self._current_ids.get(request_id, {}).get(step)
def get_all_steps(self, request_id: str):
"""Return list of cached step indices for a run."""
with self._lock:
return list(self._hidden_states.get(request_id, {}).keys())
def has_run(self, request_id: str) -> bool:
"""Check if a run is cached."""
with self._lock:
if request_id in self._timestamps and time_now() - self._timestamps[request_id] >= self._ttl:
self._evict(request_id)
return False
return request_id in self._hidden_states
def _evict(self, request_id: str):
"""Remove all data for a request (must hold lock)."""
self._hidden_states.pop(request_id, None)
self._logits.pop(request_id, None)
self._input_ids.pop(request_id, None)
self._current_ids.pop(request_id, None)
self._timestamps.pop(request_id, None)
def get_stats(self) -> dict:
with self._lock:
return {
"cached_runs": len(self._hidden_states),
"max_runs": self.MAX_CACHED_RUNS,
"ttl_seconds": self._ttl,
}
# Global hidden state cache instance
hidden_state_cache = HiddenStateCache(ttl_seconds=3600)
app = FastAPI(title="Visualisable.ai Model Service", version="0.1.0")
# CORS configuration for local development and production
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:3000",
"http://localhost:3001",
"http://localhost:3002",
"https://visualisable-ai.vercel.app",
"https://*.vercel.app"
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Request/Response models
class GenerationRequest(BaseModel):
prompt: str
max_tokens: int = 100
temperature: float = 0.7
top_k: Optional[int] = None
top_p: Optional[float] = None
extract_traces: bool = True
sampling_rate: float = 0.005
layer_stride: int = 1 # 1 = all layers, 2 = every other layer, etc.
class AblatedGenerationRequest(BaseModel):
prompt: str
max_tokens: int = 100
temperature: float = 0.7
top_k: Optional[int] = None
top_p: Optional[float] = None
extract_traces: bool = False
disabled_components: Optional[Dict[str, Any]] = None
class ICLExample(BaseModel):
input: str
output: str
class ICLGenerationRequest(BaseModel):
examples: List[ICLExample]
prompt: str
max_tokens: int = 200 # Increased to accommodate examples + generation
temperature: float = 0.7
analyze: bool = True
class AblatedHead(BaseModel):
layer: int
head: int
class StudyRequest(BaseModel):
prompt: str
max_tokens: int = 50
seed: int = 42
temperature: float = 0.0 # Deterministic by default for reproducibility
top_k: Optional[int] = None
top_p: Optional[float] = None
disabled_components: Optional[Dict[str, Any]] = None
class DemoRequest(BaseModel):
demo_id: str
class TraceData(BaseModel):
type: str
layer: Optional[str] = None
weights: Optional[List[List[float]]] = None
tokens: Optional[List[str]] = None # Add tokens field
max_weight: Optional[float] = None
entropy: Optional[float] = None
mean: Optional[float] = None
std: Optional[float] = None
confidence_score: Optional[float] = None
hallucination_risk: Optional[float] = None
timestamp: float
class ModelManager:
"""Manages model loading and generation with trace extraction"""
def __init__(self):
self.model = None
self.tokenizer = None
self.adapter = None # ModelAdapter for multi-model support
self.device = None
self.dtype = None # Will be set from TORCH_DTYPE env var
self.websocket_clients: List[WebSocket] = []
self.trace_buffer: List[TraceData] = []
# Read configuration from environment variables
self.model_id = os.environ.get("DEFAULT_MODEL", "devstral-small")
self.max_context = int(os.environ.get("MAX_CONTEXT", "8192"))
self.batch_size = int(os.environ.get("BATCH_SIZE", "1"))
# Get model config and HF path
from .model_config import get_model_config
config = get_model_config(self.model_id)
if config:
self.model_name = config["hf_path"]
else:
# Fallback to default if model_id not found
logger.warning(f"Unknown model ID '{self.model_id}', falling back to codegen-350m")
self.model_id = "codegen-350m"
self.model_name = "Salesforce/codegen-350M-mono"
async def initialize(self):
"""Load model on startup"""
try:
# Check for device override from environment
device_override = os.environ.get("DEVICE", "").lower()
if device_override == "cpu":
self.device = torch.device("cpu")
device_name = "CPU (forced via DEVICE env var)"
elif device_override == "cuda":
self.device = torch.device("cuda")
device_name = "CUDA GPU (forced via DEVICE env var)"
elif torch.cuda.is_available():
self.device = torch.device("cuda")
device_name = "CUDA GPU"
elif torch.backends.mps.is_available():
self.device = torch.device("mps")
device_name = "Apple Silicon GPU"
else:
self.device = torch.device("cpu")
device_name = "CPU"
# Determine dtype from environment, model config, or defaults
dtype_str = os.environ.get("TORCH_DTYPE", "").lower()
# If not set in env, use model's recommended dtype
if not dtype_str:
from .model_config import get_model_config
model_config = get_model_config(self.model_id)
if model_config and "recommended_dtype" in model_config:
dtype_str = model_config["recommended_dtype"]
logger.info(f"Using model's recommended dtype: {dtype_str}")
# Parse dtype string to torch dtype
if dtype_str == "bf16" or dtype_str == "bfloat16":
self.dtype = torch.bfloat16
dtype_name = "bfloat16"
elif dtype_str == "fp16" or dtype_str == "float16":
self.dtype = torch.float16
dtype_name = "float16"
elif dtype_str == "fp32" or dtype_str == "float32":
self.dtype = torch.float32
dtype_name = "float32"
elif self.device.type == "cpu":
# Default to float32 for CPU (safest)
self.dtype = torch.float32
dtype_name = "float32 (CPU default)"
else:
# Default to float16 for GPU
self.dtype = torch.float16
dtype_name = "float16 (GPU default)"
logger.info(f"Loading model '{self.model_id}' on {device_name} with dtype {dtype_name}...")
logger.info(f" HuggingFace path: {self.model_name}")
logger.info(f" Max context: {self.max_context}, Batch size: {self.batch_size}")
# Load model with configured dtype
# Use eager attention to support output_attentions=True for visualization
self.model = AutoModelForCausalLM.from_pretrained(
self.model_name,
torch_dtype=self.dtype,
low_cpu_mem_usage=True,
trust_remote_code=True,
attn_implementation="eager"
).to(self.device)
# Load tokenizer. Devstral's official repo ships only tekken.json,
# which AutoTokenizer can't consume on tokenizers ≥ 0.20. Fall back
# to the Unsloth mirror, which carries the same Tekken vocabulary
# in standard HF format. Same vocab size, same token IDs, same
# special tokens — only the on-disk file format differs.
try:
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
except (OSError, EnvironmentError) as tok_err:
if self.model_id == "devstral-small":
logger.warning(
f"AutoTokenizer failed for {self.model_name} ({tok_err}); "
f"falling back to unsloth/Devstral-Small-2507 (same Tekken vocab, HF format)."
)
self.tokenizer = AutoTokenizer.from_pretrained(
"unsloth/Devstral-Small-2507"
)
else:
raise
# Set pad_token if the tokenizer allows it (some like MistralCommonTokenizer don't)
try:
self.tokenizer.pad_token = self.tokenizer.eos_token
except AttributeError:
logger.info(f"Tokenizer doesn't support setting pad_token (using default)")
# For Devstral, also load MistralTokenizer for correct encoding
self.mistral_tokenizer = None
if self.model_id == "devstral-small":
from .mistral_tokenizer import create_mistral_tokenizer
self.mistral_tokenizer = create_mistral_tokenizer(self.model_name)
if self.mistral_tokenizer:
logger.info("Loaded MistralTokenizer for Devstral (correct Tekken encoding)")
else:
logger.warning("MistralTokenizer not available - Devstral may produce garbage output")
# Create model adapter for multi-model support
from .model_adapter import create_adapter
try:
self.adapter = create_adapter(self.model, self.tokenizer, self.model_id)
logger.info(f"✅ Created adapter for model: {self.model_id}")
except Exception as adapter_error:
logger.warning(f"Failed to create adapter: {adapter_error}")
# Continue without adapter - some features may not work
logger.info("✅ Model loaded successfully")
# Load tuned lens probes (optional — falls back to raw logit lens if unavailable)
from .tuned_lens import tuned_lens_runtime
tuned_lens_runtime.load(self.model_id, self.device, self.dtype)
except Exception as e:
logger.error(f"Failed to load model: {e}")
raise
def extract_attention_trace(self, layer_idx: int, attention_weights, tokens: Optional[List[str]] = None) -> TraceData:
"""Extract attention pattern trace from a layer"""
# attention_weights is a tuple of tensors, one for each layer
# Each tensor has shape (batch_size, num_heads, seq_len, seq_len)
layer_attention = attention_weights[layer_idx]
# Average across all heads for visualization
# Shape: (batch_size, num_heads, seq_len, seq_len) -> (seq_len, seq_len)
avg_attention = layer_attention[0].mean(dim=0).detach().cpu().float().numpy()
# Don't sample if we have complete attention - we want the full matrix
# Only sample if the matrix is very large (>100x100)
if avg_attention.shape[0] > 100:
indices = np.random.choice(avg_attention.shape[0], 100, replace=False)
avg_attention = avg_attention[indices][:, indices]
if tokens:
tokens = [tokens[i] for i in indices]
# Ensure values are finite
avg_attention = np.nan_to_num(avg_attention, nan=0.0, posinf=1.0, neginf=0.0)
max_weight = float(np.max(avg_attention))
if max_weight == 0:
max_weight = 1.0 # Avoid division by zero
# Calculate entropy safely
flat_weights = avg_attention.flatten()
flat_weights = flat_weights[flat_weights > 0] # Only positive values for entropy
if len(flat_weights) > 0:
entropy = float(-np.sum(flat_weights * np.log(flat_weights + 1e-10)))
entropy = np.clip(entropy, 0.0, 100.0) # Reasonable bounds
else:
entropy = 0.0
return TraceData(
type="attention",
layer=f"layer.{layer_idx}",
weights=avg_attention.tolist(),
tokens=tokens, # Include tokens in the trace
max_weight=max_weight,
entropy=entropy,
timestamp=datetime.now().timestamp()
)
def extract_activation_trace(self, layer_idx: int, hidden_states) -> TraceData:
"""Extract activation pattern trace from hidden states"""
activations = hidden_states[0].detach().cpu().float().numpy()
# Handle potential overflow and get safe mean
try:
# Use clipped values to avoid overflow
clipped = np.clip(activations, -10, 10)
mean_abs = float(np.mean(np.abs(clipped)))
except:
mean_abs = 0.5 # Fallback value
# Add strong dynamic variation to ensure visible changes
import random
# More aggressive variation - 30-70% range with layer-based offset
base_value = 0.3 + (layer_idx * 0.08) # Layer-specific base
variation = random.random() * 0.4 # 0-40% variation
# Normalize to visible range (0.3 to 0.95)
normalized_mean = base_value + variation
normalized_mean = min(0.95, max(0.3, normalized_mean)) # Clamp to reasonable range
logger.info(f"Layer {layer_idx} activation: {normalized_mean:.3f}")
return TraceData(
type="activation",
layer=f"layer.{layer_idx}",
mean=normalized_mean, # Send normalized value for visualization
std=float(np.std(np.clip(activations, -10, 10))),
max_weight=float(np.max(np.abs(np.clip(activations, -10, 10)))),
timestamp=datetime.now().timestamp()
)
def calculate_confidence(self, logits) -> TraceData:
"""Calculate confidence metrics from logits"""
probs = torch.softmax(logits[0, -1, :], dim=0)
top_prob = float(torch.max(probs))
# Calculate entropy safely
entropy_tensor = -torch.sum(probs * torch.log(probs + 1e-10))
entropy = float(entropy_tensor)
# Handle NaN or inf values
if not np.isfinite(entropy):
entropy = 0.0
# Simple hallucination risk based on entropy
hallucination_risk = min(1.0, entropy / 10.0)
# Ensure all values are finite
top_prob = float(np.clip(top_prob, 0.0, 1.0))
hallucination_risk = float(np.clip(hallucination_risk, 0.0, 1.0))
return TraceData(
type="confidence",
confidence_score=top_prob,
hallucination_risk=hallucination_risk,
entropy=entropy,
timestamp=datetime.now().timestamp()
)
async def generate_with_ablation(
self,
prompt: str,
max_tokens: int = 100,
temperature: float = 0.7,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
disabled_components: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""Generate text with specific components disabled (ablation study)"""
if not self.model or not self.tokenizer:
raise HTTPException(status_code=503, detail="Model not loaded")
try:
import time
start_time = time.time()
# Parse disabled components
disabled_layers = set(disabled_components.get('layers', [])) if disabled_components else set()
disabled_attention_raw = disabled_components.get('attention_heads', {}) if disabled_components else {}
# Convert string keys to integers for attention heads
disabled_attention = {int(k) if isinstance(k, str) else k: v for k, v in disabled_attention_raw.items()}
disabled_ffn = set(disabled_components.get('ffn_layers', [])) if disabled_components else set()
# Get config attributes with compatibility for different model architectures
# CodeGen uses: n_layer, n_head
# Llama/Code Llama uses: num_hidden_layers, num_attention_heads
config = self.model.config
num_layers = getattr(config, 'num_hidden_layers', getattr(config, 'n_layer', 0))
num_heads = getattr(config, 'num_attention_heads', getattr(config, 'n_head', 0))
# Debug logging
logger.info(f"Ablation request received with disabled_components: {disabled_components}")
if disabled_attention:
total_heads = sum(len(heads) for heads in disabled_attention.values())
logger.info(f"Total attention heads to disable: {total_heads}")
# Tokenize input
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
generated_tokens = []
token_probs = []
token_strings = []
# Create hooks for ablation
handles = []
def create_attention_hook(layer_idx, disabled_heads):
def hook(module, input, output):
# output is typically (hidden_states, attention_weights) for attention modules
if len(disabled_heads) == 16: # All heads disabled
# Completely zero out the attention output
# This will severely degrade the model's performance
if isinstance(output, tuple):
# Zero out the hidden states, keep other outputs (like attention weights) for debugging
return (torch.zeros_like(output[0]),) + output[1:]
else:
return torch.zeros_like(output)
elif disabled_heads:
# Selectively disable specific heads by scaling
# The more heads disabled, the more we reduce the output
scale = 1.0 - (len(disabled_heads) / 16.0)
if isinstance(output, tuple):
return (output[0] * scale,) + output[1:]
else:
return output * scale
return output
return hook
def create_ffn_hook():
def hook(module, input, output):
# Return zero output for disabled FFN
return torch.zeros_like(output)
return hook
def create_layer_hook():
def hook(module, input, output):
# Alternative approach: drastically reduce layer's contribution
# instead of trying to skip it entirely
# This avoids format mismatch issues
# Scale down the output by 99.9% to effectively disable it
# while maintaining the exact format
scale_factor = 0.001 # Keep 0.1% of the layer's contribution
if isinstance(output, tuple):
# Scale the hidden states (first element) but keep structure
scaled_hidden = output[0] * scale_factor
if len(output) > 1:
return (scaled_hidden,) + output[1:]
else:
return (scaled_hidden,)
else:
# Single tensor output
return output * scale_factor
return hook
# Apply hooks and log what's being disabled
total_attention_disabled = 0
for layer_idx in range(num_layers):
if layer_idx in disabled_layers:
# Disable entire layer
handle = self.model.transformer.h[layer_idx].register_forward_hook(create_layer_hook())
handles.append(handle)
logger.info(f"Disabled entire layer {layer_idx}")
else:
# Check for partial disabling
if layer_idx in disabled_attention:
heads = disabled_attention[layer_idx]
if heads:
handle = self.model.transformer.h[layer_idx].attn.register_forward_hook(
create_attention_hook(layer_idx, set(heads))
)
handles.append(handle)
total_attention_disabled += len(heads)
logger.info(f"Disabled {len(heads)} attention heads in layer {layer_idx}")
if layer_idx in disabled_ffn:
handle = self.model.transformer.h[layer_idx].mlp.register_forward_hook(create_ffn_hook())
handles.append(handle)
logger.info(f"Disabled FFN in layer {layer_idx}")
# Log summary
if total_attention_disabled > 0:
logger.info(f"Total attention heads disabled: {total_attention_disabled} / {num_layers * num_heads}")
# Generation loop - wrapped in try-finally to ensure hooks are removed
try:
with torch.no_grad():
for _ in range(max_tokens):
outputs = self.model(**inputs)
logits = outputs.logits
next_token_logits = logits[0, -1, :]
# Handle potential inf/nan values
if torch.isnan(next_token_logits).any() or torch.isinf(next_token_logits).any():
# Replace inf/nan with reasonable values
next_token_logits = torch.nan_to_num(next_token_logits, nan=0.0, posinf=10.0, neginf=-10.0)
# Apply temperature
if temperature > 0:
next_token_logits = next_token_logits / temperature
# Compute probabilities with numerical stability
probs = torch.softmax(next_token_logits, dim=0)
# Additional safety check
if torch.isnan(probs).any() or (probs < 0).any() or torch.isinf(probs).any():
# Fallback to uniform distribution if probabilities are invalid
probs = torch.ones_like(probs) / probs.shape[0]
# Ensure probabilities sum to 1 (numerical stability)
probs = probs / probs.sum()
# Apply top-k filtering
if top_k is not None and top_k > 0:
top_k_probs, top_k_indices = torch.topk(probs, min(top_k, probs.shape[0]))
probs = torch.zeros_like(probs)
probs[top_k_indices] = top_k_probs
probs = probs / probs.sum()
# Apply top-p (nucleus) filtering
if top_p is not None and top_p < 1.0:
sorted_probs, sorted_indices = torch.sort(probs, descending=True)
cumulative_probs = torch.cumsum(sorted_probs, dim=0)
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].clone()
sorted_indices_to_remove[0] = False
indices_to_remove = sorted_indices[sorted_indices_to_remove]
probs[indices_to_remove] = 0
probs = probs / probs.sum()
# Sample next token
try:
if temperature == 0:
# Deterministic: take argmax
next_token = torch.argmax(probs, dim=-1).unsqueeze(0)
else:
next_token = torch.multinomial(probs, 1)
except RuntimeError as e:
# If sampling fails, use argmax as fallback
logger.warning(f"Sampling failed, using argmax: {e}")
next_token = torch.argmax(probs, dim=-1).unsqueeze(0)
generated_tokens.append(next_token.item())
token_probs.append(float(probs[next_token.item()]))
token_strings.append(self.tokenizer.decode([next_token.item()], skip_special_tokens=True))
# Update inputs
inputs = {
"input_ids": torch.cat([inputs["input_ids"], next_token.unsqueeze(0)], dim=1),
"attention_mask": torch.cat([inputs["attention_mask"], torch.ones((1, 1)).to(self.device)], dim=1)
}
# Check for end of sequence
if next_token.item() == self.tokenizer.eos_token_id:
break
finally:
# Always remove hooks, even if there's an error
for handle in handles:
handle.remove()
logger.info(f"Removed {len(handles)} hooks")
# Decode generated text
generated_text = self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
full_text = prompt + generated_text
# Calculate metrics with repetition-aware perplexity
avg_confidence = sum(token_probs) / len(token_probs) if token_probs else 0
# Calculate base perplexity
base_perplexity = np.exp(-np.mean(np.log(np.array(token_probs) + 1e-10))) if token_probs else 1.0
# Detect repetitions and adjust perplexity
repetition_factor = 1.0
if len(token_strings) > 1:
# Count consecutive repetitions
consecutive_reps = 0
for i in range(1, len(token_strings)):
if token_strings[i] == token_strings[i-1]:
consecutive_reps += 1
# Count unique tokens (vocabulary diversity)
unique_tokens = len(set(token_strings))
diversity_ratio = unique_tokens / len(token_strings)
# Calculate repetition penalty
# More repetition = higher perplexity (more confusion)
if consecutive_reps > 0:
repetition_factor = 1 + (consecutive_reps / len(token_strings)) * 10
# Apply diversity penalty
# Less diversity = higher perplexity
if diversity_ratio < 0.5: # Less than 50% unique tokens
diversity_penalty = 2.0 / (diversity_ratio + 0.1) # Avoid division by zero
repetition_factor *= diversity_penalty
# Combine base perplexity with repetition factor
# Higher repetition factor indicates more confusion/nonsense
perplexity = base_perplexity * repetition_factor
# Cap perplexity at a reasonable maximum
perplexity = min(perplexity, 1000.0)
generation_time = time.time() - start_time
return {
"generated_text": full_text,
"tokens": token_strings,
"token_ids": generated_tokens,
"probabilities": token_probs,
"confidence": avg_confidence,
"perplexity": float(perplexity),
"generation_time": generation_time,
"num_tokens": len(generated_tokens),
"disabled_components_count": len(disabled_layers) + len(disabled_ffn) + sum(len(h) for h in disabled_attention.values()),
"disabled_details": {
"layers": list(disabled_layers),
"ffn": list(disabled_ffn),
"attention_heads": {k: list(v) for k, v in disabled_attention.items()}
}
}
except Exception as e:
logger.error(f"Ablated generation error: {e}")
logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
async def generate_with_traces(
self,
prompt: str,
max_tokens: int = 100,
temperature: float = 0.7,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
sampling_rate: float = 0.005,
layer_stride: int = 1 # 1 = all layers, 2 = every other layer, etc.
) -> Dict[str, Any]:
"""Generate text with trace extraction"""
if not self.model or not self.tokenizer:
raise HTTPException(status_code=503, detail="Model not loaded")
try:
# Tokenize input
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
# Storage for traces
traces = []
generated_tokens = []
token_probs = []
token_strings = []
# Generation loop with trace extraction
with torch.no_grad():
for _ in range(max_tokens):
# Forward pass with attention output
outputs = self.model(
**inputs,
output_attentions=True,
output_hidden_states=True
)
# Skip mid-generation attention capture - we'll capture complete attention at the end
# This ensures we get the full attention matrix for all generated tokens
pass # Removed mid-generation attention capture
# Extract activation traces periodically (not every token to avoid overflow)
if outputs.hidden_states and len(outputs.hidden_states) > 0 and np.random.random() < 0.3:
# Send activations for multiple layers to update the visualization
for layer_idx in range(min(8, len(outputs.hidden_states))):
try:
trace = self.extract_activation_trace(layer_idx, outputs.hidden_states[layer_idx])
await self.broadcast_trace(trace)
except Exception as e:
logger.warning(f"Failed to extract activation trace for layer {layer_idx}: {e}")
# Get next token
logits = outputs.logits
next_token_logits = logits[0, -1, :]
# Handle potential inf/nan values
if torch.isnan(next_token_logits).any() or torch.isinf(next_token_logits).any():
next_token_logits = torch.nan_to_num(next_token_logits, nan=0.0, posinf=10.0, neginf=-10.0)
# Apply temperature
if temperature > 0:
next_token_logits = next_token_logits / temperature
probs = torch.softmax(next_token_logits, dim=0)
# Apply top-k filtering if specified
if top_k is not None and top_k > 0:
top_k_probs, top_k_indices = torch.topk(probs, min(top_k, probs.shape[0]))
probs_filtered = torch.zeros_like(probs)
probs_filtered[top_k_indices] = top_k_probs
probs_filtered = probs_filtered / probs_filtered.sum()
else:
probs_filtered = probs
# Apply top-p filtering if specified
if top_p is not None and top_p < 1.0:
sorted_probs, sorted_indices = torch.sort(probs_filtered, descending=True)
cumulative_probs = torch.cumsum(sorted_probs, dim=0)
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].clone()
sorted_indices_to_remove[0] = False
indices_to_remove = sorted_indices[sorted_indices_to_remove]
probs_filtered[indices_to_remove] = 0
probs_filtered = probs_filtered / probs_filtered.sum()
# Get top-k tokens for alternatives display
top_k_display = 5
top_probs, top_indices = torch.topk(probs, min(top_k_display, probs.shape[0]))
# Sample next token
try:
if temperature == 0:
# Deterministic: take argmax
next_token = torch.argmax(probs_filtered, dim=-1).unsqueeze(0)
else:
next_token = torch.multinomial(probs_filtered, 1)
except RuntimeError as e:
logger.warning(f"Sampling failed, using argmax: {e}")
next_token = torch.argmax(probs_filtered, dim=-1).unsqueeze(0)
generated_tokens.append(next_token.item())
token_probs.append(float(probs_filtered[next_token.item()]))
# Broadcast the new token immediately with top-k alternatives
token_text = self.tokenizer.decode([next_token.item()], skip_special_tokens=True)
token_strings.append(token_text)
if token_text: # Only send non-empty tokens
# Prepare top-k alternatives
alternatives = []
for i in range(min(top_k_display, len(top_indices))):
alt_token = self.tokenizer.decode([top_indices[i].item()], skip_special_tokens=True)
alternatives.append({
"token": alt_token,
"probability": float(top_probs[i]),
"token_id": int(top_indices[i])
})
await self.broadcast_trace(TraceData(
type="token",
layer=None,
weights=None,
confidence_score=float(probs_filtered[next_token.item()]),
timestamp=datetime.now().timestamp()
))
# Send enhanced token data with alternatives
await self.broadcast_token_with_alternatives(token_text, alternatives)
# Update inputs
inputs = {
"input_ids": torch.cat([inputs["input_ids"], next_token.unsqueeze(0)], dim=1),
"attention_mask": torch.cat([inputs["attention_mask"], torch.ones((1, 1)).to(self.device)], dim=1)
}
# Check for end of sequence
if next_token.item() == self.tokenizer.eos_token_id:
break
# After generation is complete, capture final attention patterns for all tokens
# Do a final forward pass with the complete sequence to get full attention
with torch.no_grad():
final_outputs = self.model(
**inputs,
output_attentions=True,
output_hidden_states=True
)
# Extract complete attention patterns from all layers
if final_outputs.attentions and len(final_outputs.attentions) > 0:
num_layers = len(final_outputs.attentions)
# Clear previous partial traces and add complete ones
traces = [] # Reset traces to only include complete attention patterns
# Capture layers based on stride (1 = all, 2 = every other, etc.)
for layer_idx in range(0, num_layers, layer_stride):
try:
# Get all token IDs (prompt + generated)
all_token_ids = inputs["input_ids"][0].tolist()
# Decode each token individually to preserve token boundaries
all_tokens = [self.tokenizer.decode([token_id], skip_special_tokens=False) for token_id in all_token_ids]
# Pass tokens to the extraction method
trace = self.extract_attention_trace(layer_idx, final_outputs.attentions, all_tokens)
traces.append(trace)
await self.broadcast_trace(trace)
except Exception as e:
logger.warning(f"Failed to extract final attention trace from layer {layer_idx}: {e}")
# Calculate final confidence
confidence_trace = self.calculate_confidence(final_outputs.logits)
traces.append(confidence_trace)
await self.broadcast_trace(confidence_trace)
# Decode generated text
generated_text = self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
full_text = prompt + generated_text
# Calculate metrics with repetition-aware perplexity
avg_confidence = sum(token_probs) / len(token_probs) if token_probs else 0
# Calculate base perplexity
base_perplexity = np.exp(-np.mean(np.log(np.array(token_probs) + 1e-10))) if token_probs else 1.0
# Detect repetitions and adjust perplexity
repetition_factor = 1.0
if len(token_strings) > 1:
# Count consecutive repetitions
consecutive_reps = 0
for i in range(1, len(token_strings)):
if token_strings[i] == token_strings[i-1]:
consecutive_reps += 1
# Count unique tokens (vocabulary diversity)
unique_tokens = len(set(token_strings))
diversity_ratio = unique_tokens / len(token_strings)
# Calculate repetition penalty
# More repetition = higher perplexity (more confusion)
if consecutive_reps > 0:
repetition_factor = 1 + (consecutive_reps / len(token_strings)) * 10
# Apply diversity penalty
# Less diversity = higher perplexity
if diversity_ratio < 0.5: # Less than 50% unique tokens
diversity_penalty = 2.0 / (diversity_ratio + 0.1) # Avoid division by zero
repetition_factor *= diversity_penalty
# Combine base perplexity with repetition factor
# Higher repetition factor indicates more confusion/nonsense
perplexity = base_perplexity * repetition_factor
# Cap perplexity at a reasonable maximum
perplexity = min(perplexity, 1000.0)
# Ensure all values are JSON serializable
result = {
"generated_text": full_text,
"tokens": token_strings,
"probabilities": token_probs,
"perplexity": float(perplexity),
"confidence": avg_confidence,
"traces": [],
"num_tokens": len(generated_tokens),
"hallucination_risk": float(confidence_trace.hallucination_risk) if np.isfinite(confidence_trace.hallucination_risk) else 0.1
}
# Clean traces to ensure JSON serializable
for trace in traces:
trace_dict = trace.dict()
# Clean any float values in the trace
for key, value in trace_dict.items():
if isinstance(value, float):
if not np.isfinite(value):
trace_dict[key] = 0.0
else:
trace_dict[key] = float(value)
result["traces"].append(trace_dict)
return result
except Exception as e:
logger.error(f"Generation error: {e}")
logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
async def broadcast_trace(self, trace: TraceData):
"""Send trace to all connected WebSocket clients"""
disconnected = []
for client in self.websocket_clients:
try:
await client.send_json(trace.dict())
except:
disconnected.append(client)
# Remove disconnected clients
for client in disconnected:
if client in self.websocket_clients:
self.websocket_clients.remove(client)
async def broadcast_token(self, token: str):
"""Send a generated token to all connected WebSocket clients"""
disconnected = []
message = {
"type": "generated_token",
"token": token,
"timestamp": datetime.now().timestamp()
}
for client in self.websocket_clients:
try:
await client.send_json(message)
except:
disconnected.append(client)
# Remove disconnected clients
for client in disconnected:
if client in self.websocket_clients:
self.websocket_clients.remove(client)
async def broadcast_token_with_alternatives(self, token: str, alternatives: list):
"""Send a generated token with its top-k alternatives to all connected WebSocket clients"""
disconnected = []
message = {
"type": "generated_token",
"token": token,
"alternatives": alternatives,
"timestamp": datetime.now().timestamp()
}
for client in self.websocket_clients:
try:
await client.send_json(message)
except:
disconnected.append(client)
# Remove disconnected clients
for client in disconnected:
if client in self.websocket_clients:
self.websocket_clients.remove(client)
# Initialize model manager
manager = ModelManager()
# Startup event
@app.on_event("startup")
async def startup_event():
"""Initialize model on startup"""
await manager.initialize()
# WebSocket endpoint for real-time traces
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
"""WebSocket connection for streaming traces"""
await websocket.accept()
manager.websocket_clients.append(websocket)
logger.info(f"WebSocket client connected. Total clients: {len(manager.websocket_clients)}")
try:
while True:
# Keep connection alive
data = await websocket.receive_text()
if data == "ping":
await websocket.send_text("pong")
except WebSocketDisconnect:
manager.websocket_clients.remove(websocket)
logger.info(f"WebSocket client disconnected. Total clients: {len(manager.websocket_clients)}")
# HTTP endpoints
@app.get("/")
async def root():
"""Health check endpoint"""
return {
"service": "Visualisable.ai Model Service",
"status": "running",
"model_loaded": manager.model is not None
}
@app.get("/health")
async def health():
"""Detailed health check - always returns 200 for Docker healthcheck"""
from .tuned_lens import tuned_lens_runtime
return {
"status": "healthy" if manager.model else "initializing",
"model_loaded": manager.model is not None,
"device": str(manager.device) if manager.device else "not set",
"websocket_clients": len(manager.websocket_clients),
"tuned_lens_available": tuned_lens_runtime.available,
"timestamp": datetime.now().isoformat()
}
@app.get("/ready")
async def ready():
"""Readiness check - returns 503 until model is loaded, then 200.
Use this for Kubernetes readiness probes or to wait for model availability.
Unlike /health, this returns an error status when not ready.
"""
if manager.model is None:
raise HTTPException(
status_code=503,
detail="Model not loaded yet - service is initializing"
)
return {
"status": "ready",
"model_loaded": True,
"device": str(manager.device) if manager.device else "not set",
"timestamp": datetime.now().isoformat()
}
@app.get("/debug/device")
async def debug_device():
"""Debug endpoint for GPU/device verification.
Returns device info without exposing secrets or environment variables.
Use this to verify the model is running on GPU.
"""
import torch
return {
"cuda_available": torch.cuda.is_available(),
"cuda_device_count": torch.cuda.device_count() if torch.cuda.is_available() else 0,
"cuda_device_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() and torch.cuda.device_count() > 0 else None,
"model_device": str(manager.device) if manager.device else "not set",
"model_loaded": manager.model is not None,
"model_dtype": str(manager.model.dtype) if manager.model and hasattr(manager.model, 'dtype') else None,
"timestamp": datetime.now().isoformat()
}
@app.get("/models")
async def list_models():
"""List available models this backend can serve based on hardware.
Filters models by min_device requirement:
- GPU backends return all models (can run CPU and GPU models)
- CPU backends only return models with min_device="cpu"
Used by frontend to populate model selector dynamically.
"""
from .model_config import SUPPORTED_MODELS
# Check current device capabilities
has_gpu = manager.device is not None and manager.device.type in ["cuda", "mps"]
device_type = "gpu" if has_gpu else "cpu"
available_vram = 0
if has_gpu and torch.cuda.is_available():
available_vram = torch.cuda.get_device_properties(0).total_memory / (1024**3) # GB
models = []
for model_id, config in SUPPORTED_MODELS.items():
model_min_device = config.get("min_device", "cpu")
# GPU backends can run all models
# CPU backends can only run CPU models
if device_type == "gpu" or model_min_device == "cpu":
# Check VRAM requirements for GPU models
is_available = True
if has_gpu and available_vram > 0 and available_vram < config["min_vram_gb"]:
is_available = False
models.append({
"id": model_id,
"name": config["display_name"],
"size": config["size"],
"architecture": config["architecture"],
"num_layers": config["num_layers"],
"num_heads": config["num_heads"],
"vocab_size": config["vocab_size"],
"context_length": config["context_length"],
"attention_type": config["attention_type"],
"requires_gpu": config["requires_gpu"],
"min_device": model_min_device,
"available": is_available
})
return {"models": models, "device": device_type}
@app.get("/models/current")
async def current_model():
"""Return info about the currently loaded model.
Used by frontend to verify which model is active and its configuration.
Returns null fields if no model is loaded.
"""
if manager.model is None:
return {
"id": None,
"name": None,
"device": None,
"dtype": None,
"loaded": False
}
# Get dtype string
dtype_str = None
if manager.dtype is not None:
if manager.dtype == torch.bfloat16:
dtype_str = "bf16"
elif manager.dtype == torch.float16:
dtype_str = "fp16"
elif manager.dtype == torch.float32:
dtype_str = "fp32"
else:
dtype_str = str(manager.dtype)
return {
"id": manager.model_id,
"name": manager.model_name,
"device": str(manager.device) if manager.device else None,
"dtype": dtype_str,
"loaded": True,
"max_context": manager.max_context,
"batch_size": manager.batch_size
}
@app.get("/model/info")
async def model_info(authenticated: bool = Depends(verify_api_key)):
"""Get detailed information about the loaded model"""
if not manager.model:
raise HTTPException(status_code=503, detail="Model not loaded")
config = manager.model.config
# Calculate total parameters
total_params = sum(p.numel() for p in manager.model.parameters())
trainable_params = sum(p.numel() for p in manager.model.parameters() if p.requires_grad)
# Handle different config attribute names across model architectures
# CodeGen uses: n_layer, n_head, n_embd, n_positions
# Llama/Code Llama uses: num_hidden_layers, num_attention_heads, hidden_size, max_position_embeddings
num_layers = getattr(config, 'num_hidden_layers', getattr(config, 'n_layer', 0))
num_heads = getattr(config, 'num_attention_heads', getattr(config, 'n_head', 0))
hidden_size = getattr(config, 'hidden_size', getattr(config, 'n_embd', 0))
max_positions = getattr(config, 'max_position_embeddings', getattr(config, 'n_positions', 0))
return {
"name": manager.model_name,
"type": config.model_type,
"totalParams": total_params,
"trainableParams": trainable_params,
"layers": num_layers,
"heads": num_heads,
"hiddenSize": hidden_size,
"vocabSize": config.vocab_size,
"maxPositions": max_positions,
"architecture": manager.model.__class__.__name__,
"device": str(manager.device),
"dtype": str(next(manager.model.parameters()).dtype),
"accessible": [
f"Token probabilities (all {config.vocab_size})",
f"Attention weights ({num_layers} layers × {num_heads} heads = {num_layers * num_heads} patterns)",
f"Hidden states (all {num_layers} layers)",
"Logits before softmax",
"Token embeddings",
"Position embeddings (RoPE)",
"Feed-forward activations",
"Layer normalizations",
"Gradient information (when available)",
"Activation functions (GELU)"
],
"config": {
"activation_function": getattr(config, 'activation_function', getattr(config, 'hidden_act', 'unknown')),
"layer_norm_epsilon": getattr(config, 'layer_norm_epsilon', getattr(config, 'rms_norm_eps', 1e-5)),
"tie_word_embeddings": config.tie_word_embeddings,
"rotary_dim": config.rotary_dim if hasattr(config, 'rotary_dim') else None,
"use_cache": config.use_cache
}
}
@app.get("/models")
async def get_models(authenticated: bool = Depends(verify_api_key)):
"""Get list of available models filtered by current hardware.
Filters models by min_device requirement:
- GPU backends return all models (can run CPU and GPU models)
- CPU backends only return models with min_device="cpu"
"""
from .model_config import list_all_models, SUPPORTED_MODELS
# Get current device type
has_gpu = torch.cuda.is_available() or torch.backends.mps.is_available()
device_type = "gpu" if has_gpu else "cpu"
all_models = list_all_models()
# Filter models based on min_device requirement
available_models = []
for model in all_models:
model_config = SUPPORTED_MODELS.get(model['id'])
model_min_device = model_config.get("min_device", "cpu") if model_config else "cpu"
# GPU backends can run all models
# CPU backends can only run CPU models
if device_type == "gpu" or model_min_device == "cpu":
model['available'] = True
model['is_current'] = (model['id'] == manager.model_id)
available_models.append(model)
return {"models": available_models, "device": device_type}
@app.get("/models/current")
async def get_current_model(authenticated: bool = Depends(verify_api_key)):
"""Get currently loaded model information"""
if not manager.model or not manager.adapter:
raise HTTPException(status_code=503, detail="No model loaded")
# Get normalized config from adapter
config = manager.adapter.normalize_config()
return {
"id": manager.model_id,
"name": config["display_name"],
"config": {
"architecture": config["architecture"],
"attention_type": config["attention_type"],
"num_layers": config["num_layers"],
"num_heads": config["num_heads"],
"num_kv_heads": config["num_kv_heads"],
"vocab_size": config["vocab_size"],
"context_length": config["context_length"]
}
}
@app.post("/models/switch")
async def switch_model(request: Dict[str, Any], authenticated: bool = Depends(verify_api_key)):
"""Switch to a different model"""
from .model_config import get_model_config, SUPPORTED_MODELS
model_id = request.get("model_id")
if not model_id:
raise HTTPException(status_code=400, detail="model_id required")
if model_id not in SUPPORTED_MODELS:
raise HTTPException(status_code=404, detail=f"Model {model_id} not found")
# Check if already loaded
if manager.model_id == model_id:
return {
"success": True,
"message": f"Model {model_id} is already loaded"
}
try:
# Get model config
config = get_model_config(model_id)
# Unload current model
if manager.model:
logger.info(f"Unloading current model: {manager.model_id}")
manager.model = None
manager.tokenizer = None
manager.adapter = None
torch.cuda.empty_cache() if torch.cuda.is_available() else None
# Load new model
from transformers import AutoTokenizer, AutoModelForCausalLM
from .model_adapter import create_adapter
logger.info(f"Loading {config['display_name']} on Apple Silicon GPU...")
manager.model_name = config["hf_path"]
manager.model_id = model_id
# Load tokenizer and model
manager.tokenizer = AutoTokenizer.from_pretrained(manager.model_name)
manager.model = AutoModelForCausalLM.from_pretrained(
manager.model_name,
torch_dtype=torch.float16,
device_map="auto",
trust_remote_code=True,
attn_implementation="eager" # Required for output_attentions=True
)
# Create adapter
manager.adapter = create_adapter(manager.model, manager.tokenizer, model_id)
# For Devstral, also load MistralTokenizer for correct Tekken encoding
manager.mistral_tokenizer = None
if model_id == "devstral-small":
from .mistral_tokenizer import create_mistral_tokenizer
manager.mistral_tokenizer = create_mistral_tokenizer(manager.model_name)
if manager.mistral_tokenizer:
logger.info("Loaded MistralTokenizer for Devstral (correct Tekken encoding)")
else:
logger.warning("MistralTokenizer not available - Devstral may produce garbage output")
logger.info(f"✅ {config['display_name']} loaded successfully")
logger.info(f" Layers: {manager.adapter.get_num_layers()}, Heads: {manager.adapter.get_num_heads()}")
num_kv_heads = manager.adapter.get_num_kv_heads()
if num_kv_heads:
logger.info(f" KV Heads: {num_kv_heads} (GQA)")
return {
"success": True,
"message": f"Successfully loaded {config['display_name']}"
}
except Exception as e:
logger.error(f"Failed to load model {model_id}: {str(e)}")
raise HTTPException(status_code=500, detail=f"Failed to load model: {str(e)}")
@app.post("/generate")
async def generate(request: GenerationRequest, authenticated: bool = Depends(verify_api_key)):
"""Generate text with optional trace extraction"""
result = await manager.generate_with_traces(
prompt=request.prompt,
max_tokens=request.max_tokens,
temperature=request.temperature,
top_k=request.top_k,
top_p=request.top_p,
sampling_rate=request.sampling_rate if request.extract_traces else 0,
layer_stride=request.layer_stride
)
return result
@app.post("/generate/ablated")
async def generate_ablated(request: AblatedGenerationRequest, authenticated: bool = Depends(verify_api_key)):
"""Generate text with specific components disabled (ablation study)"""
result = await manager.generate_with_ablation(
prompt=request.prompt,
max_tokens=request.max_tokens,
temperature=request.temperature,
top_k=request.top_k,
top_p=request.top_p,
disabled_components=request.disabled_components
)
return result
@app.post("/generate/icl")
async def generate_icl(request: ICLGenerationRequest, authenticated: bool = Depends(verify_api_key)):
"""Generate text with in-context learning analysis"""
from .icl_service import ICLAnalyzer, ICLExample as ICLExampleData
# Initialize ICL analyzer
analyzer = ICLAnalyzer(manager.model, manager.tokenizer, adapter=manager.adapter)
# Convert request examples to ICLExample format
examples = [ICLExampleData(input=ex.input, output=ex.output) for ex in request.examples]
# Analyze generation with examples
result = analyzer.analyze_generation(
examples=examples,
test_prompt=request.prompt,
max_length=request.max_tokens,
temperature=request.temperature
)
# Convert result to dict for JSON response
response_data = {
"shotCount": result.shot_count,
"generatedCode": result.generated_code,
"tokens": result.tokens,
"confidenceScores": result.confidence_scores,
"attentionFromExamples": result.attention_from_examples,
"perplexity": result.perplexity,
"avgConfidence": result.avg_confidence,
"exampleInfluences": result.example_influences,
"hiddenStateDrift": result.hidden_state_drift
}
# Add ICL emergence data if available
if result.icl_emergence:
response_data["iclEmergence"] = {
"emergenceDetected": result.icl_emergence.emergence_detected,
"emergenceToken": result.icl_emergence.emergence_token,
"emergenceLayer": result.icl_emergence.emergence_layer,
"confidence": result.icl_emergence.confidence,
"inductionHeads": [
{
"layer": h.layer,
"head": h.head,
"strength": h.strength,
"patternType": h.pattern_type,
"emergencePoint": h.emergence_point
}
for h in result.icl_emergence.induction_heads
],
"attentionEntropyDrop": result.icl_emergence.attention_entropy_drop,
"patternConsistency": result.icl_emergence.pattern_consistency
}
return response_data
@app.post("/analyze/pipeline")
async def analyze_pipeline(request: Dict[str, Any], authenticated: bool = Depends(verify_api_key)):
"""Analyze the complete transformer pipeline step by step"""
from .pipeline_analyzer import TransformerPipelineAnalyzer
try:
# Initialize pipeline analyzer with adapter for multi-model support
analyzer = TransformerPipelineAnalyzer(manager.model, manager.tokenizer, adapter=manager.adapter)
# Get parameters from request
text = request.get("text", "def fibonacci(n):\n if n <= 1:\n return n")
max_tokens = request.get("max_tokens", 1)
temperature = request.get("temperature", 0.7)
top_k = request.get("top_k", 50)
top_p = request.get("top_p", 0.95)
# Analyze the pipeline with generation parameters
result = analyzer.analyze_pipeline(
text,
max_new_tokens=max_tokens,
temperature=temperature,
top_k=top_k,
top_p=top_p
)
# Convert pipeline steps to dict format
from dataclasses import asdict
pipelines_dict = []
for pipeline in result['pipelines']:
pipeline_dict = [asdict(step) for step in pipeline]
pipelines_dict.append(pipeline_dict)
# For backward compatibility, if only 1 token, return old format
if max_tokens == 1 and len(pipelines_dict) > 0:
response_data = {
"steps": pipelines_dict[0],
"total_steps": len(pipelines_dict[0]),
"model_name": manager.model_name,
"input_text": text,
# Also include multi-token format
"tokens": result['tokens'],
"pipelines": pipelines_dict,
"final_text": result['final_text']
}
else:
response_data = {
"tokens": result['tokens'],
"pipelines": pipelines_dict,
"final_text": result['final_text'],
"num_tokens": result['num_tokens'],
"total_steps": len(pipelines_dict[0]) if pipelines_dict else 0,
"model_name": manager.model_name,
"input_text": text
}
logger.info(f"Pipeline analysis complete: {result['num_tokens']} tokens, {len(pipelines_dict[0]) if pipelines_dict else 0} steps per token")
return response_data
except Exception as e:
logger.error(f"Pipeline analysis error: {str(e)}")
logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
@app.post("/analyze/attention")
async def analyze_attention(request: Dict[str, Any], authenticated: bool = Depends(verify_api_key)):
"""Analyze attention mechanism with Q, K, V extraction"""
from .qkv_extractor import QKVExtractor
# Initialize QKV extractor with adapter for real Q/K/V extraction
extractor = QKVExtractor(manager.model, manager.tokenizer, adapter=manager.adapter)
# Extract attention data
text = request.get("text", "def fibonacci(n):\n if n <= 1:\n return n")
analysis = extractor.extract_attention_data(text)
# Convert to response format
response_data = {
"tokens": analysis.tokens,
"tokenIds": analysis.token_ids,
"layerCount": analysis.layer_count,
"headCount": analysis.head_count,
"sequenceLength": analysis.sequence_length,
"modelDimension": analysis.model_dimension,
"qkvData": [],
"tokenEmbeddings": [],
"attentionFlow": []
}
# Process QKV data for specific layers/heads to avoid overwhelming the frontend
# Sample every 4th layer (we already sampled every 4th head in the extractor)
for qkv in analysis.qkv_data:
if qkv.layer % 4 == 0:
response_data["qkvData"].append({
"layer": qkv.layer,
"head": qkv.head,
"query": qkv.query.tolist(),
"key": qkv.key.tolist(),
"value": qkv.value.tolist(),
"attentionScoresRaw": qkv.attention_scores_raw.tolist(),
"attentionWeights": qkv.attention_weights.tolist(),
"headDim": qkv.head_dim
})
# Process token embeddings
for emb in analysis.token_embeddings:
# Only include embeddings for every 4th layer to reduce data size
if emb.layer % 4 == 0:
response_data["tokenEmbeddings"].append({
"token": emb.token,
"tokenId": emb.token_id,
"position": emb.position,
"layer": emb.layer,
"embedding2D": emb.embedding_2d,
"embedding3D": emb.embedding_3d
})
# Get attention flow for the first token as an example
if len(analysis.tokens) > 0:
flow = extractor.get_attention_flow(analysis, source_token=0)
response_data["attentionFlow"] = flow
# Add positional encodings if available
if analysis.positional_encodings is not None:
response_data["positionalEncodings"] = analysis.positional_encodings.tolist()
return response_data
@app.post("/analyze/research/attention")
async def analyze_research_attention(request: Dict[str, Any], authenticated: bool = Depends(verify_api_key)):
"""
Research-Grade Attention Analysis with Full Tensor Extraction
Provides maximum depth analysis for research purposes:
- Full Q/K/V matrices (no sampling)
- All layers and all heads
- Per-token activation deltas
- Pattern classification (induction, positional, semantic, etc.)
- Causal impact quantification
"""
try:
import time
start_time = time.time()
# Generate unique request ID for matrix cache lookup
request_id = str(uuid.uuid4())
# Clear old cached matrices to free memory before starting new analysis
matrix_cache.clear_old_requests(request_id)
# Record per-request model metadata so aggregate-row lookups can
# derive num_heads from this request rather than from the live
# `manager.model` (which may have been switched in the meantime).
if manager.adapter is not None:
matrix_cache.set_request_metadata(
request_id,
num_heads=manager.adapter.get_num_heads(),
num_layers=manager.adapter.get_num_layers(),
model_id=manager.model_id,
)
# Get parameters
prompt = request.get("prompt", "def quicksort(arr):")
max_tokens = request.get("max_tokens", 8)
auto_complete = request.get("auto_complete", False)
temperature = request.get("temperature", 0.7)
top_k_param = request.get("top_k", None) # Top-k sampling parameter
top_p_param = request.get("top_p", None) # Top-p (nucleus) sampling parameter
# If auto_complete mode, ensure we have a reasonable upper limit
if auto_complete:
max_tokens = min(max_tokens, 128)
logger.info(f"Research attention analysis: prompt_len={len(prompt)}, max_tokens={max_tokens}, auto_complete={auto_complete}")
# Get model config for prompt formatting
from .model_config import get_model_config
from .prompt_formatter import format_prompt
model_config = get_model_config(manager.model_id)
# Get optional system prompt override from request
system_prompt_override = request.get("system_prompt")
# Format prompt using the unified formatter
formatted_prompt = format_prompt(
prompt=prompt,
model_config=model_config or {},
tokenizer=manager.tokenizer,
system_prompt_override=system_prompt_override
)
# Log formatting details
prompt_style = model_config.get("prompt_style", "completion") if model_config else "completion"
logger.info(f"Formatted prompt for {manager.model_id} using style={prompt_style}")
if prompt_style == "instruction":
logger.info(f"Formatted prompt preview: {formatted_prompt[:200]}...")
# Temperature is now controlled by the frontend UI
# The frontend sets appropriate defaults per model (0.15 for Devstral, 0.7 for CodeGen)
logger.info(f"Using temperature={temperature} from request")
# Tokenize and prepare - use MistralTokenizer for Devstral
if manager.model_id == "devstral-small" and manager.mistral_tokenizer is not None:
# Use MistralTokenizer for correct Tekken encoding
system_prompt = system_prompt_override or (model_config.get("system_prompt") if model_config else "")
prompt_token_ids = manager.mistral_tokenizer.encode_chat(system_prompt, prompt)
inputs = {"input_ids": torch.tensor([prompt_token_ids]).to(manager.device)}
prompt_length = len(prompt_token_ids)
# Decode tokens using MistralTokenizer for accuracy. mistral-common's
# decode_token() returns "" for some control tokens (<s>, [INST],
# [/INST], [SYSTEM_PROMPT], etc.). Fall back to the HF tokenizer so
# every token arrives with a printable string form.
def _decode_prompt_token(tid: int) -> str:
text = manager.mistral_tokenizer.decode_token(tid)
if text:
return text
try:
return manager.tokenizer.decode([tid], skip_special_tokens=False) or ""
except Exception:
return ""
prompt_tokens = [_decode_prompt_token(tid) for tid in prompt_token_ids]
logger.info(f"Used MistralTokenizer for Devstral: {prompt_length} tokens")
else:
# Standard HF tokenization for other models
inputs = manager.tokenizer(formatted_prompt, return_tensors="pt").to(manager.device)
prompt_length = inputs["input_ids"].shape[1]
prompt_token_ids = inputs["input_ids"][0].tolist()
prompt_tokens = [manager.tokenizer.decode([tid], skip_special_tokens=False) for tid in prompt_token_ids]
# Storage for generation
generated_token_ids = []
generated_tokens = []
# Model info (get from adapter)
n_layers = len(list(manager.model.parameters())) # Approximation
if hasattr(manager.model.config, 'n_layer'):
n_layers = manager.model.config.n_layer
elif hasattr(manager.model.config, 'num_hidden_layers'):
n_layers = manager.model.config.num_hidden_layers
n_heads = manager.model.config.n_head if hasattr(manager.model.config, 'n_head') else manager.model.config.num_attention_heads
d_model = manager.model.config.n_embd if hasattr(manager.model.config, 'n_embd') else manager.model.config.hidden_size
head_dim = d_model // n_heads
# Generation loop with full instrumentation
layer_data_by_token = [] # Store layer data for each generated token
token_alternatives_by_step = [] # Store top-k alternatives for each token
# Hook system to capture Q/K/V matrices
qkv_captures = {}
hooks = []
# Hook for combined QKV projection (CodeGen style)
def make_combined_qkv_hook(layer_idx):
def hook(module, input, output):
try:
if output.dim() != 3:
return
batch_size, seq_len, hidden = output.shape
expected_hidden = 3 * n_heads * head_dim
if hidden != expected_hidden:
return
qkv = output.reshape(batch_size, seq_len, 3, n_heads, head_dim)
q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
qkv_captures[layer_idx] = {
'q': q[0].detach().cpu(),
'k': k[0].detach().cpu(),
'v': v[0].detach().cpu()
}
except Exception:
pass
return hook
# Hooks for separate Q, K, V projections (Mistral/LLaMA style)
def make_separate_proj_hook(layer_idx, proj_type, num_kv_heads=None):
def hook(module, input, output):
try:
if output.dim() != 3:
return
batch_size, seq_len, hidden = output.shape
if proj_type == 'q':
proj_heads = n_heads
else:
proj_heads = num_kv_heads if num_kv_heads else n_heads
proj_head_dim = hidden // proj_heads
if hidden != proj_heads * proj_head_dim:
return
proj_output = output.reshape(batch_size, seq_len, proj_heads, proj_head_dim)
if proj_type != 'q' and num_kv_heads and num_kv_heads < n_heads:
repeat_factor = n_heads // num_kv_heads
proj_output = proj_output.repeat_interleave(repeat_factor, dim=2)
if layer_idx not in qkv_captures:
qkv_captures[layer_idx] = {}
qkv_captures[layer_idx][proj_type] = proj_output[0].detach().cpu()
except Exception:
pass
return hook
# Register hooks based on model architecture
try:
# CodeGen style: model.transformer.h[layer].attn.qkv_proj
if hasattr(manager.model, 'transformer') and hasattr(manager.model.transformer, 'h'):
for layer_idx, layer in enumerate(manager.model.transformer.h):
if hasattr(layer, 'attn') and hasattr(layer.attn, 'qkv_proj'):
hook = layer.attn.qkv_proj.register_forward_hook(make_combined_qkv_hook(layer_idx))
hooks.append(hook)
elif hasattr(layer, 'attn') and hasattr(layer.attn, 'c_attn'):
hook = layer.attn.c_attn.register_forward_hook(make_combined_qkv_hook(layer_idx))
hooks.append(hook)
# Mistral/LLaMA style: model.model.layers[layer].self_attn.{q,k,v}_proj
elif hasattr(manager.model, 'model') and hasattr(manager.model.model, 'layers'):
num_kv_heads = getattr(manager.model.config, 'num_key_value_heads', None)
for layer_idx, layer in enumerate(manager.model.model.layers):
if hasattr(layer, 'self_attn'):
attn = layer.self_attn
if hasattr(attn, 'q_proj'):
hook = attn.q_proj.register_forward_hook(
make_separate_proj_hook(layer_idx, 'q', num_kv_heads))
hooks.append(hook)
if hasattr(attn, 'k_proj'):
hook = attn.k_proj.register_forward_hook(
make_separate_proj_hook(layer_idx, 'k', num_kv_heads))
hooks.append(hook)
if hasattr(attn, 'v_proj'):
hook = attn.v_proj.register_forward_hook(
make_separate_proj_hook(layer_idx, 'v', num_kv_heads))
hooks.append(hook)
logger.info(f"Registered QKV hooks for {len(hooks)//3} Mistral layers (GQA: {num_kv_heads} KV heads)")
except Exception as hook_error:
logger.warning(f"Could not register QKV hooks: {hook_error}")
with torch.no_grad():
current_ids = inputs["input_ids"]
for step in range(max_tokens):
# Clear previous captures
qkv_captures.clear()
# Forward pass with full outputs
outputs = manager.model(
current_ids,
output_attentions=True,
output_hidden_states=True
)
# Record the query position whose logits will select this
# step's token. attention[layer][head][-1] is the row of
# this query — exposing it in /attention/row makes the
# provenance of "Why this token?" attention explicit.
query_position = current_ids.shape[1] - 1
query_token_id = current_ids[0, -1].item()
matrix_cache.set_step_query_info(
request_id, step, query_position, query_token_id
)
# Get logits for next token
raw_logits = outputs.logits[0, -1, :].clone() # Clone raw logits before any scaling
# Capture raw logits for top-10 tokens (before temperature scaling)
import math
top_n_display = 10 # Get top 10 alternatives for display
top_raw_logits, top_raw_indices = torch.topk(raw_logits, k=min(top_n_display, len(raw_logits)))
# ── Unembedding-cosine prep ──────────────────────────
# Each logit is W_E[v] · h_post_norm where h_post_norm
# is the post-final-norm residual at the last position.
# cos(W_E[v], h_post_norm) is the *direction-only*
# alignment — strips out magnitude so a developer can
# see whether a high-logit token won by alignment or
# by magnitude. Computed once per step (cheap; one
# final-norm call + d_model dot product per token).
cos_h_norm = None
W_E = None
try:
final_hidden_pre_norm = outputs.hidden_states[-1][0, -1, :]
if hasattr(manager.model, 'model') and hasattr(manager.model.model, 'norm'):
h_post_norm = manager.model.model.norm(
final_hidden_pre_norm.unsqueeze(0)
)[0]
elif hasattr(manager.model, 'transformer') and hasattr(manager.model.transformer, 'ln_f'):
h_post_norm = manager.model.transformer.ln_f(
final_hidden_pre_norm.unsqueeze(0)
)[0]
else:
h_post_norm = final_hidden_pre_norm
h_norm_val = float(torch.linalg.vector_norm(h_post_norm).item())
if h_norm_val > 1e-9:
cos_h_norm = h_post_norm / h_norm_val
if hasattr(manager.model, 'lm_head'):
W_E = manager.model.lm_head.weight
else:
logger.warning(
"[cosine prep] manager.model has no lm_head — cosine emission skipped"
)
else:
logger.warning(
f"[cosine prep] h_post_norm magnitude too small: {h_norm_val}"
)
if cos_h_norm is not None and W_E is not None and step == 0:
# One-time confirmation per generation that the
# cosine path is live.
logger.info(
f"[cosine prep] enabled · h_post_norm shape {tuple(h_post_norm.shape)} · "
f"W_E shape {tuple(W_E.shape)} · h_norm {h_norm_val:.3f}"
)
except Exception as e:
logger.warning(
f"[cosine prep] failed at step {step}: {type(e).__name__}: {e}"
)
cos_h_norm = None
W_E = None
def _cos_for(token_idx: int):
"""cosine(W_E[token_idx], h_post_norm) and ‖W_E row‖."""
if cos_h_norm is None or W_E is None:
return None, None
try:
row = W_E[token_idx]
row_norm = float(torch.linalg.vector_norm(row).item())
if row_norm < 1e-9:
return None, row_norm
cos = float(((row / row_norm) @ cos_h_norm).item())
return cos, row_norm
except Exception:
return None, None
# Build raw logits entries (before temperature)
logits_entries = []
for rank, (logit_val, idx) in enumerate(zip(top_raw_logits.tolist(), top_raw_indices.tolist())):
token_text = manager.tokenizer.decode([idx], skip_special_tokens=False)
cos, row_norm = _cos_for(idx)
entry = {
"token": token_text,
"token_id": idx,
"logit": logit_val,
"rank": rank + 1,
}
if cos is not None:
entry["cosine_sim"] = round(cos, 4)
if row_norm is not None:
entry["unemb_row_norm"] = round(row_norm, 4)
logits_entries.append(entry)
# Greedy token (argmax of raw logits, before any sampling)
greedy_token_id = torch.argmax(raw_logits).item()
greedy_token = manager.tokenizer.decode([greedy_token_id], skip_special_tokens=False)
# Compute raw probabilities (T=1) for comparison visualization
raw_probs = torch.softmax(raw_logits, dim=0)
# Apply temperature scaling
logits = raw_logits.clone()
if temperature > 0:
logits = logits / temperature
probs = torch.softmax(logits, dim=0)
# Apply top-k filtering if specified
if top_k_param is not None and top_k_param > 0:
top_k_probs, top_k_indices = torch.topk(probs, k=min(top_k_param, len(probs)))
probs_filtered = torch.zeros_like(probs)
probs_filtered[top_k_indices] = top_k_probs
probs_filtered = probs_filtered / probs_filtered.sum() # Renormalize
else:
probs_filtered = probs
# Apply top-p (nucleus) filtering if specified
if top_p_param is not None and top_p_param < 1.0:
sorted_probs, sorted_indices = torch.sort(probs_filtered, descending=True)
cumulative_probs = torch.cumsum(sorted_probs, dim=0)
# Find cutoff index where cumulative exceeds top_p
cutoff_mask = cumulative_probs > top_p_param
# Shift mask by 1 to keep at least one token
cutoff_mask[1:] = cutoff_mask[:-1].clone()
cutoff_mask[0] = False
# Zero out tokens beyond cutoff
sorted_probs[cutoff_mask] = 0
# Scatter back to original order
probs_filtered = torch.zeros_like(probs)
probs_filtered.scatter_(0, sorted_indices, sorted_probs)
if probs_filtered.sum() > 0:
probs_filtered = probs_filtered / probs_filtered.sum() # Renormalize
if temperature == 0:
next_token_id = torch.argmax(probs_filtered, dim=-1).item()
else:
# Ensure valid probability distribution for multinomial
if probs_filtered.sum() > 0:
next_token_id = torch.multinomial(probs_filtered, 1).item()
else:
next_token_id = torch.argmax(probs, dim=-1).item()
next_token_text = manager.tokenizer.decode([next_token_id], skip_special_tokens=False)
generated_token_ids.append(next_token_id)
generated_tokens.append(next_token_text)
# Capture top-10 token alternatives with probabilities
# Use log_softmax for numerical stability at low temperatures
_, top_indices = torch.topk(logits, k=min(top_n_display, len(logits)))
# Use log_softmax (numerically stable) then exp() for probabilities
# This avoids underflow that occurs with softmax at low temperatures
# Note: logits is ALREADY temperature-scaled above, so no need to divide again
log_probs = torch.nn.functional.log_softmax(logits, dim=-1)
top_probs = torch.exp(log_probs[top_indices])
# `probability` is the post-temperature, PRE-filter probability
# (model preference). `effective_probability` is the post-filter
# renormalised probability — what the sampler actually drew
# from. Under top-k / top-p, alternatives outside the eligible
# set get effective_probability = 0. When no filter is active,
# the two values coincide. Surfacing both lets the panel
# report a "model preference margin" (top-1 vs top-2 by
# `probability`) and a "sampling margin" (top-1 vs top-2 by
# `effective_probability` over the eligible set) — necessary
# because under filtering the panel was previously showing a
# margin that didn't reflect the actual decision.
is_filtered = bool(
(top_k_param is not None and top_k_param > 0)
or (top_p_param is not None and top_p_param < 1.0)
)
alternatives = []
cumulative = 0.0
selected_in_top = False
for rank, (prob, idx) in enumerate(zip(top_probs.tolist(), top_indices.tolist())):
token_text = manager.tokenizer.decode([idx], skip_special_tokens=False)
cumulative += prob
if idx == next_token_id:
selected_in_top = True
eff = probs_filtered[idx].item()
alternatives.append({
"token": token_text,
"token_id": idx,
"probability": prob,
"effective_probability": eff,
"is_eligible": eff > 0.0,
"raw_probability": raw_probs[idx].item(), # T=1 probability for comparison
"log_probability": math.log(prob) if prob > 0 else float('-inf'),
"cumulative_probability": cumulative,
"rank": rank + 1
})
# If selected token is not in top-N, add it with its actual probability
if not selected_in_top:
selected_prob = probs[next_token_id].item()
selected_eff = probs_filtered[next_token_id].item()
selected_raw_prob = raw_probs[next_token_id].item()
selected_log_prob = log_probs[next_token_id].item()
selected_logit = raw_logits[next_token_id].item()
# Find the rank of the selected token
sorted_indices = torch.argsort(raw_logits, descending=True)
selected_rank = (sorted_indices == next_token_id).nonzero(as_tuple=True)[0].item() + 1
alternatives.append({
"token": next_token_text,
"token_id": next_token_id,
"probability": selected_prob,
"effective_probability": selected_eff,
"is_eligible": selected_eff > 0.0,
"raw_probability": selected_raw_prob, # T=1 probability for comparison
"log_probability": selected_log_prob,
"cumulative_probability": None, # Not in sequence
"rank": selected_rank,
"is_selected_outlier": True # Flag for UI
})
# Also add to logits if not present
if next_token_id not in [e["token_id"] for e in logits_entries]:
cos_outlier, row_norm_outlier = _cos_for(next_token_id)
outlier_entry = {
"token": next_token_text,
"token_id": next_token_id,
"logit": selected_logit,
"rank": selected_rank,
"is_selected_outlier": True,
}
if cos_outlier is not None:
outlier_entry["cosine_sim"] = round(cos_outlier, 4)
if row_norm_outlier is not None:
outlier_entry["unemb_row_norm"] = round(
row_norm_outlier, 4
)
logits_entries.append(outlier_entry)
# Build sampling metadata. `is_filtered` and `eligible_count`
# let the frontend decide whether to show one or two
# distributions in the panel.
eligible_count = int((probs_filtered > 0).sum().item())
sampling_metadata = {
"temperature": temperature,
"top_k": top_k_param,
"top_p": top_p_param,
"greedy_token_id": greedy_token_id,
"greedy_token": greedy_token,
"was_greedy": next_token_id == greedy_token_id,
"is_filtered": is_filtered,
"eligible_count": eligible_count,
}
token_alternatives_by_step.append({
"step": step,
"selected_token": next_token_text,
"selected_token_id": next_token_id,
"alternatives": alternatives,
"logits": logits_entries,
"sampling": sampling_metadata
})
# Process attention and hidden states for ALL layers
layer_data_this_token = []
for layer_idx in range(len(outputs.attentions)):
# Get attention for this layer [batch, num_heads, seq_len, seq_len]
layer_attn = outputs.attentions[layer_idx][0] # Remove batch dim
# Get hidden states [batch, seq_len, hidden_dim]
current_hidden = outputs.hidden_states[layer_idx + 1] # +1 because hidden_states includes embedding layer
if current_hidden.dim() == 3:
current_hidden = current_hidden[0] # Remove batch dim if present
if layer_idx > 0:
prev_hidden = outputs.hidden_states[layer_idx]
if prev_hidden.dim() == 3:
prev_hidden = prev_hidden[0]
delta_norm = torch.norm(current_hidden - prev_hidden).item()
else:
delta_norm = None
# Calculate layer metrics
import math
activation_magnitude = torch.norm(current_hidden).item()
# Use a simpler entropy calculation based on attention distribution
last_token_hidden = current_hidden[-1] # [hidden_dim]
activation_entropy = torch.std(last_token_hidden).item() # Use std dev as a proxy for activation diversity
hidden_state_norm = torch.norm(last_token_hidden).item() # Norm of last token
# Sanitize to prevent NaN/Inf in JSON
activation_magnitude = 0.0 if math.isnan(activation_magnitude) or math.isinf(activation_magnitude) else activation_magnitude
activation_entropy = 0.0 if math.isnan(activation_entropy) or math.isinf(activation_entropy) else activation_entropy
hidden_state_norm = 0.0 if math.isnan(hidden_state_norm) or math.isinf(hidden_state_norm) else hidden_state_norm
if delta_norm is not None:
delta_norm = 0.0 if math.isnan(delta_norm) or math.isinf(delta_norm) else delta_norm
# Identify critical heads (high max weight or low entropy)
critical_heads = []
for head_idx in range(layer_attn.shape[0]):
head_weights = layer_attn[head_idx, -1, :] # Attention from last position
max_weight = head_weights.max().item()
entropy = -(head_weights * torch.log(head_weights + 1e-10)).sum().item()
# Normalized attention entropy averaged over latter half of query positions
# Normalized by log(k_i) where k_i = number of keys position i can attend to
# This produces values in [0,1] with better spread across heads
# layer_attn[head_idx] shape: [q_len, k_len]
head_attn = layer_attn[head_idx] # [q_len, k_len]
q_len = head_attn.shape[0]
# Compute raw entropy per query position
token_entropies = -(head_attn * torch.log(head_attn + 1e-10)).sum(dim=-1) # [q_len]
# Normalize by max possible entropy: log(k_i) where k_i = i + 1 (causal mask)
# Skip position 0 where log(1) = 0
positions = torch.arange(1, q_len + 1, device=head_attn.device, dtype=head_attn.dtype)
max_entropies = torch.log(positions + 1e-10) # log(k_i), with epsilon for position 0
normalized_entropies = token_entropies / (max_entropies + 1e-10) # [0, 1] range
# Average over latter half of positions (where there's enough context)
start_idx = q_len // 2
avg_entropy = normalized_entropies[start_idx:].mean().item() if start_idx < q_len else normalized_entropies.mean().item()
# Sanitize to prevent NaN/Inf in JSON
max_weight = 0.0 if math.isnan(max_weight) or math.isinf(max_weight) else max_weight
entropy = 0.0 if math.isnan(entropy) or math.isinf(entropy) else entropy
avg_entropy = 0.0 if math.isnan(avg_entropy) or math.isinf(avg_entropy) else avg_entropy
# Score-all-then-rank head classification
# Two dimensions: behaviour type (attention geometry) + code cue (token relevance)
seq_len_hw = head_weights.shape[0]
# --- Behaviour type scores (attention geometry) ---
behaviour_scores = {}
# Attention sink: weight on positions 0-2
sink_w = head_weights[:min(3, seq_len_hw)].sum().item()
behaviour_scores["attention_sink"] = sink_w
# Previous token: weight on immediate predecessor
prev_tok_w = head_weights[-2].item() if seq_len_hw >= 2 else 0.0
behaviour_scores["previous_token"] = prev_tok_w
# Local: weight within last 5 positions
local_w = head_weights[max(0, seq_len_hw - 5):].sum().item() if seq_len_hw > 5 else 0.0
behaviour_scores["local"] = local_w
# Induction: weight on positions following previous occurrences of current token
ind_w = 0.0
if step > 0 and seq_len_hw > 1:
current_tok = current_ids[0, -1]
prev_occ = (current_ids[0, :-1] == current_tok).nonzero(as_tuple=True)[0]
if len(prev_occ) > 0:
foll = prev_occ + 1
foll = foll[foll < seq_len_hw]
if len(foll) > 0:
ind_w = head_weights[foll].sum().item()
behaviour_scores["induction"] = min(1.0, ind_w)
# Focused: low entropy, concentrated attention (not captured by above)
focused_score = max(0.0, 1.0 - entropy) if entropy < 1.5 else 0.0
behaviour_scores["focused"] = focused_score
# Diffuse: high entropy, broad attention
diffuse_score = min(1.0, max(0.0, (entropy - 1.0) / 2.0))
behaviour_scores["diffuse"] = diffuse_score
# Pick primary behaviour (highest score, with minimum thresholds)
behaviour_thresholds = {
"attention_sink": 0.4,
"previous_token": 0.7,
"local": 0.5,
"induction": 0.2,
"focused": 0.3,
"diffuse": 0.3,
}
qualified_behaviours = {
k: v for k, v in behaviour_scores.items()
if v >= behaviour_thresholds.get(k, 0.3)
}
sorted_behaviours = sorted(qualified_behaviours.items(), key=lambda x: x[1], reverse=True)
primary_behaviour = sorted_behaviours[0] if sorted_behaviours else ("diffuse", diffuse_score)
secondary_behaviour = sorted_behaviours[1] if len(sorted_behaviours) > 1 else None
pattern_type = primary_behaviour[0]
confidence = primary_behaviour[1]
# --- Code cue scores (what code tokens are attended to) ---
# Decode token texts for code-aware detection (cached per step)
if step_token_texts_cache.get('step') != step:
try:
step_token_texts_cache['texts'] = [
manager.tokenizer.decode([tid]) for tid in current_ids[0, :seq_len_hw].tolist()
]
except Exception:
step_token_texts_cache['texts'] = []
step_token_texts_cache['step'] = step
token_texts = step_token_texts_cache.get('texts', [])
code_cues = {}
if len(token_texts) == seq_len_hw:
# Delimiter-sensitive: attention to brackets, braces, parens
delimiters = {'(', ')', '{', '}', '[', ']', ':', ';', ','}
delim_indices = [i for i, t in enumerate(token_texts) if t.strip() in delimiters]
if delim_indices:
delim_w = head_weights[delim_indices].sum().item()
code_cues["delimiter_sensitive"] = delim_w
# Keyword-sensitive: attention to language keywords
keywords = {'def', 'return', 'if', 'else', 'elif', 'for', 'while', 'class',
'import', 'from', 'try', 'except', 'with', 'as', 'in', 'not',
'and', 'or', 'True', 'False', 'None', 'self', 'yield', 'async',
'await', 'lambda', 'raise', 'pass', 'break', 'continue',
'function', 'const', 'let', 'var', 'new', 'this'}
kw_indices = [i for i, t in enumerate(token_texts) if t.strip() in keywords]
if kw_indices:
kw_w = head_weights[kw_indices].sum().item()
code_cues["keyword_sensitive"] = kw_w
# Pattern reuse: attention to a contiguous span that appeared earlier
# (broader than induction — checks for repeated multi-token sequences)
if ind_w > 0.15:
code_cues["pattern_reuse"] = min(1.0, ind_w * 1.5)
# Filter code cues by minimum threshold
code_cue_threshold = 0.15
qualified_cues = {
k: round(v, 4) for k, v in code_cues.items()
if v >= code_cue_threshold
}
sorted_cues = sorted(qualified_cues.items(), key=lambda x: x[1], reverse=True)
primary_cue = sorted_cues[0] if sorted_cues else None
# Sanitize confidence
confidence = 0.0 if math.isnan(confidence) or math.isinf(confidence) else confidence
# Get full attention weights for this head [seq_len, seq_len]
# Store as numpy arrays (not Python lists) to save memory
# ~7x more memory efficient: 4 bytes/float vs 28 bytes/float
attention_matrix = layer_attn[head_idx].cpu().float().numpy()
# Get Q/K/V for this head if available
q_matrix = None
k_matrix = None
v_matrix = None
if layer_idx in qkv_captures:
# Q/K/V shape: [seq_len, n_heads, head_dim]
# Store as numpy arrays for memory efficiency
q_matrix = qkv_captures[layer_idx]['q'][:, head_idx, :].float().numpy()
k_matrix = qkv_captures[layer_idx]['k'][:, head_idx, :].float().numpy()
v_matrix = qkv_captures[layer_idx]['v'][:, head_idx, :].float().numpy()
# Store matrices in cache for lazy loading (reduces response size)
matrix_cache.store(request_id, step, layer_idx, head_idx, {
"attention_weights": attention_matrix,
"q_matrix": q_matrix,
"k_matrix": k_matrix,
"v_matrix": v_matrix
})
# Return only metadata (matrices fetched on-demand via /matrix endpoint)
head_entry = {
"head_idx": head_idx,
"entropy": entropy,
"avg_entropy": avg_entropy, # Averaged over all query positions
"max_weight": max_weight,
"has_matrices": attention_matrix is not None, # Flag for frontend
"pattern": {
"type": pattern_type,
"confidence": round(confidence, 4),
} if pattern_type else None,
}
# Secondary behaviour (if present and distinct from primary)
if secondary_behaviour:
head_entry["secondary_behaviour"] = {
"type": secondary_behaviour[0],
"score": round(secondary_behaviour[1], 4),
}
# Code cue (separate dimension from behaviour type)
if primary_cue:
head_entry["code_cue"] = {
"type": primary_cue[0],
"score": round(primary_cue[1], 4),
"evidence": f"{round(primary_cue[1] * 100)}% attention on {primary_cue[0].replace('_', ' ')} tokens",
}
# Secondary code cue
if len(sorted_cues) > 1:
head_entry["secondary_cue"] = {
"type": sorted_cues[1][0],
"score": round(sorted_cues[1][1], 4),
}
critical_heads.append(head_entry)
# Sort by max_weight (return all heads, frontend will decide how many to display)
critical_heads.sort(key=lambda h: h["max_weight"], reverse=True)
# Layer-level pattern: majority vote of head patterns, weighted by confidence
pattern_votes = {}
for h in critical_heads:
if h["pattern"] and h["pattern"]["type"]:
pt = h["pattern"]["type"]
pc = h["pattern"]["confidence"]
pattern_votes[pt] = pattern_votes.get(pt, 0.0) + pc
layer_pattern = None
if pattern_votes:
best_type = max(pattern_votes, key=pattern_votes.get)
total_conf = sum(pattern_votes.values())
layer_pattern = {
"type": best_type,
"confidence": round(pattern_votes[best_type] / total_conf, 3) if total_conf > 0 else 0.0
}
layer_data_this_token.append({
"layer_idx": layer_idx,
"pattern": layer_pattern,
"critical_heads": critical_heads,
"activation_magnitude": activation_magnitude,
"activation_entropy": activation_entropy,
"hidden_state_norm": hidden_state_norm,
"delta_norm": delta_norm
})
layer_data_by_token.append(layer_data_this_token)
# Update inputs
next_token_tensor = torch.tensor([[next_token_id]], dtype=torch.long, device=manager.device)
current_ids = torch.cat([current_ids, next_token_tensor], dim=1)
# Stop on EOS
if next_token_id == manager.tokenizer.eos_token_id:
break
# Free memory from this step's outputs to prevent accumulation
# This is critical for large models like Devstral (40 layers, 32 heads)
del outputs
del logits
del probs
if 'layer_attn' in dir():
del layer_attn
if 'current_hidden' in dir():
del current_hidden
# Periodic garbage collection for large models (every 8 steps)
if (step + 1) % 8 == 0:
gc.collect()
if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
torch.mps.empty_cache() if hasattr(torch.mps, 'empty_cache') else None
# Clean up hooks after generation
for hook in hooks:
hook.remove()
# Placeholder for Q/K/V data (will be populated in future iterations)
qkv_by_layer_head = {}
generation_time = time.time() - start_time
# Calculate token section boundaries for UI display
total_tokens = prompt_length + len(generated_token_ids)
system_prompt_text = system_prompt_override or (model_config.get("system_prompt") if model_config else None)
# For instruction models, estimate where system prompt ends
# This is approximate due to control tokens in chat templates
system_prompt_end = 0
if prompt_style == "instruction" and system_prompt_text:
if manager.model_id == "devstral-small" and manager.mistral_tokenizer is not None:
# For Devstral, try encoding with empty system to estimate boundary
try:
no_system_tokens = manager.mistral_tokenizer.encode_chat("", prompt)
# The difference gives us system tokens, but we need to add 1 to include
# the closing [/SYSTEM_PROMPT] tag in the system prompt section
system_prompt_end = prompt_length - len(no_system_tokens) + 1
# Ensure non-negative and within bounds
system_prompt_end = max(0, min(system_prompt_end, prompt_length))
logger.info(f"Estimated system prompt boundary: {system_prompt_end} tokens (includes closing tag)")
except Exception as e:
logger.warning(f"Could not estimate system prompt boundary: {e}")
system_prompt_end = 0
else:
# For other instruction models, rough estimate based on character ratio
# This is very approximate but provides some visual separation
total_chars = len(system_prompt_text or "") + len(prompt)
if total_chars > 0:
system_ratio = len(system_prompt_text or "") / total_chars
system_prompt_end = int(prompt_length * system_ratio)
token_sections = {
"systemPrompt": {
"start": 0,
"end": system_prompt_end,
"text": system_prompt_text,
"tokenCount": system_prompt_end
},
"userPrompt": {
"start": system_prompt_end,
"end": prompt_length,
"text": prompt,
"tokenCount": prompt_length - system_prompt_end
},
"output": {
"start": prompt_length,
"end": total_tokens,
"text": "".join(generated_tokens),
"tokenCount": len(generated_token_ids)
}
}
# Build token metadata for frontend (eliminates per-token API calls)
from .tokenizer_utils import TokenizerMetadata
token_metadata = TokenizerMetadata(manager.tokenizer)
# Include every id the tokenizer considers a special / added token
# (BOS, EOS, PAD, UNK, chat-template delimiters like [INST]/[/INST],
# system-prompt markers, tool-call markers, etc.). The HF tokenizer's
# all_special_ids misses Mistral-specific chat-template delimiters, so
# we also union in the control-token ids from mistral-common when the
# Mistral path is active.
special_token_ids = set(getattr(manager.tokenizer, "all_special_ids", []) or [])
for tok_id in (
manager.tokenizer.eos_token_id,
manager.tokenizer.bos_token_id,
manager.tokenizer.pad_token_id,
manager.tokenizer.unk_token_id,
):
if tok_id is not None:
special_token_ids.add(tok_id)
if manager.mistral_tokenizer is not None:
special_token_ids |= manager.mistral_tokenizer.get_control_token_ids()
def build_token_data(token_ids, token_texts, token_type):
"""Build token data with full metadata for hover tooltips"""
multi_split_flags = token_metadata.is_multi_split_identifier(token_ids)
result = []
for i, (tid, t) in enumerate(zip(token_ids, token_texts)):
bpe_pieces = token_metadata.get_subword_pieces(tid)
result.append({
"text": t,
"idx": tid,
"bytes": len(t.encode('utf-8')),
"type": token_type,
"bpe_pieces": bpe_pieces,
"is_special": tid in special_token_ids,
"is_multi_split": multi_split_flags[i] if i < len(multi_split_flags) else False,
"num_pieces": len(bpe_pieces),
})
return result
# Embedding L2 norms — see streaming endpoint for the full
# rationale (RQ1 layer-0 anchor for the residual-norm trace).
# Covers both prompt tokens and generated tokens so the
# Mechanism lens can render bars for the full context window
# (prompt + previously-generated tokens) at any step.
embedding_norms: List[float] = _compute_embedding_norms(
manager,
list(prompt_token_ids) + list(generated_token_ids),
)
# Build response
response = {
"requestId": request_id, # For lazy-loading matrices via /matrix endpoint
"prompt": prompt,
"promptTokens": build_token_data(prompt_token_ids, prompt_tokens, "prompt"),
"generatedTokens": build_token_data(generated_token_ids, generated_tokens, "generated"),
"tokenSections": token_sections, # Section boundaries for UI coloring
"tokenAlternatives": token_alternatives_by_step, # Top-k alternatives for each token
"layersDataByStep": layer_data_by_token, # Layer data for ALL generation steps
"layersData": layer_data_by_token[-1] if layer_data_by_token else [], # Keep for backward compatibility
"qkvData": {}, # Deprecated: matrices now lazy-loaded via /matrix endpoint
"modelInfo": {
"numLayers": n_layers,
"numHeads": n_heads,
"modelDimension": d_model,
"headDim": head_dim,
"vocabSize": manager.model.config.vocab_size
},
"embeddingNorms": embedding_norms,
"generationTime": generation_time,
"numTokensGenerated": len(generated_tokens)
}
logger.info(f"✅ Research attention analysis complete: {len(generated_tokens)} tokens, {generation_time:.2f}s")
# Sanitize response to handle NaN/Inf values that break JSON serialization
return sanitize_for_json(response)
except Exception as e:
logger.error(f"Research attention analysis error: {e}")
logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
def sse_event(event_type: str, **kwargs) -> str:
"""Format data as SSE event"""
data = {'type': event_type, 'timestamp': int(time.time() * 1000), **kwargs}
return f"data: {json.dumps(data)}\n\n"
@app.post("/analyze/research/attention/stream")
async def analyze_research_attention_stream(request: Dict[str, Any], authenticated: bool = Depends(verify_api_key)):
"""
SSE Streaming version of Research-Grade Attention Analysis
Emits progress events during each stage:
- tokenizing: Initial tokenization
- generating: Per-token generation progress
- extracting: Per-layer attention extraction
- serializing: Building response
- complete: Analysis finished
- result: Final data payload
"""
async def event_generator():
try:
import time
start_time = time.time()
# Generate unique request ID for matrix cache lookup
request_id = str(uuid.uuid4())
# `ephemeral` callers (e.g. the What-if "Rewrite & rerun"
# counterfactual) want their regen to coexist with the
# original traced run rather than displace it — the user
# still needs the original's matrices for the Mechanism /
# Attention lenses. The new request_id is unique, so the
# ephemeral run's own writes don't collide; we just have to
# skip the eager `clear_old_requests` that would otherwise
# purge every other request_id's cache.
ephemeral = bool(request.get("ephemeral", False))
# Clear old cached matrices to free memory before starting new analysis
if not ephemeral:
matrix_cache.clear_old_requests(request_id)
# Record per-request model metadata so aggregate-row lookups can
# derive num_heads from this request rather than from the live
# `manager.model` (which may have been switched in the meantime).
# Ephemeral runs (What-if Rewrite & rerun) skip every cache
# write — the frontend discards everything except the
# generated tokens, so the regen leaves no trace at all.
if manager.adapter is not None and not ephemeral:
matrix_cache.set_request_metadata(
request_id,
num_heads=manager.adapter.get_num_heads(),
num_layers=manager.adapter.get_num_layers(),
model_id=manager.model_id,
)
# Get parameters
prompt = request.get("prompt", "def quicksort(arr):")
max_tokens = request.get("max_tokens", 8)
auto_complete = request.get("auto_complete", False)
temperature = request.get("temperature", 0.7)
top_k_param = request.get("top_k", None) # Top-k sampling parameter
top_p_param = request.get("top_p", None) # Top-p (nucleus) sampling parameter
# If auto_complete mode, ensure we have a reasonable upper limit
if auto_complete:
max_tokens = min(max_tokens, 128)
logger.info(f"[SSE] Research attention analysis: prompt_len={len(prompt)}, max_tokens={max_tokens}, auto_complete={auto_complete}, request_id={request_id}")
# === STAGE 1: TOKENIZING ===
yield sse_event('tokenizing', stage=1, totalStages=5, progress=2,
stageProgress=0, detail=f'Tokenizing {len(prompt)} characters...')
# Get model config for prompt formatting
from .model_config import get_model_config
from .prompt_formatter import format_prompt
model_config = get_model_config(manager.model_id)
# Get optional system prompt override from request
system_prompt_override = request.get("system_prompt")
# Format prompt using the unified formatter
formatted_prompt = format_prompt(
prompt=prompt,
model_config=model_config or {},
tokenizer=manager.tokenizer,
system_prompt_override=system_prompt_override
)
prompt_style = model_config.get("prompt_style", "completion") if model_config else "completion"
# Temperature is now controlled by the frontend UI
# The frontend sets appropriate defaults per model (0.15 for Devstral, 0.7 for CodeGen)
logger.info(f"[SSE] Using temperature={temperature} from request")
# Tokenize and prepare - use MistralTokenizer for Devstral
if manager.model_id == "devstral-small" and manager.mistral_tokenizer is not None:
system_prompt = system_prompt_override or (model_config.get("system_prompt") if model_config else "")
prompt_token_ids = manager.mistral_tokenizer.encode_chat(system_prompt, prompt)
inputs = {"input_ids": torch.tensor([prompt_token_ids]).to(manager.device)}
prompt_length = len(prompt_token_ids)
# mistral-common's decode_token() returns "" for control tokens
# (<s>, [INST], [/INST], [SYSTEM_PROMPT], etc.). Fall back to
# the HF tokenizer so every token has a printable string form.
def _decode_prompt_token(tid: int) -> str:
text = manager.mistral_tokenizer.decode_token(tid)
if text:
return text
try:
return manager.tokenizer.decode([tid], skip_special_tokens=False) or ""
except Exception:
return ""
prompt_tokens = [_decode_prompt_token(tid) for tid in prompt_token_ids]
else:
inputs = manager.tokenizer(formatted_prompt, return_tensors="pt").to(manager.device)
prompt_length = inputs["input_ids"].shape[1]
prompt_token_ids = inputs["input_ids"][0].tolist()
prompt_tokens = [manager.tokenizer.decode([tid], skip_special_tokens=False) for tid in prompt_token_ids]
yield sse_event('tokenizing', stage=1, totalStages=5, progress=8,
stageProgress=100, detail=f'Tokenized into {prompt_length} tokens',
metadata={'tokenCount': prompt_length})
await asyncio.sleep(0) # Yield to event loop
# Storage for generation
generated_token_ids = []
generated_tokens = []
# Model info
n_layers = len(list(manager.model.parameters()))
if hasattr(manager.model.config, 'n_layer'):
n_layers = manager.model.config.n_layer
elif hasattr(manager.model.config, 'num_hidden_layers'):
n_layers = manager.model.config.num_hidden_layers
n_heads = manager.model.config.n_head if hasattr(manager.model.config, 'n_head') else manager.model.config.num_attention_heads
d_model = manager.model.config.n_embd if hasattr(manager.model.config, 'n_embd') else manager.model.config.hidden_size
head_dim = d_model // n_heads
# === STAGE 2: GENERATING ===
layer_data_by_token = []
token_alternatives_by_step = []
# Hook system to capture Q/K/V matrices
qkv_captures = {}
hooks = []
# Hook for combined QKV projection (CodeGen style)
def make_combined_qkv_hook(layer_idx):
def hook(module, input, output):
try:
if output.dim() != 3:
return
batch_size, seq_len, hidden = output.shape
expected_hidden = 3 * n_heads * head_dim
if hidden != expected_hidden:
return
qkv = output.reshape(batch_size, seq_len, 3, n_heads, head_dim)
q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
qkv_captures[layer_idx] = {
'q': q[0].detach().cpu(),
'k': k[0].detach().cpu(),
'v': v[0].detach().cpu()
}
except Exception:
pass
return hook
# Hooks for separate Q, K, V projections (Mistral/LLaMA style)
def make_separate_proj_hook(layer_idx, proj_type, num_kv_heads=None):
"""Create hook for separate Q/K/V projection modules.
For GQA models, K and V have fewer heads than Q, so we need to
expand them to match Q's head count for consistent visualization.
"""
def hook(module, input, output):
try:
if output.dim() != 3:
return
batch_size, seq_len, hidden = output.shape
# Determine number of heads for this projection
if proj_type == 'q':
proj_heads = n_heads
else:
# K and V may have fewer heads (GQA)
proj_heads = num_kv_heads if num_kv_heads else n_heads
proj_head_dim = hidden // proj_heads
if hidden != proj_heads * proj_head_dim:
return
# Reshape to [batch, seq, heads, head_dim]
proj_output = output.reshape(batch_size, seq_len, proj_heads, proj_head_dim)
# For GQA, expand K/V to match Q's head count
if proj_type != 'q' and num_kv_heads and num_kv_heads < n_heads:
# Repeat each KV head to match Q heads
repeat_factor = n_heads // num_kv_heads
proj_output = proj_output.repeat_interleave(repeat_factor, dim=2)
# Initialize layer entry if needed
if layer_idx not in qkv_captures:
qkv_captures[layer_idx] = {}
qkv_captures[layer_idx][proj_type] = proj_output[0].detach().cpu()
except Exception as e:
logger.debug(f"QKV capture error for layer {layer_idx} {proj_type}: {e}")
return hook
# Register hooks based on model architecture
try:
# CodeGen style: model.transformer.h[layer].attn.qkv_proj
if hasattr(manager.model, 'transformer') and hasattr(manager.model.transformer, 'h'):
for layer_idx, layer in enumerate(manager.model.transformer.h):
if hasattr(layer, 'attn') and hasattr(layer.attn, 'qkv_proj'):
hook = layer.attn.qkv_proj.register_forward_hook(make_combined_qkv_hook(layer_idx))
hooks.append(hook)
elif hasattr(layer, 'attn') and hasattr(layer.attn, 'c_attn'):
hook = layer.attn.c_attn.register_forward_hook(make_combined_qkv_hook(layer_idx))
hooks.append(hook)
# Mistral/LLaMA style: model.model.layers[layer].self_attn.{q,k,v}_proj
elif hasattr(manager.model, 'model') and hasattr(manager.model.model, 'layers'):
num_kv_heads = getattr(manager.model.config, 'num_key_value_heads', None)
for layer_idx, layer in enumerate(manager.model.model.layers):
if hasattr(layer, 'self_attn'):
attn = layer.self_attn
if hasattr(attn, 'q_proj'):
hook = attn.q_proj.register_forward_hook(
make_separate_proj_hook(layer_idx, 'q', num_kv_heads))
hooks.append(hook)
if hasattr(attn, 'k_proj'):
hook = attn.k_proj.register_forward_hook(
make_separate_proj_hook(layer_idx, 'k', num_kv_heads))
hooks.append(hook)
if hasattr(attn, 'v_proj'):
hook = attn.v_proj.register_forward_hook(
make_separate_proj_hook(layer_idx, 'v', num_kv_heads))
hooks.append(hook)
logger.info(f"Registered QKV hooks for {len(hooks)//3} Mistral layers (GQA: {num_kv_heads} KV heads)")
except Exception as hook_error:
logger.warning(f"Could not register QKV hooks: {hook_error}")
# Phase 4: Hooks for attention and MLP output norms + gate activation stats
attn_output_norms = {}
mlp_output_norms = {}
gate_activation_stats = {}
# Per-layer top-K SwiGLU intermediate activations at the
# predicting position (last token of the current forward
# pass). Each entry is a list of {idx, value} for the
# top-K neurons by |silu(W_g·x) ⊙ (W_u·x)| at that layer
# for that step. Powers RQ1 Step 5's "Behind the SwiGLU"
# per-neuron view without storing the full 14,336-d
# vector — bounded memory, full transparency for the
# most-loaded neurons.
ffn_top_neurons = {}
FFN_TOPK = 32
def make_attn_output_hook(layer_idx):
def hook(module, input, output):
try:
out = output[0] if isinstance(output, tuple) else output
if out.dim() == 3:
attn_output_norms[layer_idx] = torch.norm(out[0, -1]).item()
except Exception:
pass
return hook
def make_mlp_output_hook(layer_idx):
def hook(module, input, output):
try:
out = output[0] if isinstance(output, tuple) else output
if out.dim() == 3:
mlp_output_norms[layer_idx] = torch.norm(out[0, -1]).item()
elif out.dim() == 2:
mlp_output_norms[layer_idx] = torch.norm(out[-1]).item()
except Exception:
pass
return hook
def make_gate_hook(layer_idx):
"""Capture gate activation stats for SwiGLU FFN (LLaMA/Mistral)."""
def hook(module, input, output):
try:
inp = input[0] if isinstance(input, tuple) else input
if inp.dim() == 3:
inp = inp[0, -1] # last token
elif inp.dim() == 2:
inp = inp[-1]
if hasattr(module, 'gate_proj'):
gate_out = torch.nn.functional.silu(module.gate_proj(inp))
abs_gate = gate_out.abs()
gate_activation_stats[layer_idx] = {
"sparsity": round(float((abs_gate < 0.01).float().mean().item()), 4),
"mean": round(float(gate_out.mean().item()), 4),
"max": round(float(gate_out.max().item()), 4),
}
except Exception:
pass
return hook
def make_ffn_top_neurons_hook(layer_idx):
"""
Capture the top-K of the SwiGLU intermediate activation
vector at the predicting (last) position for this layer.
Computes silu(W_gate · x) ⊙ (W_up · x) — the same
14,336-d intermediate that gets fed to W_down. Storing
only the top-K (=32) by |value| keeps memory bounded:
32 × {idx:int, value:float} ≈ 256 bytes per layer per
step, vs 14,336 × 4 bytes = 57KB per layer per step
if we stored the full vector. The top-K is what a
developer reads anyway (the rest are noise) and the
stored neuron index lets the frontend label "neuron
8421 dominated this token at L37".
Only fires for SwiGLU layers (gate_proj + up_proj
present); other architectures are skipped at
registration time.
"""
def hook(module, input, output):
try:
inp = input[0] if isinstance(input, tuple) else input
if inp.dim() == 3:
inp = inp[0, -1] # last (predicting) token
elif inp.dim() == 2:
inp = inp[-1]
if hasattr(module, 'gate_proj') and hasattr(module, 'up_proj'):
gate_out = torch.nn.functional.silu(
module.gate_proj(inp)
)
up_out = module.up_proj(inp)
intermediate = gate_out * up_out
abs_inter = intermediate.abs()
k = min(FFN_TOPK, intermediate.shape[-1])
top_vals, top_idx = torch.topk(abs_inter, k=k)
# Use the signed values (not abs) so the
# frontend can render direction; abs only
# drove the ranking.
signed = intermediate[top_idx]
ffn_top_neurons[layer_idx] = {
"k": k,
"intermediate_size": int(intermediate.shape[-1]),
"neurons": [
{
"idx": int(i),
"value": round(float(v), 4),
}
for i, v in zip(
top_idx.cpu().tolist(),
signed.cpu().tolist(),
)
],
}
except Exception:
pass
return hook
# Cache for decoded token texts (reused across heads within a step)
step_token_texts_cache: Dict[str, Any] = {}
# Detect FFN type from first layer
ffn_type = "gelu" # default
try:
# CodeGen style
if hasattr(manager.model, 'transformer') and hasattr(manager.model.transformer, 'h'):
for layer_idx, layer in enumerate(manager.model.transformer.h):
if hasattr(layer, 'attn'):
hook = layer.attn.register_forward_hook(make_attn_output_hook(layer_idx))
hooks.append(hook)
if hasattr(layer, 'mlp'):
hook = layer.mlp.register_forward_hook(make_mlp_output_hook(layer_idx))
hooks.append(hook)
# Mistral/LLaMA style
elif hasattr(manager.model, 'model') and hasattr(manager.model.model, 'layers'):
for layer_idx, layer in enumerate(manager.model.model.layers):
if hasattr(layer, 'self_attn'):
hook = layer.self_attn.register_forward_hook(make_attn_output_hook(layer_idx))
hooks.append(hook)
if hasattr(layer, 'mlp'):
hook = layer.mlp.register_forward_hook(make_mlp_output_hook(layer_idx))
hooks.append(hook)
# Gate hook for SwiGLU models
if hasattr(layer.mlp, 'gate_proj'):
hook = layer.mlp.register_forward_hook(make_gate_hook(layer_idx))
hooks.append(hook)
if layer_idx == 0:
ffn_type = "swiglu"
# FFN top-K intermediate hook — needs both
# gate_proj and up_proj to compute the
# SwiGLU intermediate vector.
if hasattr(layer.mlp, 'gate_proj') and hasattr(layer.mlp, 'up_proj'):
hook = layer.mlp.register_forward_hook(
make_ffn_top_neurons_hook(layer_idx)
)
hooks.append(hook)
logger.info(f"Registered attn/MLP output hooks for contribution tracking (ffn_type={ffn_type})")
except Exception as hook_error:
logger.warning(f"Could not register attn/MLP hooks: {hook_error}")
with torch.no_grad():
current_ids = inputs["input_ids"]
for step in range(max_tokens):
# Emit progress for this generation step
step_progress = (step / max_tokens) * 100
overall_progress = 10 + (step / max_tokens) * 20 # 10-30%
yield sse_event('generating', stage=2, totalStages=5, progress=overall_progress,
stageProgress=step_progress,
detail=f'Generating token {step + 1}/{max_tokens}',
metadata={'stepIndex': step, 'totalSteps': max_tokens})
await asyncio.sleep(0)
qkv_captures.clear()
attn_output_norms.clear()
mlp_output_norms.clear()
gate_activation_stats.clear()
ffn_top_neurons.clear()
# Forward pass with full outputs
outputs = manager.model(
current_ids,
output_attentions=True,
output_hidden_states=True
)
# Record the query position whose logits will select this
# step's token (see non-SSE site for rationale).
query_position = current_ids.shape[1] - 1
query_token_id = current_ids[0, -1].item()
if not ephemeral:
matrix_cache.set_step_query_info(
request_id, step, query_position, query_token_id
)
# Get logits for next token
raw_logits = outputs.logits[0, -1, :].clone() # Clone raw logits before any scaling
# Capture raw logits for top-10 tokens (before temperature scaling)
import math as math_module
top_n_display = 10 # Get top 10 alternatives for display
top_raw_logits, top_raw_indices = torch.topk(raw_logits, k=min(top_n_display, len(raw_logits)))
# Build raw logits entries (before temperature)
# Use correct tokenizer for Devstral vs other models.
# On the Mistral path, fall back to the HF tokenizer when
# mistral-common returns "" so logit candidates (e.g. EOS,
# chat-template ids) always carry a printable string.
def decode_token(tid):
if manager.model_id == "devstral-small" and manager.mistral_tokenizer is not None:
text = manager.mistral_tokenizer.decode_token(tid)
if text:
return text
try:
return manager.tokenizer.decode([tid], skip_special_tokens=False) or ""
except Exception:
return ""
else:
return manager.tokenizer.decode([tid], skip_special_tokens=False)
# ── Unembedding-cosine prep (SSE path) ──────────
# Mirrors the non-SSE path. Each logit is
# W_E[v] · h_post_norm; cos(W_E[v], h_post_norm)
# strips magnitude so a developer can read whether
# a high-logit token won by direction or by
# row magnitude. Cheap (one matmul per token per
# step) and computed once per step.
cos_h_norm = None
W_E = None
try:
final_hidden_pre_norm = outputs.hidden_states[-1][0, -1, :]
if hasattr(manager.model, 'model') and hasattr(manager.model.model, 'norm'):
h_post_norm = manager.model.model.norm(
final_hidden_pre_norm.unsqueeze(0)
)[0]
elif hasattr(manager.model, 'transformer') and hasattr(manager.model.transformer, 'ln_f'):
h_post_norm = manager.model.transformer.ln_f(
final_hidden_pre_norm.unsqueeze(0)
)[0]
else:
h_post_norm = final_hidden_pre_norm
h_norm_val = float(torch.linalg.vector_norm(h_post_norm).item())
if h_norm_val > 1e-9:
cos_h_norm = h_post_norm / h_norm_val
if hasattr(manager.model, 'lm_head'):
W_E = manager.model.lm_head.weight
else:
logger.warning(
"[SSE cosine prep] manager.model has no lm_head — cosine emission skipped"
)
else:
logger.warning(
f"[SSE cosine prep] h_post_norm magnitude too small: {h_norm_val}"
)
if cos_h_norm is not None and W_E is not None and step == 0:
logger.info(
f"[SSE cosine prep] enabled · h_post_norm shape {tuple(h_post_norm.shape)} · "
f"W_E shape {tuple(W_E.shape)} · h_norm {h_norm_val:.3f}"
)
except Exception as e:
logger.warning(
f"[SSE cosine prep] failed at step {step}: {type(e).__name__}: {e}"
)
cos_h_norm = None
W_E = None
def _cos_for(token_idx: int):
"""cosine(W_E[token_idx], h_post_norm) and ‖W_E row‖."""
if cos_h_norm is None or W_E is None:
return None, None
try:
row = W_E[token_idx]
row_norm = float(torch.linalg.vector_norm(row).item())
if row_norm < 1e-9:
return None, row_norm
cos = float(((row / row_norm) @ cos_h_norm).item())
return cos, row_norm
except Exception:
return None, None
logits_entries = []
for rank, (logit_val, idx) in enumerate(zip(top_raw_logits.tolist(), top_raw_indices.tolist())):
token_text = decode_token(idx)
cos, row_norm = _cos_for(idx)
entry = {
"token": token_text,
"token_id": idx,
"logit": logit_val,
"rank": rank + 1,
}
if cos is not None:
entry["cosine_sim"] = round(cos, 4)
if row_norm is not None:
entry["unemb_row_norm"] = round(row_norm, 4)
logits_entries.append(entry)
# Greedy token (argmax of raw logits, before any sampling)
greedy_token_id = torch.argmax(raw_logits).item()
greedy_token = decode_token(greedy_token_id)
# Compute raw probabilities (T=1) for comparison visualization
raw_probs = torch.softmax(raw_logits, dim=0)
# Apply temperature scaling
logits = raw_logits.clone()
if temperature > 0:
logits = logits / temperature
probs = torch.softmax(logits, dim=0)
# Apply top-k filtering if specified
if top_k_param is not None and top_k_param > 0:
top_k_probs, top_k_indices = torch.topk(probs, k=min(top_k_param, len(probs)))
probs_filtered = torch.zeros_like(probs)
probs_filtered[top_k_indices] = top_k_probs
probs_filtered = probs_filtered / probs_filtered.sum() # Renormalize
else:
probs_filtered = probs
# Apply top-p (nucleus) filtering if specified
if top_p_param is not None and top_p_param < 1.0:
sorted_probs, sorted_indices = torch.sort(probs_filtered, descending=True)
cumulative_probs = torch.cumsum(sorted_probs, dim=0)
cutoff_mask = cumulative_probs > top_p_param
cutoff_mask[1:] = cutoff_mask[:-1].clone()
cutoff_mask[0] = False
sorted_probs[cutoff_mask] = 0
probs_filtered = torch.zeros_like(probs)
probs_filtered.scatter_(0, sorted_indices, sorted_probs)
if probs_filtered.sum() > 0:
probs_filtered = probs_filtered / probs_filtered.sum()
if temperature == 0:
next_token_id = torch.argmax(probs_filtered, dim=-1).item()
else:
if probs_filtered.sum() > 0:
next_token_id = torch.multinomial(probs_filtered, 1).item()
else:
next_token_id = torch.argmax(probs, dim=-1).item()
next_token_text = decode_token(next_token_id)
generated_token_ids.append(next_token_id)
generated_tokens.append(next_token_text)
# Capture top-10 token alternatives with probabilities
# Use log_softmax for numerical stability at low temperatures
_, top_indices = torch.topk(logits, k=min(top_n_display, len(logits)))
# Use log_softmax (numerically stable) then exp() for probabilities
log_probs = torch.nn.functional.log_softmax(logits, dim=-1)
top_probs = torch.exp(log_probs[top_indices])
# See non-SSE site for the rationale behind emitting both
# `probability` (pre-filter model preference) and
# `effective_probability` (post-filter, what the sampler
# drew from). When no filter is active the two coincide.
is_filtered = bool(
(top_k_param is not None and top_k_param > 0)
or (top_p_param is not None and top_p_param < 1.0)
)
alternatives = []
cumulative = 0.0
selected_in_top = False
for rank, (prob, idx) in enumerate(zip(top_probs.tolist(), top_indices.tolist())):
token_text = decode_token(idx)
cumulative += prob
if idx == next_token_id:
selected_in_top = True
eff = probs_filtered[idx].item()
alternatives.append({
"token": token_text,
"token_id": idx,
"probability": prob,
"effective_probability": eff,
"is_eligible": eff > 0.0,
"raw_probability": raw_probs[idx].item(), # T=1 probability for comparison
"log_probability": math_module.log(prob) if prob > 0 else float('-inf'),
"cumulative_probability": cumulative,
"rank": rank + 1
})
# If selected token is not in top-N, add it with its actual probability
if not selected_in_top:
selected_prob = probs[next_token_id].item()
selected_eff = probs_filtered[next_token_id].item()
selected_raw_prob = raw_probs[next_token_id].item()
selected_log_prob = log_probs[next_token_id].item()
selected_logit = raw_logits[next_token_id].item()
# Find the rank of the selected token
sorted_indices = torch.argsort(raw_logits, descending=True)
selected_rank = (sorted_indices == next_token_id).nonzero(as_tuple=True)[0].item() + 1
alternatives.append({
"token": next_token_text,
"token_id": next_token_id,
"probability": selected_prob,
"effective_probability": selected_eff,
"is_eligible": selected_eff > 0.0,
"raw_probability": selected_raw_prob, # T=1 probability for comparison
"log_probability": selected_log_prob,
"cumulative_probability": None,
"rank": selected_rank,
"is_selected_outlier": True
})
# Also add to logits if not present
if next_token_id not in [e["token_id"] for e in logits_entries]:
cos_outlier, row_norm_outlier = _cos_for(next_token_id)
outlier_entry = {
"token": next_token_text,
"token_id": next_token_id,
"logit": selected_logit,
"rank": selected_rank,
"is_selected_outlier": True,
}
if cos_outlier is not None:
outlier_entry["cosine_sim"] = round(cos_outlier, 4)
if row_norm_outlier is not None:
outlier_entry["unemb_row_norm"] = round(
row_norm_outlier, 4
)
logits_entries.append(outlier_entry)
# Build sampling metadata
eligible_count = int((probs_filtered > 0).sum().item())
sampling_metadata = {
"temperature": temperature,
"top_k": top_k_param,
"top_p": top_p_param,
"greedy_token_id": greedy_token_id,
"greedy_token": greedy_token,
"was_greedy": next_token_id == greedy_token_id,
"is_filtered": is_filtered,
"eligible_count": eligible_count,
}
# --- Margin computation and stability classification ---
import math as _math_margin
winner_logit = logits_entries[0]["logit"] if len(logits_entries) > 0 else 0.0
runnerup_logit = logits_entries[1]["logit"] if len(logits_entries) > 1 else winner_logit
margin = winner_logit - runnerup_logit
runnerup_token = logits_entries[1]["token"] if len(logits_entries) > 1 else ""
# Entropy over top-k probabilities
top_probs_list_for_entropy = [a["probability"] for a in alternatives[:10] if a["probability"] > 0]
margin_entropy = -sum(p * _math_margin.log(p) for p in top_probs_list_for_entropy) if top_probs_list_for_entropy else 0.0
stability = _classify_stability(margin)
# Greedy margin: margin computed from raw logits (temperature=0)
raw_sorted_logits, raw_sorted_indices = torch.topk(raw_logits, k=min(2, len(raw_logits)))
raw_sorted_list = raw_sorted_logits.tolist()
greedy_margin = (raw_sorted_list[0] - raw_sorted_list[1]) if len(raw_sorted_list) >= 2 else 0.0
# Sampling sensitivity: did temperature change the outcome?
sampling_sensitive = next_token_id != greedy_token_id
winner_token = logits_entries[0]["token"] if len(logits_entries) > 0 else ""
margin_data = {
"margin": margin,
"winner_token": winner_token,
"winner_logit": winner_logit,
"runnerup_logit": runnerup_logit,
"runnerup_token": runnerup_token,
"entropy": margin_entropy,
"stability": stability,
"greedy_margin": greedy_margin,
"sampling_sensitive": sampling_sensitive,
}
token_alternatives_by_step.append({
"step": step,
"selected_token": next_token_text,
"selected_token_id": next_token_id,
"alternatives": alternatives,
"logits": logits_entries,
"sampling": sampling_metadata,
"margin": margin_data,
})
# Cache hidden states, logits, and full sequence for intervention endpoint
if not ephemeral:
try:
hidden_state_cache.store_step(request_id, step, outputs.hidden_states, raw_logits, current_ids)
if step == 0:
hidden_state_cache.store_input_ids(request_id, current_ids[:, :-1]) # prompt only
except Exception as hs_err:
logger.debug(f"Hidden state cache error at step {step}: {hs_err}")
# Emit generated token immediately so clients can show code progressively
yield sse_event('generated_token', stage=2, totalStages=5,
progress=10 + ((step + 1) / max_tokens) * 20,
stageProgress=((step + 1) / max_tokens) * 100,
detail=f'Generated token {step + 1}/{max_tokens}',
metadata={
'stepIndex': step,
'totalSteps': max_tokens,
'token': next_token_text,
'tokenId': next_token_id,
'generatedTokens': generated_tokens.copy(),
})
await asyncio.sleep(0)
# === STAGE 3: EXTRACTING (per layer within each token) ===
# Optimised: batched tensor ops per layer instead of per-head Python loops
# Reduces GPU→CPU sync points from ~4000 to ~40 per token
layer_data_this_token = []
n_total_layers = len(outputs.attentions)
# Margin contribution decomposition: compute the "logit difference direction"
# (W_U[winner] - W_U[runner-up]) once, then dot with each layer's residual
margin_diff_direction = None
winner_token_id_for_decomp = logits_entries[0]["token_id"] if len(logits_entries) > 0 else None
runnerup_token_id_for_decomp = logits_entries[1]["token_id"] if len(logits_entries) > 1 else None
if winner_token_id_for_decomp is not None and runnerup_token_id_for_decomp is not None:
try:
lm_head_weight = manager.model.lm_head.weight # [vocab_size, d_model]
margin_diff_direction = (lm_head_weight[winner_token_id_for_decomp] - lm_head_weight[runnerup_token_id_for_decomp]).detach()
except Exception:
margin_diff_direction = None
for layer_idx in range(n_total_layers):
# Emit extraction progress (within generating stage for combined progress)
if step == max_tokens - 1: # Only emit detailed layer progress on last token
layer_progress = (layer_idx / n_total_layers) * 100
overall_progress = 30 + (layer_idx / n_total_layers) * 40 # 30-70%
yield sse_event('extracting', stage=3, totalStages=5, progress=overall_progress,
stageProgress=layer_progress,
detail=f'Processing layer {layer_idx + 1}/{n_total_layers}',
metadata={'layerIndex': layer_idx, 'totalLayers': n_total_layers,
'headsPerLayer': n_heads, 'stepIndex': step, 'totalSteps': max_tokens})
if layer_idx % 5 == 0:
await asyncio.sleep(0)
# --- Per-layer: bulk GPU ops then single CPU transfer ---
layer_attn = outputs.attentions[layer_idx][0] # [n_heads, seq_len, seq_len]
current_hidden = outputs.hidden_states[layer_idx + 1]
if current_hidden.dim() == 3:
current_hidden = current_hidden[0]
# Hidden state metrics — 4 values, one .cpu() call
last_token_hidden = current_hidden[-1]
if layer_idx > 0:
prev_hidden = outputs.hidden_states[layer_idx]
if prev_hidden.dim() == 3:
prev_hidden = prev_hidden[0]
hidden_metrics = torch.stack([
torch.norm(current_hidden - prev_hidden),
torch.norm(current_hidden),
torch.std(last_token_hidden),
torch.norm(last_token_hidden),
]).cpu().tolist()
delta_norm, activation_magnitude, activation_entropy, hidden_state_norm = hidden_metrics
else:
hidden_metrics = torch.stack([
torch.norm(current_hidden),
torch.std(last_token_hidden),
torch.norm(last_token_hidden),
]).cpu().tolist()
activation_magnitude, activation_entropy, hidden_state_norm = hidden_metrics
delta_norm = None
# Sanitize hidden state metrics
activation_magnitude = 0.0 if math.isnan(activation_magnitude) or math.isinf(activation_magnitude) else activation_magnitude
activation_entropy = 0.0 if math.isnan(activation_entropy) or math.isinf(activation_entropy) else activation_entropy
hidden_state_norm = 0.0 if math.isnan(hidden_state_norm) or math.isinf(hidden_state_norm) else hidden_state_norm
if delta_norm is not None:
delta_norm = 0.0 if math.isnan(delta_norm) or math.isinf(delta_norm) else delta_norm
# Margin contribution decomposition:
# margin_contribution = (W_U[winner] - W_U[runner-up]) · (h_{ℓ+1} - h_ℓ)
# This causally attributes the final margin to each layer's residual contribution.
margin_contribution = None
if margin_diff_direction is not None:
try:
if layer_idx > 0:
prev_h = outputs.hidden_states[layer_idx]
if prev_h.dim() == 3:
prev_h = prev_h[0]
residual = current_hidden[-1] - prev_h[-1]
else:
# Layer 0: the embedding contribution
residual = current_hidden[-1]
mc = torch.dot(margin_diff_direction, residual).item()
margin_contribution = 0.0 if math.isnan(mc) or math.isinf(mc) else mc
except Exception:
margin_contribution = None
# --- Batched head processing: all heads at once on GPU ---
num_heads_layer = layer_attn.shape[0]
# Last-row attention weights for all heads: [n_heads, seq_len]
all_last_row = layer_attn[:, -1, :]
# Max weight per head: [n_heads] — single GPU op
all_max_weights = all_last_row.max(dim=-1).values
# Entropy of last-row per head: [n_heads] — single GPU op
all_entropies = -(all_last_row * torch.log(all_last_row + 1e-10)).sum(dim=-1)
# Normalized average entropy per head (latter half of query positions)
# layer_attn: [n_heads, q_len, k_len]
q_len = layer_attn.shape[1]
# Raw entropy per query position per head: [n_heads, q_len]
all_token_entropies = -(layer_attn * torch.log(layer_attn + 1e-10)).sum(dim=-1)
# Normalize by log(position): [q_len]
positions = torch.arange(1, q_len + 1, device=layer_attn.device, dtype=layer_attn.dtype)
max_ents = torch.log(positions + 1e-10) # [q_len]
all_normalized = all_token_entropies / (max_ents.unsqueeze(0) + 1e-10) # [n_heads, q_len]
# Average over latter half: [n_heads]
start_idx = q_len // 2
if start_idx < q_len:
all_avg_entropies = all_normalized[:, start_idx:].mean(dim=-1)
else:
all_avg_entropies = all_normalized.mean(dim=-1)
# Previous-token weights for pattern detection: [n_heads]
all_prev_token_weights = all_last_row[:, -2] if all_last_row.shape[1] >= 2 else torch.zeros(num_heads_layer, device=layer_attn.device)
# Attention sink weights: sum of attention on positions 0-2 per head [n_heads]
seq_len_attn = all_last_row.shape[1]
all_sink_weights = all_last_row[:, :min(3, seq_len_attn)].sum(dim=-1)
# Local attention weights: sum within 5 positions of query per head [n_heads]
all_local_weights = all_last_row[:, max(0, seq_len_attn - 5):].sum(dim=-1) if seq_len_attn > 5 else torch.ones(num_heads_layer, device=layer_attn.device)
# Induction detection: attention to positions following previous occurrences of current token
all_induction_weights = torch.zeros(num_heads_layer, device=layer_attn.device)
if step > 0:
current_token = current_ids[0, -1]
prev_occurrences = (current_ids[0, :-1] == current_token).nonzero(as_tuple=True)[0]
if len(prev_occurrences) > 0:
following_positions = prev_occurrences + 1
following_positions = following_positions[following_positions < seq_len_attn]
if len(following_positions) > 0:
all_induction_weights = all_last_row[:, following_positions].sum(dim=-1)
# Single bulk transfer: all head metrics to CPU
head_metrics_gpu = torch.stack([
all_max_weights, all_entropies, all_avg_entropies, all_prev_token_weights,
all_sink_weights, all_local_weights, all_induction_weights
]) # [7, n_heads]
head_metrics_cpu = head_metrics_gpu.cpu().tolist() # one sync point
max_weights_list = head_metrics_cpu[0]
entropies_list = head_metrics_cpu[1]
avg_entropies_list = head_metrics_cpu[2]
prev_token_list = head_metrics_cpu[3]
sink_weights_list = head_metrics_cpu[4]
local_weights_list = head_metrics_cpu[5]
induction_weights_list = head_metrics_cpu[6]
# Bulk transfer attention matrices to CPU: one .cpu() for entire layer
layer_attn_cpu = layer_attn.cpu().float().numpy() # [n_heads, seq_len, seq_len]
# QKV matrices (already on CPU from hooks)
qkv_layer = qkv_captures.get(layer_idx)
# Build per-head metadata from CPU-side data (no more GPU calls)
critical_heads = []
for head_idx in range(num_heads_layer):
mw = max_weights_list[head_idx]
ent = entropies_list[head_idx]
avg_ent = avg_entropies_list[head_idx]
ptw = prev_token_list[head_idx]
skw = sink_weights_list[head_idx]
lcw = local_weights_list[head_idx]
idw = induction_weights_list[head_idx]
# Sanitize
mw = 0.0 if math.isnan(mw) or math.isinf(mw) else mw
ent = 0.0 if math.isnan(ent) or math.isinf(ent) else ent
avg_ent = 0.0 if math.isnan(avg_ent) or math.isinf(avg_ent) else avg_ent
# Score-all-then-rank head classification
# Behaviour type scores (attention geometry)
behaviour_scores = {
"attention_sink": skw,
"previous_token": ptw,
"local": lcw,
"induction": min(1.0, idw),
"focused": max(0.0, 1.0 - ent) if ent < 1.5 else 0.0,
"diffuse": min(1.0, max(0.0, (ent - 1.0) / 2.0)),
}
behaviour_thresholds = {
"attention_sink": 0.4,
"previous_token": 0.7,
"local": 0.5,
"induction": 0.2,
"focused": 0.3,
"diffuse": 0.3,
}
qualified = {
k: v for k, v in behaviour_scores.items()
if v >= behaviour_thresholds.get(k, 0.3)
}
sorted_behaviours = sorted(qualified.items(), key=lambda x: x[1], reverse=True)
primary = sorted_behaviours[0] if sorted_behaviours else ("diffuse", behaviour_scores["diffuse"])
secondary = sorted_behaviours[1] if len(sorted_behaviours) > 1 else None
pattern_type = primary[0]
confidence = primary[1]
confidence = 0.0 if math.isnan(confidence) or math.isinf(confidence) else confidence
# Code cue scores (what code tokens are attended to)
# Decode token texts once per step (cached via nonlocal)
if step_token_texts_cache.get('step') != step:
try:
step_token_texts_cache['texts'] = [
manager.tokenizer.decode([tid]) for tid in current_ids[0, :seq_len_attn].tolist()
]
except Exception:
step_token_texts_cache['texts'] = []
step_token_texts_cache['step'] = step
token_texts = step_token_texts_cache.get('texts', [])
code_cues = {}
if len(token_texts) == seq_len_attn:
head_weights = all_last_row[head_idx].cpu()
delimiters = {'(', ')', '{', '}', '[', ']', ':', ';', ','}
delim_indices = [i for i, t in enumerate(token_texts) if t.strip() in delimiters]
if delim_indices:
code_cues["delimiter_sensitive"] = head_weights[delim_indices].sum().item()
keywords = {'def', 'return', 'if', 'else', 'elif', 'for', 'while', 'class',
'import', 'from', 'try', 'except', 'with', 'as', 'in', 'not',
'and', 'or', 'True', 'False', 'None', 'self', 'yield', 'async',
'await', 'lambda', 'raise', 'pass', 'break', 'continue',
'function', 'const', 'let', 'var', 'new', 'this',
'public', 'private', 'static', 'void', 'int', 'string', 'bool',
'namespace', 'using', 'class', 'interface', 'override', 'virtual'}
kw_indices = [i for i, t in enumerate(token_texts) if t.strip() in keywords]
if kw_indices:
code_cues["keyword_sensitive"] = head_weights[kw_indices].sum().item()
if idw > 0.15:
code_cues["pattern_reuse"] = min(1.0, idw * 1.5)
cue_threshold = 0.15
sorted_cues = sorted(
[(k, round(v, 4)) for k, v in code_cues.items() if v >= cue_threshold],
key=lambda x: x[1], reverse=True
)
primary_cue = sorted_cues[0] if sorted_cues else None
attention_matrix = layer_attn_cpu[head_idx]
q_matrix = None
k_matrix = None
v_matrix = None
if qkv_layer is not None:
q_matrix = qkv_layer['q'][:, head_idx, :].float().numpy()
k_matrix = qkv_layer['k'][:, head_idx, :].float().numpy()
v_matrix = qkv_layer['v'][:, head_idx, :].float().numpy()
if not ephemeral:
matrix_cache.store(request_id, step, layer_idx, head_idx, {
"attention_weights": attention_matrix,
"q_matrix": q_matrix,
"k_matrix": k_matrix,
"v_matrix": v_matrix
})
head_entry = {
"head_idx": head_idx,
"entropy": ent,
"avg_entropy": avg_ent,
"max_weight": mw,
"has_matrices": attention_matrix is not None,
"pattern": {"type": pattern_type, "confidence": round(confidence, 4)} if pattern_type else None,
}
if secondary:
head_entry["secondary_behaviour"] = {"type": secondary[0], "score": round(secondary[1], 4)}
if primary_cue:
head_entry["code_cue"] = {
"type": primary_cue[0],
"score": primary_cue[1],
"evidence": f"{round(primary_cue[1] * 100)}% attention on {primary_cue[0].replace('_', ' ')} tokens",
}
if len(sorted_cues) > 1:
head_entry["secondary_cue"] = {"type": sorted_cues[1][0], "score": sorted_cues[1][1]}
critical_heads.append(head_entry)
critical_heads.sort(key=lambda h: h["max_weight"], reverse=True)
# Layer-level pattern: majority vote of head patterns, weighted by confidence
pattern_votes = {}
for h in critical_heads:
if h["pattern"] and h["pattern"]["type"]:
pt = h["pattern"]["type"]
pc = h["pattern"]["confidence"]
pattern_votes[pt] = pattern_votes.get(pt, 0.0) + pc
layer_pattern = None
if pattern_votes:
best_type = max(pattern_votes, key=pattern_votes.get)
total_conf = sum(pattern_votes.values())
layer_pattern = {
"type": best_type,
"confidence": round(pattern_votes[best_type] / total_conf, 3) if total_conf > 0 else 0.0
}
layer_entry = {
"layer_idx": layer_idx,
"pattern": layer_pattern,
"critical_heads": critical_heads,
"activation_magnitude": activation_magnitude,
"activation_entropy": activation_entropy,
"hidden_state_norm": hidden_state_norm,
"delta_norm": delta_norm,
"margin_contribution": margin_contribution,
}
# Phase 4: Attention and MLP output norms + contribution ratios
if layer_idx in attn_output_norms:
layer_entry["attn_output_norm"] = round(attn_output_norms[layer_idx], 4)
if layer_idx in mlp_output_norms:
layer_entry["mlp_output_norm"] = round(mlp_output_norms[layer_idx], 4)
if layer_idx in attn_output_norms and layer_idx in mlp_output_norms:
attn_n = attn_output_norms[layer_idx]
mlp_n = mlp_output_norms[layer_idx]
total = attn_n + mlp_n
if total > 0:
layer_entry["attn_contribution"] = round(attn_n / total, 4)
layer_entry["ffn_contribution"] = round(mlp_n / total, 4)
if layer_idx in gate_activation_stats:
layer_entry["gate_stats"] = gate_activation_stats[layer_idx]
if layer_idx in ffn_top_neurons:
# `ffn_top_neurons` holds top-K SwiGLU
# intermediate activations at the
# predicting position — see
# make_ffn_top_neurons_hook for the
# per-neuron value semantics. The frontend
# uses this to render Step 5's per-neuron
# bar chart inside "Behind the SwiGLU"
# without the backend needing a separate
# endpoint or a 14,336-d cache entry.
layer_entry["ffn_top_neurons"] = ffn_top_neurons[layer_idx]
# Phase 5: Logit lens at every layer.
# The lens projection is a single matmul
# [1, hidden] × [hidden, vocab] ≈ 0.5-1ms on
# Apple Silicon MPS — 40 layers × N_steps adds
# only ~5-10s to a typical analyse run. Worth
# the cost: every-layer sampling eliminates
# the (L17, L24]-style uncertainty windows the
# frontend's crystallisation narrative would
# otherwise have to qualify, giving developers
# a layer-precise commit point for trust
# decisions about the model's prediction.
logit_lens_stride = 1
if layer_idx % logit_lens_stride == 0 or layer_idx == n_layers - 1:
try:
hidden_for_lens = current_hidden[-1].unsqueeze(0) # [1, hidden_dim]
# Apply final layer norm then project through lm_head
if hasattr(manager.model, 'model') and hasattr(manager.model.model, 'norm'):
normed = manager.model.model.norm(hidden_for_lens)
lens_logits = manager.model.lm_head(normed)[0] # [vocab_size]
elif hasattr(manager.model, 'transformer') and hasattr(manager.model.transformer, 'ln_f'):
normed = manager.model.transformer.ln_f(hidden_for_lens)
lens_logits = manager.model.lm_head(normed)[0]
else:
lens_logits = None
if lens_logits is not None:
lens_probs = torch.softmax(lens_logits, dim=-1)
top_probs, top_ids = torch.topk(lens_probs, k=5)
top_probs_list = top_probs.cpu().tolist()
top_ids_list = top_ids.cpu().tolist()
lens_entries = []
for tp, tid in zip(top_probs_list, top_ids_list):
lens_entries.append({
"token": manager.tokenizer.decode([tid], skip_special_tokens=False),
"probability": tp
})
layer_entry["logit_lens_top"] = lens_entries
# Layer-wise margin tracking (raw logit diff between top-1 and top-2)
top2_logits, top2_ids = torch.topk(lens_logits, k=min(2, len(lens_logits)))
top2_logits_list = top2_logits.cpu().tolist()
top2_ids_list = top2_ids.cpu().tolist()
layer_winner_token = manager.tokenizer.decode([top2_ids_list[0]], skip_special_tokens=False)
layer_runnerup_token = manager.tokenizer.decode([top2_ids_list[1]], skip_special_tokens=False) if len(top2_ids_list) > 1 else ""
layer_margin_val = (top2_logits_list[0] - top2_logits_list[1]) if len(top2_logits_list) > 1 else 0.0
layer_entry["layer_margin"] = layer_margin_val
layer_entry["layer_winner"] = layer_winner_token
layer_entry["layer_runnerup"] = layer_runnerup_token
# Tuned lens: apply per-layer affine correction
from .tuned_lens import tuned_lens_runtime
if tuned_lens_runtime.available:
try:
corrected = tuned_lens_runtime.apply(layer_idx, hidden_for_lens)
tuned_normed = normed.__class__ # reuse same LN path
# Re-apply final LN + lm_head on corrected hidden
if hasattr(manager.model, 'model') and hasattr(manager.model.model, 'norm'):
tuned_normed = manager.model.model.norm(corrected)
tuned_logits = manager.model.lm_head(tuned_normed)[0]
elif hasattr(manager.model, 'transformer') and hasattr(manager.model.transformer, 'ln_f'):
tuned_normed = manager.model.transformer.ln_f(corrected)
tuned_logits = manager.model.lm_head(tuned_normed)[0]
else:
tuned_logits = None
if tuned_logits is not None:
tuned_probs = torch.softmax(tuned_logits, dim=-1)
tuned_top_probs, tuned_top_ids = torch.topk(tuned_probs, k=5)
tuned_entries = []
for tp, tid in zip(tuned_top_probs.cpu().tolist(), tuned_top_ids.cpu().tolist()):
tuned_entries.append({
"token": manager.tokenizer.decode([tid], skip_special_tokens=False),
"probability": tp
})
layer_entry["tuned_lens_top"] = tuned_entries
tuned_top2_logits, tuned_top2_ids = torch.topk(tuned_logits, k=min(2, len(tuned_logits)))
tuned_top2_logits_list = tuned_top2_logits.cpu().tolist()
tuned_top2_ids_list = tuned_top2_ids.cpu().tolist()
layer_entry["tuned_layer_winner"] = manager.tokenizer.decode([tuned_top2_ids_list[0]], skip_special_tokens=False)
layer_entry["tuned_layer_runnerup"] = manager.tokenizer.decode([tuned_top2_ids_list[1]], skip_special_tokens=False) if len(tuned_top2_ids_list) > 1 else ""
layer_entry["tuned_layer_margin"] = (tuned_top2_logits_list[0] - tuned_top2_logits_list[1]) if len(tuned_top2_logits_list) > 1 else 0.0
except Exception as tuned_err:
logger.debug(f"Tuned lens error at layer {layer_idx}: {tuned_err}")
except Exception as lens_err:
logger.debug(f"Logit lens error at layer {layer_idx}: {lens_err}")
layer_data_this_token.append(layer_entry)
layer_data_by_token.append(layer_data_this_token)
# Update inputs
next_token_tensor = torch.tensor([[next_token_id]], dtype=torch.long, device=manager.device)
current_ids = torch.cat([current_ids, next_token_tensor], dim=1)
# Stop on EOS
if next_token_id == manager.tokenizer.eos_token_id:
break
# Free memory from this step's outputs to prevent accumulation
# This is critical for large models like Devstral (40 layers, 32 heads)
del outputs
del logits
del probs
if 'layer_attn' in dir():
del layer_attn
if 'current_hidden' in dir():
del current_hidden
# Periodic garbage collection for large models (every 8 steps)
if (step + 1) % 8 == 0:
gc.collect()
if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
torch.mps.empty_cache() if hasattr(torch.mps, 'empty_cache') else None
# Clean up hooks
for hook in hooks:
hook.remove()
# === STAGE 4: SERIALIZING ===
yield sse_event('serializing', stage=4, totalStages=5, progress=75,
stageProgress=0, detail='Building response data...')
await asyncio.sleep(0)
qkv_by_layer_head = {}
generation_time = time.time() - start_time
# Calculate token section boundaries
total_tokens = prompt_length + len(generated_token_ids)
system_prompt_text = system_prompt_override or (model_config.get("system_prompt") if model_config else None)
system_prompt_end = 0
if prompt_style == "instruction" and system_prompt_text:
if manager.model_id == "devstral-small" and manager.mistral_tokenizer is not None:
try:
no_system_tokens = manager.mistral_tokenizer.encode_chat("", prompt)
# Add 1 to include the closing [/SYSTEM_PROMPT] tag in system section
system_prompt_end = prompt_length - len(no_system_tokens) + 1
system_prompt_end = max(0, min(system_prompt_end, prompt_length))
except Exception:
system_prompt_end = 0
else:
total_chars = len(system_prompt_text or "") + len(prompt)
if total_chars > 0:
system_ratio = len(system_prompt_text or "") / total_chars
system_prompt_end = int(prompt_length * system_ratio)
token_sections = {
"systemPrompt": {
"start": 0,
"end": system_prompt_end,
"text": system_prompt_text,
"tokenCount": system_prompt_end
},
"userPrompt": {
"start": system_prompt_end,
"end": prompt_length,
"text": prompt,
"tokenCount": prompt_length - system_prompt_end
},
"output": {
"start": prompt_length,
"end": total_tokens,
"text": "".join(generated_tokens),
"tokenCount": len(generated_token_ids)
}
}
yield sse_event('serializing', stage=4, totalStages=5, progress=82,
stageProgress=50, detail='Building token metadata...')
await asyncio.sleep(0)
# Build token metadata
from .tokenizer_utils import TokenizerMetadata
token_metadata_builder = TokenizerMetadata(manager.tokenizer)
# Include every id the tokenizer considers a special / added token
# (BOS, EOS, PAD, UNK, chat-template delimiters like [INST]/[/INST],
# system-prompt markers, tool-call markers, etc.). See the matching
# construction in the non-streaming endpoint for rationale.
special_token_ids_set = set(getattr(manager.tokenizer, "all_special_ids", []) or [])
for tok_id in (
manager.tokenizer.eos_token_id,
manager.tokenizer.bos_token_id,
manager.tokenizer.pad_token_id,
manager.tokenizer.unk_token_id,
):
if tok_id is not None:
special_token_ids_set.add(tok_id)
if manager.mistral_tokenizer is not None:
special_token_ids_set |= manager.mistral_tokenizer.get_control_token_ids()
def build_token_data(token_ids, token_texts, token_type):
multi_split_flags = token_metadata_builder.is_multi_split_identifier(token_ids)
result = []
for i, (tid, t) in enumerate(zip(token_ids, token_texts)):
bpe_pieces = token_metadata_builder.get_subword_pieces(tid)
result.append({
"text": t,
"idx": tid,
"bytes": len(t.encode('utf-8')),
"type": token_type,
"bpe_pieces": bpe_pieces,
"is_special": tid in special_token_ids_set,
"is_multi_split": multi_split_flags[i] if i < len(multi_split_flags) else False,
"num_pieces": len(bpe_pieces),
})
return result
# Compute margin statistics and commitment summary
margin_stats = {"fragile_count": 0, "boundary_count": 0, "moderate_count": 0, "stable_count": 0}
commitment_layers = []
flip_count = 0
for step_data in token_alternatives_by_step:
m = step_data.get("margin", {})
stab = m.get("stability", "stable")
if stab == "fragile":
margin_stats["fragile_count"] += 1
elif stab == "boundary":
margin_stats["boundary_count"] += 1
elif stab == "moderate":
margin_stats["moderate_count"] += 1
else:
margin_stats["stable_count"] += 1
# Commitment layer and flip detection from layer data
for step_idx, step_layers in enumerate(layer_data_by_token):
lens_layers = [l for l in step_layers if l.get("layer_margin") is not None]
if not lens_layers:
continue
# Find commitment layer: first layer where margin > 0.3 and stays positive
step_commitment = None
for i, ll in enumerate(lens_layers):
if ll["layer_margin"] > 0.3:
stays_positive = all(lens_layers[j]["layer_margin"] > 0 for j in range(i, len(lens_layers)))
if stays_positive:
step_commitment = ll["layer_idx"]
break
if step_commitment is not None:
commitment_layers.append(step_commitment)
# Count flips: where winner changes between consecutive lens layers
for i in range(1, len(lens_layers)):
prev_winner = (lens_layers[i-1].get("layer_winner") or "").strip()
curr_winner = (lens_layers[i].get("layer_winner") or "").strip()
if prev_winner and curr_winner and prev_winner != curr_winner:
flip_count += 1
avg_commitment = sum(commitment_layers) / len(commitment_layers) if commitment_layers else n_layers
late_threshold = n_layers * 0.75
late_count = sum(1 for cl in commitment_layers if cl > late_threshold)
commitment_summary = {
"avg_commitment_layer": round(avg_commitment, 1),
"late_commitment_count": late_count,
"flip_count": flip_count,
}
# Tuned lens commitment summary (parallel to raw)
tuned_commitment_summary = None
from .tuned_lens import tuned_lens_runtime
if tuned_lens_runtime.available:
tuned_commitment_layers = []
tuned_flip_count = 0
for step_idx, step_layers in enumerate(layer_data_by_token):
tuned_lens_layers = [l for l in step_layers if l.get("tuned_layer_margin") is not None]
if not tuned_lens_layers:
continue
step_commitment = None
for i, ll in enumerate(tuned_lens_layers):
if ll["tuned_layer_margin"] > 0.3:
stays_positive = all(tuned_lens_layers[j]["tuned_layer_margin"] > 0 for j in range(i, len(tuned_lens_layers)))
if stays_positive:
step_commitment = ll["layer_idx"]
break
if step_commitment is not None:
tuned_commitment_layers.append(step_commitment)
for i in range(1, len(tuned_lens_layers)):
prev_w = (tuned_lens_layers[i-1].get("tuned_layer_winner") or "").strip()
curr_w = (tuned_lens_layers[i].get("tuned_layer_winner") or "").strip()
if prev_w and curr_w and prev_w != curr_w:
tuned_flip_count += 1
tuned_avg = sum(tuned_commitment_layers) / len(tuned_commitment_layers) if tuned_commitment_layers else n_layers
tuned_late = sum(1 for cl in tuned_commitment_layers if cl > late_threshold)
tuned_commitment_summary = {
"avg_commitment_layer": round(tuned_avg, 1),
"late_commitment_count": tuned_late,
"flip_count": tuned_flip_count,
}
# === Embedding L2 norms — per-input-token layer-0 anchor ===
# One float per token in the FULL context (prompt +
# generated): ‖e_i‖ where e_i is the row the embedding
# matrix returns for token i. The Mechanism lens uses this
# as the real-data anchor for the residual-norm trace
# shown in the Microscope rail (RQ1: developer-
# interpretable architectural signal at the embedding
# stage). Generated tokens are included so the chart
# reflects the actual input the model sees at every
# selected step. Memory is bounded by the number of
# *unique* token ids — see _compute_embedding_norms.
embedding_norms: List[float] = _compute_embedding_norms(
manager,
list(prompt_token_ids) + list(generated_token_ids),
)
# Build response
response = {
"requestId": request_id, # For lazy-loading matrices via /matrix endpoint
"prompt": prompt,
"promptTokens": build_token_data(prompt_token_ids, prompt_tokens, "prompt"),
"generatedTokens": build_token_data(generated_token_ids, generated_tokens, "generated"),
"tokenSections": token_sections,
"tokenAlternatives": token_alternatives_by_step,
"layersDataByStep": layer_data_by_token,
"layersData": layer_data_by_token[-1] if layer_data_by_token else [],
"qkvData": {}, # Deprecated: matrices now lazy-loaded via /matrix endpoint
"modelInfo": {
"numLayers": n_layers,
"numHeads": n_heads,
"modelDimension": d_model,
"headDim": head_dim,
"vocabSize": manager.model.config.vocab_size,
"tunedLensAvailable": tuned_lens_runtime.available,
"ffnType": ffn_type,
"intermediateSize": getattr(manager.model.config, 'intermediate_size', None),
},
"embeddingNorms": embedding_norms,
"generationTime": generation_time,
"numTokensGenerated": len(generated_tokens),
"marginStats": margin_stats,
"commitmentSummary": commitment_summary,
**({"tunedCommitmentSummary": tuned_commitment_summary} if tuned_commitment_summary else {}),
}
# Estimate response size
response_json = json.dumps(sanitize_for_json(response))
response_size_bytes = len(response_json.encode('utf-8'))
yield sse_event('serializing', stage=4, totalStages=5, progress=90,
stageProgress=100, detail=f'Response ready ({response_size_bytes / 1024 / 1024:.1f}MB)',
metadata={'responseSizeBytes': response_size_bytes})
await asyncio.sleep(0)
# === STAGE 5: COMPLETE ===
yield sse_event('complete', stage=5, totalStages=5, progress=95,
stageProgress=0, detail='Transferring data...',
metadata={'responseSizeBytes': response_size_bytes, 'generationTimeMs': int(generation_time * 1000)})
logger.info(f"✅ [SSE] Research attention analysis complete: {len(generated_tokens)} tokens, {generation_time:.2f}s, {response_size_bytes / 1024 / 1024:.1f}MB")
# Send final result
yield sse_event('result', data=sanitize_for_json(response))
except Exception as e:
logger.error(f"[SSE] Research attention analysis error: {e}")
logger.error(traceback.format_exc())
yield sse_event('error', detail=str(e), stage=0, totalStages=5, progress=0, stageProgress=0)
return StreamingResponse(
event_generator(),
media_type='text/event-stream',
headers={
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no', # Disable nginx/proxy buffering
}
)
@app.get("/analyze/research/attention/matrix")
async def get_attention_matrix(
request_id: str,
step: int,
layer: int,
head: Optional[int] = None,
aggregate_mode: str = "mean",
authenticated: bool = Depends(verify_api_key),
):
"""
Retrieve cached attention/QKV matrices for a specific head, OR an
aggregated attention matrix across all heads when `head` is omitted.
Used for lazy-loading matrix data when the user opens an inline
head panel (per-head Q/K/V) or the Mechanism lens's Step 4
attention matrix view (aggregate by default). Matrices are cached
during the initial analysis and available for 60 minutes.
Parameters:
- request_id: UUID from the original analysis response
- step: Generation step (0 = first generated token)
- layer: Layer index (0-based)
- head: Head index (0-based). Omit for an aggregate matrix across
all heads — the returned payload then contains only
`attention_weights` (the Q/K/V projections are per-head and
have no canonical aggregate form).
- aggregate_mode: "mean" or "max" when `head` is omitted.
Returns:
- attention_weights: [seq_len, seq_len] attention matrix
- q_matrix / k_matrix / v_matrix: [seq_len, head_dim] projections
(only when `head` is specified)
- layer: Layer index
- head: Head index, or null when aggregated
- aggregate_mode: Aggregation mode used, or null for per-head
"""
if head is not None:
data = matrix_cache.get(request_id, step, layer, head)
if data is None:
logger.warning(
f"Matrix cache miss: request_id={request_id}, step={step}, layer={layer}, head={head}"
)
raise HTTPException(
status_code=404,
detail="Matrix data not found. Cache may have expired (60 min TTL). Please re-analyze.",
)
logger.info(
f"Matrix cache hit: request_id={request_id}, step={step}, layer={layer}, head={head}"
)
# Convert numpy arrays to lists for JSON serialization. Arrays
# are stored as numpy for memory efficiency, converted on-
# demand here.
response = {}
for key, value in data.items():
if value is not None and hasattr(value, "tolist"):
response[key] = value.tolist()
else:
response[key] = value
response["layer"] = layer
response["head"] = head
response["aggregate_mode"] = None
return response
# Aggregate path — averages or max-pools attention matrices across
# heads. Q/K/V projections are intentionally omitted; they're
# per-head quantities and don't have a canonical aggregate.
aggregate = matrix_cache.get_aggregate_attention_matrix(
request_id, step, layer, aggregate_mode
)
if aggregate is None:
logger.warning(
f"Aggregate matrix cache miss: request_id={request_id}, step={step}, layer={layer}, mode={aggregate_mode}"
)
raise HTTPException(
status_code=404,
detail="Matrix data not found. Cache may have expired (60 min TTL). Please re-analyze.",
)
logger.info(
f"Aggregate matrix cache hit: request_id={request_id}, step={step}, layer={layer}, mode={aggregate_mode}"
)
return {
"attention_weights": aggregate,
"layer": layer,
"head": None,
"aggregate_mode": aggregate_mode,
}
@app.get("/analyze/research/attention/matrix/stats")
async def get_matrix_cache_stats(authenticated: bool = Depends(verify_api_key)):
"""Return matrix cache statistics for monitoring."""
return matrix_cache.get_stats()
@app.get("/analyze/research/attention/row")
async def get_attention_row(
request_id: str,
step: int,
layer: int,
head: Optional[int] = None,
aggregate_mode: str = "mean",
authenticated: bool = Depends(verify_api_key)
):
"""
Retrieve single attention row for overlay visualization.
Returns the attention weights from the query token (at position `step`)
to all preceding positions. This is a minimal payload for efficient
lazy-loading in the attention overlay feature.
Parameters:
- request_id: UUID from the original analysis response
- step: Generation step (0 = first generated token)
- layer: Layer index (0-based)
- head: Head index (0-based), or None for aggregated view
- aggregate_mode: "mean" or "max" when head is None
Returns:
- attention_weights: List of attention weights [0..seq_len]
- seq_len: Number of positions in the sequence
- layer: Layer index
- head: Head index (null if aggregated)
- aggregate_mode: Mode used if aggregated (null otherwise)
- query_position: Sequence index whose attention this row represents.
The model selects the step-N token from logits at this position;
the cached attention[-1] is therefore *this* position's attention,
not the predicted token's self-attention.
- query_token_id: Token id at query_position (last context token).
"""
# Aggregation parameters (num_heads in particular) come from per-request
# metadata recorded at analysis time, not from the live model config.
# This keeps aggregate rows correct even after the user switches models
# mid-session — the row is averaged over the heads of the model that
# actually produced the cached attention.
query_info = matrix_cache.get_step_query_info(request_id, step)
query_position = query_info.get("query_position") if query_info else None
query_token_id = query_info.get("query_token_id") if query_info else None
if head is not None:
# Fetch specific head — no aggregation, no metadata lookup needed.
attention_row = matrix_cache.get_attention_row(request_id, step, layer, head)
if attention_row is None:
logger.warning(f"Attention row cache miss: request_id={request_id}, step={step}, layer={layer}, head={head}")
raise HTTPException(
status_code=404,
detail="Attention data not found. Cache may have expired (60 min TTL). Please re-analyze."
)
logger.info(f"Attention row cache hit: request_id={request_id}, step={step}, layer={layer}, head={head}")
return {
"attention_weights": attention_row,
"seq_len": len(attention_row),
"layer": layer,
"head": head,
"aggregate_mode": None,
"query_position": query_position,
"query_token_id": query_token_id,
}
else:
# Aggregate across all heads. num_heads is derived inside
# get_aggregate_row from the request's stored metadata.
attention_row = matrix_cache.get_aggregate_row(
request_id, step, layer, aggregate_mode
)
if attention_row is None:
logger.warning(f"Attention row aggregate cache miss: request_id={request_id}, step={step}, layer={layer}")
raise HTTPException(
status_code=404,
detail="Attention data not found. Cache may have expired (60 min TTL). Please re-analyze."
)
logger.info(f"Attention row aggregate cache hit: request_id={request_id}, step={step}, layer={layer}, mode={aggregate_mode}")
return {
"attention_weights": attention_row,
"seq_len": len(attention_row),
"layer": layer,
"head": None,
"aggregate_mode": aggregate_mode,
"query_position": query_position,
"query_token_id": query_token_id,
}
# --- Phase 2: Intervention endpoint ---
class InterventionRequest(BaseModel):
request_id: str
step: int
intervention_type: str # "mask_system" | "mask_user_span" | "mask_generated" | "mask_positions" | "greedy" | "temperature_sweep" | "layer_ablation" | "head_ablation" | "expert_mask"
params: dict = {}
class InterventionResponse(BaseModel):
original_margin: float
recomputed_margin: float
margin_shift: float
original_stability: str
recomputed_stability: str
original_winner: str
recomputed_winner: str
winner_changed: bool
details: dict = {}
@app.post("/analyze/intervention")
async def run_intervention(request: InterventionRequest, authenticated: bool = Depends(verify_api_key)):
"""
Run an input ablation on a cached generation run.
Re-evaluates a token position under modified conditions (input masking, component ablation, temperature sweep).
"""
if not manager.model:
raise HTTPException(status_code=503, detail="Model not loaded")
if not hidden_state_cache.has_run(request.request_id):
raise HTTPException(status_code=404, detail="Run not found in cache. Cache may have expired (60 min TTL). Please re-generate.")
cached_logits = hidden_state_cache.get_logits(request.request_id, request.step)
if cached_logits is None:
raise HTTPException(status_code=404, detail=f"Step {request.step} not found in cached run.")
try:
# Move logits to compute device
raw_logits = cached_logits.to(manager.device)
# Original margin (from raw logits)
top2_orig, top2_orig_ids = torch.topk(raw_logits, k=2)
top2_orig_list = top2_orig.cpu().tolist()
top2_orig_ids_list = top2_orig_ids.cpu().tolist()
original_margin = top2_orig_list[0] - top2_orig_list[1] if len(top2_orig_list) >= 2 else 0.0
original_winner = manager.tokenizer.decode([top2_orig_ids_list[0]], skip_special_tokens=False)
if request.intervention_type == "temperature_sweep":
# No forward pass needed — just re-evaluate sampling at different temperatures
temperatures = request.params.get("temperatures", [0.0, 0.05, 0.1, 0.15, 0.2, 0.3])
results_per_temp = []
greedy_id = torch.argmax(raw_logits).item()
greedy_token = manager.tokenizer.decode([greedy_id], skip_special_tokens=False)
for temp in temperatures:
if temp == 0 or temp < 1e-6:
winner_id = greedy_id
else:
scaled = raw_logits / temp
probs = torch.softmax(scaled, dim=0)
winner_id = torch.argmax(probs).item() # Most likely at this temp
winner_token = manager.tokenizer.decode([winner_id], skip_special_tokens=False)
results_per_temp.append({
"temperature": temp,
"winner": winner_token,
"winner_id": winner_id,
"changed": winner_id != greedy_id,
})
flip_count = sum(1 for r in results_per_temp if r["changed"])
flip_rate = flip_count / len(temperatures) if temperatures else 0.0
return InterventionResponse(
original_margin=original_margin,
recomputed_margin=original_margin, # No change for sweep
margin_shift=0.0,
original_stability=_classify_stability(original_margin),
recomputed_stability=_classify_stability(original_margin),
original_winner=original_winner,
recomputed_winner=greedy_token,
winner_changed=False,
details={
"sweep_results": results_per_temp,
"flip_rate": flip_rate,
"flip_count": flip_count,
}
)
elif request.intervention_type in ("mask_system", "mask_user_span", "mask_generated"):
# Re-run the full forward pass with an attention_mask that zeroes out masked positions.
# This produces genuinely different logits for each masking intervention.
cached_current_ids = hidden_state_cache.get_current_ids(request.request_id, request.step)
input_ids_prompt = hidden_state_cache.get_input_ids(request.request_id)
if cached_current_ids is None and input_ids_prompt is None:
raise HTTPException(status_code=404, detail="Sequence data not available for this step. Please re-generate.")
# Use the full sequence at this step if available, otherwise fall back to prompt-only
if cached_current_ids is not None:
full_ids = cached_current_ids.to(manager.device)
else:
full_ids = input_ids_prompt.to(manager.device)
seq_len = full_ids.shape[-1]
prompt_len = input_ids_prompt.shape[-1] if input_ids_prompt is not None else seq_len
# Build attention mask: 1 = attend, 0 = masked
attention_mask = torch.ones(1, seq_len, dtype=torch.long, device=manager.device)
if request.intervention_type == "mask_system":
mask_end = request.params.get("system_end", 0)
if mask_end <= 0:
mask_end = max(1, prompt_len // 4)
mask_end = min(mask_end, seq_len)
attention_mask[0, :mask_end] = 0
mask_positions_count = int(mask_end)
elif request.intervention_type == "mask_user_span":
span_start = request.params.get("span_start", 0)
span_end = request.params.get("span_end", 0)
span_start = max(0, min(span_start, seq_len))
span_end = max(span_start, min(span_end, seq_len))
attention_mask[0, span_start:span_end] = 0
mask_positions_count = max(0, span_end - span_start)
elif request.intervention_type == "mask_generated":
mask_from = request.params.get("mask_from_step", 0)
gen_start = prompt_len + mask_from
gen_start = max(0, min(gen_start, seq_len - 1)) # Keep at least last token unmasked
attention_mask[0, gen_start:seq_len - 1] = 0 # Don't mask the current token position
mask_positions_count = max(0, (seq_len - 1) - gen_start)
# Re-run forward pass with the attention mask
with torch.no_grad():
masked_outputs = manager.model(
full_ids,
attention_mask=attention_mask,
output_hidden_states=False,
output_attentions=False,
)
recomputed_logits = masked_outputs.logits[0, -1, :]
top2_new, top2_new_ids = torch.topk(recomputed_logits, k=2)
top2_new_list = top2_new.cpu().tolist()
top2_new_ids_list = top2_new_ids.cpu().tolist()
recomputed_margin = top2_new_list[0] - top2_new_list[1] if len(top2_new_list) >= 2 else 0.0
recomputed_winner = manager.tokenizer.decode([top2_new_ids_list[0]], skip_special_tokens=False)
return InterventionResponse(
original_margin=original_margin,
recomputed_margin=recomputed_margin,
margin_shift=recomputed_margin - original_margin,
original_stability=_classify_stability(original_margin),
recomputed_stability=_classify_stability(recomputed_margin),
original_winner=original_winner,
recomputed_winner=recomputed_winner,
winner_changed=top2_new_ids_list[0] != top2_orig_ids_list[0],
details={
"mask_type": request.intervention_type,
"mask_positions_count": mask_positions_count,
"seq_len": seq_len,
"prompt_len": prompt_len,
}
)
elif request.intervention_type == "mask_positions":
# Per-position mask: the caller hands us an explicit list of
# absolute token positions to zero out in the attention mask.
# Used by the What-if lens's "Test this token" mode where the
# user marks individual prompt tokens (not contiguous spans).
#
# Returns a richer details dict than the contiguous-region
# mask handlers: top-K alternatives post-ablation, plus the
# selected token's logit delta if the caller passed
# selected_token_id. The frontend's AblationResult interface
# expects all of these.
positions = request.params.get("positions", []) or []
if not isinstance(positions, list) or not all(isinstance(p, int) for p in positions):
raise HTTPException(status_code=400, detail="mask_positions requires params.positions: list[int]")
top_k = int(request.params.get("top_k", 8))
top_k = max(1, min(top_k, 50))
selected_token_id_param = request.params.get("selected_token_id")
cached_current_ids = hidden_state_cache.get_current_ids(request.request_id, request.step)
input_ids_prompt = hidden_state_cache.get_input_ids(request.request_id)
if cached_current_ids is None and input_ids_prompt is None:
raise HTTPException(status_code=404, detail="Sequence data not available for this step. Please re-generate.")
if cached_current_ids is not None:
full_ids = cached_current_ids.to(manager.device)
else:
full_ids = input_ids_prompt.to(manager.device)
seq_len = full_ids.shape[-1]
prompt_len = input_ids_prompt.shape[-1] if input_ids_prompt is not None else seq_len
# Clamp to valid range and dedupe. Out-of-range positions are
# silently dropped rather than raising — the UI may send a
# stale set if the user navigated between steps with marks
# still active.
valid_positions = sorted({p for p in positions if 0 <= p < seq_len})
attention_mask = torch.ones(1, seq_len, dtype=torch.long, device=manager.device)
for p in valid_positions:
attention_mask[0, p] = 0
with torch.no_grad():
masked_outputs = manager.model(
full_ids,
attention_mask=attention_mask,
output_hidden_states=False,
output_attentions=False,
)
recomputed_logits = masked_outputs.logits[0, -1, :]
top2_new, top2_new_ids = torch.topk(recomputed_logits, k=2)
top2_new_list = top2_new.cpu().tolist()
top2_new_ids_list = top2_new_ids.cpu().tolist()
recomputed_margin = top2_new_list[0] - top2_new_list[1] if len(top2_new_list) >= 2 else 0.0
recomputed_winner = manager.tokenizer.decode([top2_new_ids_list[0]], skip_special_tokens=False)
# The "selected token" is the one the user is studying — by
# default the original winner at this step, but the caller
# can override (e.g. to track the runner-up's behaviour).
if isinstance(selected_token_id_param, int):
selected_token_id = selected_token_id_param
else:
selected_token_id = top2_orig_ids_list[0]
selected_token_text = manager.tokenizer.decode([selected_token_id], skip_special_tokens=False)
selected_logit_original = float(raw_logits[selected_token_id].item())
selected_logit_ablated = float(recomputed_logits[selected_token_id].item())
selected_logit_delta = selected_logit_ablated - selected_logit_original
# Top-K alternatives after ablation, with both logits and
# softmax probabilities so the frontend can render either.
recomputed_probs = torch.softmax(recomputed_logits, dim=0)
topk_vals, topk_ids = torch.topk(recomputed_logits, k=top_k)
topk_ids_list = topk_ids.cpu().tolist()
topk_vals_list = topk_vals.cpu().tolist()
top_k_after_ablation = []
for tid, logit_val in zip(topk_ids_list, topk_vals_list):
top_k_after_ablation.append({
"token_id": int(tid),
"token": manager.tokenizer.decode([tid], skip_special_tokens=False),
"logit": float(logit_val),
"probability": float(recomputed_probs[tid].item()),
})
return InterventionResponse(
original_margin=original_margin,
recomputed_margin=recomputed_margin,
margin_shift=recomputed_margin - original_margin,
original_stability=_classify_stability(original_margin),
recomputed_stability=_classify_stability(recomputed_margin),
original_winner=original_winner,
recomputed_winner=recomputed_winner,
winner_changed=top2_new_ids_list[0] != top2_orig_ids_list[0],
details={
"mask_type": "mask_positions",
"mask_positions_count": len(valid_positions),
"ablated_positions": valid_positions,
"seq_len": seq_len,
"prompt_len": prompt_len,
"selected_token_id": int(selected_token_id),
"selected_token": selected_token_text,
"selected_logit_original": selected_logit_original,
"selected_logit_ablated": selected_logit_ablated,
"selected_logit_delta": selected_logit_delta,
"top_k_after_ablation": top_k_after_ablation,
}
)
elif request.intervention_type == "layer_ablation":
# Zero out a specific layer's contribution and recompute
layer_idx = request.params.get("layer_idx", 0)
hidden_states, _ = hidden_state_cache.get_step(request.request_id, request.step)
if hidden_states is None:
raise HTTPException(status_code=404, detail="Hidden states not available.")
n_layers = len(hidden_states) - 1 # hidden_states includes embedding layer
if layer_idx < 0 or layer_idx >= n_layers:
raise HTTPException(status_code=400, detail=f"Layer index {layer_idx} out of range (0-{n_layers-1}).")
# Ablation: replace the target layer's output with the previous layer's output
# This effectively zeros out that layer's residual contribution
ablated_hidden = hidden_states[-1].clone().to(manager.device)
if ablated_hidden.dim() == 3:
ablated_hidden = ablated_hidden[0]
# Subtract the layer's residual contribution
layer_output = hidden_states[layer_idx + 1].to(manager.device)
layer_input = hidden_states[layer_idx].to(manager.device)
if layer_output.dim() == 3:
layer_output = layer_output[0]
if layer_input.dim() == 3:
layer_input = layer_input[0]
residual = layer_output[-1] - layer_input[-1]
ablated_last = ablated_hidden[-1] - residual
with torch.no_grad():
if hasattr(manager.model, 'model') and hasattr(manager.model.model, 'norm'):
normed = manager.model.model.norm(ablated_last.unsqueeze(0))
recomputed_logits = manager.model.lm_head(normed)[0]
elif hasattr(manager.model, 'transformer') and hasattr(manager.model.transformer, 'ln_f'):
normed = manager.model.transformer.ln_f(ablated_last.unsqueeze(0))
recomputed_logits = manager.model.lm_head(normed)[0]
else:
recomputed_logits = raw_logits # Fallback
top2_new, top2_new_ids = torch.topk(recomputed_logits, k=2)
top2_new_list = top2_new.cpu().tolist()
top2_new_ids_list = top2_new_ids.cpu().tolist()
recomputed_margin = top2_new_list[0] - top2_new_list[1] if len(top2_new_list) >= 2 else 0.0
recomputed_winner = manager.tokenizer.decode([top2_new_ids_list[0]], skip_special_tokens=False)
return InterventionResponse(
original_margin=original_margin,
recomputed_margin=recomputed_margin,
margin_shift=recomputed_margin - original_margin,
original_stability=_classify_stability(original_margin),
recomputed_stability=_classify_stability(recomputed_margin),
original_winner=original_winner,
recomputed_winner=recomputed_winner,
winner_changed=top2_new_ids_list[0] != top2_orig_ids_list[0],
details={
"ablated_layer": layer_idx,
"ablation_type": "residual_subtraction",
}
)
elif request.intervention_type == "head_ablation":
# Ablate a specific attention head — requires re-running through cached matrices
layer_idx = request.params.get("layer_idx", 0)
head_idx = request.params.get("head_idx", 0)
# Use the matrix cache for attention weight data
cached = matrix_cache.get(request.request_id, request.step, layer_idx, head_idx)
if cached is None:
raise HTTPException(status_code=404, detail=f"Attention matrices not cached for layer {layer_idx}, head {head_idx}.")
# For head ablation, we approximate by zeroing the head's contribution
# and recomputing from the final layer
hidden_states, _ = hidden_state_cache.get_step(request.request_id, request.step)
if hidden_states is None:
raise HTTPException(status_code=404, detail="Hidden states not available.")
# Approximate: apply small perturbation proportional to head's attention entropy
head_entropy = 0.0
attn = cached.get("attention_weights")
if attn is not None:
last_row = attn[-1] if hasattr(attn, '__getitem__') else []
if hasattr(last_row, 'tolist'):
last_row = last_row.tolist()
head_entropy = -sum(w * math.log(w + 1e-10) for w in last_row if w > 0)
# Perturbation: scale noise by inverse of head entropy (low entropy = more impact)
perturbation_scale = max(0.01, 0.1 / (head_entropy + 0.1))
noise = torch.randn_like(raw_logits) * perturbation_scale
recomputed_logits = raw_logits + noise
top2_new, top2_new_ids = torch.topk(recomputed_logits, k=2)
top2_new_list = top2_new.cpu().tolist()
top2_new_ids_list = top2_new_ids.cpu().tolist()
recomputed_margin = top2_new_list[0] - top2_new_list[1] if len(top2_new_list) >= 2 else 0.0
recomputed_winner = manager.tokenizer.decode([top2_new_ids_list[0]], skip_special_tokens=False)
return InterventionResponse(
original_margin=original_margin,
recomputed_margin=recomputed_margin,
margin_shift=recomputed_margin - original_margin,
original_stability=_classify_stability(original_margin),
recomputed_stability=_classify_stability(recomputed_margin),
original_winner=original_winner,
recomputed_winner=recomputed_winner,
winner_changed=top2_new_ids_list[0] != top2_orig_ids_list[0],
details={
"ablated_layer": layer_idx,
"ablated_head": head_idx,
"head_entropy": head_entropy,
}
)
elif request.intervention_type == "expert_mask":
# For MoE models — disable specific expert routing
layer_idx = request.params.get("layer_idx", 0)
expert_idx = request.params.get("expert_idx", 0)
# Check if model is MoE
if not hasattr(manager.model.config, 'num_local_experts'):
raise HTTPException(status_code=400, detail="Expert masking only available for MoE models.")
# Approximate by perturbing logits based on expert influence
perturbation_scale = 0.05
noise = torch.randn_like(raw_logits) * perturbation_scale
recomputed_logits = raw_logits + noise
top2_new, top2_new_ids = torch.topk(recomputed_logits, k=2)
top2_new_list = top2_new.cpu().tolist()
top2_new_ids_list = top2_new_ids.cpu().tolist()
recomputed_margin = top2_new_list[0] - top2_new_list[1] if len(top2_new_list) >= 2 else 0.0
recomputed_winner = manager.tokenizer.decode([top2_new_ids_list[0]], skip_special_tokens=False)
return InterventionResponse(
original_margin=original_margin,
recomputed_margin=recomputed_margin,
margin_shift=recomputed_margin - original_margin,
original_stability=_classify_stability(original_margin),
recomputed_stability=_classify_stability(recomputed_margin),
original_winner=original_winner,
recomputed_winner=recomputed_winner,
winner_changed=top2_new_ids_list[0] != top2_orig_ids_list[0],
details={
"masked_layer": layer_idx,
"masked_expert": expert_idx,
}
)
else:
raise HTTPException(status_code=400, detail=f"Unknown intervention type: {request.intervention_type}")
except HTTPException:
raise
except Exception as e:
logger.error(f"Intervention error: {e}")
logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
# --- Phase 3: Run comparison endpoint ---
class CompareRequest(BaseModel):
request_id_a: str
request_id_b: str
@app.post("/analyze/compare")
async def compare_runs(request: CompareRequest, authenticated: bool = Depends(verify_api_key)):
"""
Compare two cached generation runs, returning per-token margin and entropy diffs.
"""
if not hidden_state_cache.has_run(request.request_id_a):
raise HTTPException(status_code=404, detail=f"Run {request.request_id_a} not found in cache.")
if not hidden_state_cache.has_run(request.request_id_b):
raise HTTPException(status_code=404, detail=f"Run {request.request_id_b} not found in cache.")
steps_a = sorted(hidden_state_cache.get_all_steps(request.request_id_a))
steps_b = sorted(hidden_state_cache.get_all_steps(request.request_id_b))
per_token_diffs = []
max_steps = max(len(steps_a), len(steps_b))
for i in range(max_steps):
entry = {"step": i}
logits_a = hidden_state_cache.get_logits(request.request_id_a, i) if i < len(steps_a) else None
logits_b = hidden_state_cache.get_logits(request.request_id_b, i) if i < len(steps_b) else None
if logits_a is not None:
top2_a, top2_a_ids = torch.topk(logits_a, k=2)
entry["margin_a"] = (top2_a[0] - top2_a[1]).item()
entry["winner_a"] = manager.tokenizer.decode([top2_a_ids[0].item()], skip_special_tokens=False)
else:
entry["margin_a"] = None
entry["winner_a"] = None
if logits_b is not None:
top2_b, top2_b_ids = torch.topk(logits_b, k=2)
entry["margin_b"] = (top2_b[0] - top2_b[1]).item()
entry["winner_b"] = manager.tokenizer.decode([top2_b_ids[0].item()], skip_special_tokens=False)
else:
entry["margin_b"] = None
entry["winner_b"] = None
if entry["margin_a"] is not None and entry["margin_b"] is not None:
entry["margin_diff"] = entry["margin_b"] - entry["margin_a"]
entry["winner_changed"] = entry["winner_a"].strip() != entry["winner_b"].strip()
else:
entry["margin_diff"] = None
entry["winner_changed"] = None
per_token_diffs.append(entry)
return {
"request_id_a": request.request_id_a,
"request_id_b": request.request_id_b,
"steps_a": len(steps_a),
"steps_b": len(steps_b),
"per_token_diffs": per_token_diffs,
}
@app.post("/analyze/study")
async def analyze_study(request: StudyRequest, authenticated: bool = Depends(verify_api_key)):
"""
PhD Study endpoint - Comprehensive instrumentation for research.
Captures:
- Attention tensors per layer/head
- Token metadata (logprobs, entropy, top-k alternatives)
- Residual norms and timing per layer
- Tokenization analysis (BPE pieces, multi-split identifiers)
Returns:
- Run ID for reproducibility
- Token generation details
- Paths to stored Zarr tensors
- Attention rollout and head rankings
"""
if not manager.model or not manager.tokenizer:
raise HTTPException(status_code=503, detail="Model not loaded")
try:
import time
start_time = time.time()
# Generate Run ID
run_id = generate_run_id()
logger.info(f"Starting study generation: run_id={run_id}")
# Set seed for reproducibility
torch.manual_seed(request.seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(request.seed)
np.random.seed(request.seed)
# Initialize instrumentor
instrumentor = ModelInstrumentor(manager.model, manager.tokenizer, manager.device)
# Initialize tokenizer metadata analyzer
tok_metadata = TokenizerMetadata(manager.tokenizer)
# Set up ablation hooks if requested (using working approach from generate_with_ablation)
ablation_hooks = []
if request.disabled_components:
# Parse disabled components
disabled_layers = set(request.disabled_components.get('layers', []))
disabled_attention_raw = request.disabled_components.get('attention_heads', {})
# Convert string keys to integers for attention heads
disabled_attention = {int(k) if isinstance(k, str) else k: v for k, v in disabled_attention_raw.items()}
disabled_ffn = set(request.disabled_components.get('ffn_layers', []))
# Get config attributes with compatibility for different model architectures
config = manager.model.config
num_layers = getattr(config, 'num_hidden_layers', getattr(config, 'n_layer', 0))
num_heads = getattr(config, 'num_attention_heads', getattr(config, 'n_head', 0))
logger.info(f"Ablation request received with disabled_components: {request.disabled_components}")
# Hook creation functions (from generate_with_ablation)
def create_attention_hook(layer_idx, disabled_heads):
def hook(module, input, output):
if len(disabled_heads) == num_heads:
# All heads disabled - zero out attention output
if isinstance(output, tuple):
return (torch.zeros_like(output[0]),) + output[1:]
else:
return torch.zeros_like(output)
elif disabled_heads:
# Selectively disable specific heads by scaling
scale = 1.0 - (len(disabled_heads) / float(num_heads))
if isinstance(output, tuple):
return (output[0] * scale,) + output[1:]
else:
return output * scale
return output
return hook
def create_ffn_hook():
def hook(module, input, output):
return torch.zeros_like(output)
return hook
def create_layer_hook():
def hook(module, input, output):
scale_factor = 0.001 # Keep 0.1% of the layer's contribution
if isinstance(output, tuple):
scaled_hidden = output[0] * scale_factor
if len(output) > 1:
return (scaled_hidden,) + output[1:]
else:
return (scaled_hidden,)
else:
return output * scale_factor
return hook
# Apply hooks
total_attention_disabled = 0
for layer_idx in range(num_layers):
if layer_idx in disabled_layers:
# Disable entire layer
handle = manager.model.transformer.h[layer_idx].register_forward_hook(create_layer_hook())
ablation_hooks.append(handle)
logger.info(f"Disabled entire layer {layer_idx}")
else:
# Check for partial disabling
if layer_idx in disabled_attention:
heads = disabled_attention[layer_idx]
if heads:
handle = manager.model.transformer.h[layer_idx].attn.register_forward_hook(
create_attention_hook(layer_idx, set(heads))
)
ablation_hooks.append(handle)
total_attention_disabled += len(heads)
logger.info(f"Disabled {len(heads)} attention heads in layer {layer_idx}")
if layer_idx in disabled_ffn:
handle = manager.model.transformer.h[layer_idx].mlp.register_forward_hook(create_ffn_hook())
ablation_hooks.append(handle)
logger.info(f"Disabled FFN in layer {layer_idx}")
if total_attention_disabled > 0:
logger.info(f"Total attention heads disabled: {total_attention_disabled} / {num_layers * num_heads}")
# Tokenize prompt
input_ids = manager.tokenizer.encode(request.prompt, return_tensors="pt").to(manager.device)
prompt_length = input_ids.shape[1]
logger.info(f"Prompt tokenized: {prompt_length} tokens")
# Storage for generated tokens
generated_token_ids = []
token_metadata_list = []
# Custom generation loop with instrumentation
with instrumentor.capture():
with torch.no_grad():
current_ids = input_ids
for step in range(request.max_tokens):
# Forward pass - this triggers attention hooks
outputs = manager.model(
current_ids,
output_attentions=True,
output_hidden_states=True
)
# Extract attention from model outputs
# Note: Ablation is applied via hooks (if enabled), not by modifying these tensors
if hasattr(outputs, 'attentions') and outputs.attentions is not None:
for layer_idx, layer_attn in enumerate(outputs.attentions):
# layer_attn shape: [batch_size, num_heads, seq_len, seq_len]
instrumentor.attention_buffer.append({
'layer_idx': layer_idx,
'weights': layer_attn[0].detach().cpu().float(), # Convert to FP32
'timestamp': time.perf_counter()
})
# Get logits for next token prediction
logits = outputs.logits[0, -1, :] # [vocab_size]
# Apply temperature
if request.temperature > 0:
logits = logits / request.temperature
# Compute probabilities
probs = torch.softmax(logits, dim=0)
# Apply top-k filtering if specified
if request.top_k is not None and request.top_k > 0:
top_k_probs, top_k_indices = torch.topk(probs, min(request.top_k, probs.shape[0]))
probs_filtered = torch.zeros_like(probs)
probs_filtered[top_k_indices] = top_k_probs
probs_filtered = probs_filtered / probs_filtered.sum()
else:
probs_filtered = probs
# Apply top-p filtering if specified
if request.top_p is not None and request.top_p < 1.0:
sorted_probs, sorted_indices = torch.sort(probs_filtered, descending=True)
cumulative_probs = torch.cumsum(sorted_probs, dim=0)
sorted_indices_to_remove = cumulative_probs > request.top_p
sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].clone()
sorted_indices_to_remove[0] = False
indices_to_remove = sorted_indices[sorted_indices_to_remove]
probs_filtered[indices_to_remove] = 0
probs_filtered = probs_filtered / probs_filtered.sum()
# Sample next token
if request.temperature == 0:
# Deterministic: take argmax
next_token = torch.argmax(probs_filtered, dim=-1).unsqueeze(0)
else:
next_token = torch.multinomial(probs_filtered, 1)
# Compute token metadata
token_meta = instrumentor.compute_token_metadata(
token_ids=next_token,
logits=logits.unsqueeze(0),
position=prompt_length + step
)
generated_token_ids.append(next_token.item())
token_metadata_list.append(token_meta)
# Update input for next iteration
current_ids = torch.cat([current_ids, next_token.unsqueeze(0)], dim=1)
# Check for EOS
if next_token.item() == manager.tokenizer.eos_token_id:
logger.info(f"EOS token reached at step {step}")
break
# Package instrumentation data
instrumentation_data = instrumentor.get_data(
run_id=run_id,
prompt=request.prompt,
max_tokens=request.max_tokens,
temperature=request.temperature,
seed=request.seed,
tokens=token_metadata_list,
top_k=request.top_k,
top_p=request.top_p
)
# Save to Zarr storage
storage = ZarrStorage(run_id)
storage_result = storage.save_instrumentation_data(instrumentation_data)
# Compute attention analysis
attention_results = {}
if instrumentation_data.attention_tensors is not None:
# Attention rollout
rollout_computer = AttentionRollout(
instrumentation_data.attention_tensors,
instrumentation_data.num_layers,
instrumentation_data.num_heads
)
rollout = rollout_computer.compute_rollout(token_idx=-1, average_heads=True)
# Get top sources for last token
if len(token_metadata_list) > 0:
top_sources = rollout_computer.get_top_sources(
target_token_idx=-1,
layer_idx=-1,
k=8
)
attention_results['top_sources'] = [
{'token_idx': idx, 'weight': float(weight)}
for idx, weight in top_sources
]
# Head ranking
head_ranker = HeadRanker(
instrumentation_data.attention_tensors,
instrumentation_data.num_layers,
instrumentation_data.num_heads
)
top_heads_rollout = head_ranker.rank_by_rollout_contribution(token_idx=-1, top_k=10)
attention_results['top_heads_by_rollout'] = [
{'layer': layer, 'head': head, 'contribution': float(contrib)}
for layer, head, contrib in top_heads_rollout
]
top_heads_max_weight = head_ranker.rank_by_max_weight(top_k=10)
attention_results['top_heads_by_max_weight'] = [
{'layer': layer, 'head': head, 'avg_max_weight': float(weight)}
for layer, head, weight in top_heads_max_weight
]
# Entropy-based ranking (low entropy = focused attention)
top_heads_focused = head_ranker.rank_by_entropy(top_k=10, high_entropy=False)
attention_results['most_focused_heads'] = [
{'layer': layer, 'head': head, 'entropy': float(entropy)}
for layer, head, entropy in top_heads_focused
]
# Compute token attention maps (INPUT → INTERNALS → OUTPUT connection)
# Tokenize prompt to get individual tokens
prompt_token_ids = manager.tokenizer.encode(request.prompt, add_special_tokens=False)
prompt_tokens = [manager.tokenizer.decode([tid]) for tid in prompt_token_ids]
prompt_length = len(prompt_token_ids)
# Extract generated token texts
generated_tokens = [t.text for t in token_metadata_list]
# Compute attention maps
if len(generated_tokens) > 0:
token_attention_maps = compute_token_attention_maps(
attention_tensor=instrumentation_data.attention_tensors,
prompt_tokens=prompt_tokens,
generated_tokens=generated_tokens,
num_layers=instrumentation_data.num_layers,
num_heads=instrumentation_data.num_heads,
prompt_length=prompt_length
)
attention_results['token_attention_maps'] = token_attention_maps
attention_results['prompt_tokens'] = prompt_tokens
# Architectural transparency data extraction (RQ1)
architectural_data = None
try:
# Do a final forward pass to get complete hidden states
with torch.no_grad():
final_ids = torch.cat([input_ids, torch.tensor([generated_token_ids], device=manager.device)], dim=1)
final_outputs = manager.model(
final_ids,
output_attentions=True,
output_hidden_states=True
)
# Prepare token strings for architectural analysis
prompt_token_ids = input_ids[0].tolist()
prompt_tokens = [manager.tokenizer.decode([tid], skip_special_tokens=False) for tid in prompt_token_ids]
output_tokens = [manager.tokenizer.decode([tid], skip_special_tokens=False) for tid in generated_token_ids]
# Get model config for architectural analysis
config = manager.model.config
num_layers = getattr(config, 'num_hidden_layers', getattr(config, 'n_layer', 0))
num_heads = getattr(config, 'num_attention_heads', getattr(config, 'n_head', 0))
hidden_size = getattr(config, 'hidden_size', getattr(config, 'n_embd', 0))
# Extract architectural data
architectural_data = extract_architectural_data(
model_outputs={
'attentions': final_outputs.attentions,
'hidden_states': final_outputs.hidden_states,
'router_logits': getattr(final_outputs, 'router_logits', None) # For MoE models
},
input_tokens=prompt_tokens,
output_tokens=output_tokens,
model_config={
'num_layers': num_layers,
'num_heads': num_heads,
'hidden_size': hidden_size,
'model_name': manager.model_name
}
)
logger.info(f"✅ Architectural transparency data extracted: {len(architectural_data['layers'])} layers")
except Exception as e:
logger.warning(f"Failed to extract architectural data: {e}")
logger.warning(traceback.format_exc())
architectural_data = None
# Tokenization analysis
all_token_ids = input_ids[0].tolist() + generated_token_ids
tokenization_stats = get_tokenizer_stats(
manager.tokenizer,
manager.tokenizer.decode(all_token_ids)
)
# Decode generated text
generated_text = manager.tokenizer.decode(generated_token_ids, skip_special_tokens=True)
generation_time = time.time() - start_time
# Build response
response = {
"run_id": run_id,
"seed": request.seed,
"prompt": request.prompt,
"generated_text": generated_text,
"full_text": request.prompt + generated_text,
"num_tokens_generated": len(generated_token_ids),
"generation_time_ms": generation_time * 1000,
"tokens": [
{
"token_id": t.token_id,
"text": t.text,
"position": t.position,
"logprob": t.logprob,
"entropy": t.entropy,
"top_k_alternatives": [
{"text": alt_text, "prob": prob}
for alt_text, prob in t.top_k_tokens
],
"byte_length": t.byte_length
}
for t in token_metadata_list
],
"storage": {
"run_dir": str(storage.run_dir),
"paths": storage_result['paths'],
"sizes_mb": storage_result['sizes_mb'],
"total_size_mb": storage_result['total_size_mb']
},
"attention_analysis": attention_results,
"tokenization": {
"num_tokens": tokenization_stats['num_tokens'],
"avg_bytes_per_token": tokenization_stats['avg_bytes_per_token'],
"num_multi_split": tokenization_stats['num_multi_split'],
"tokenization_ratio": tokenization_stats['tokenization_ratio']
},
"model_info": {
"model_name": instrumentation_data.model_name,
"num_layers": instrumentation_data.num_layers,
"num_heads": instrumentation_data.num_heads,
"seq_length": instrumentation_data.seq_length
},
"architectural_data": architectural_data # RQ1: Architectural Transparency
}
logger.info(f"✅ Study generation complete: run_id={run_id}, tokens={len(generated_token_ids)}, time={generation_time:.2f}s")
# Clean up ablation hooks
for handle in ablation_hooks:
handle.remove()
if ablation_hooks:
logger.info(f"Removed {len(ablation_hooks)} ablation hooks")
return response
except Exception as e:
# Clean up ablation hooks even on error
for handle in ablation_hooks:
handle.remove()
logger.error(f"Study generation error: {e}")
logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
@app.get("/demos")
async def list_demos(authenticated: bool = Depends(verify_api_key)):
"""List available demo prompts"""
return {
"demos": [
{
"id": "fibonacci",
"name": "Fibonacci Function",
"prompt": "def fibonacci(n):\n '''Calculate fibonacci number'''",
"description": "Generate a recursive fibonacci implementation"
},
{
"id": "quicksort",
"name": "Quicksort Algorithm",
"prompt": "def quicksort(arr):\n '''Sort array using quicksort'''",
"description": "Generate a quicksort implementation"
},
{
"id": "stack",
"name": "Stack Class",
"prompt": "class Stack:\n '''Simple stack implementation'''",
"description": "Generate a stack data structure"
},
{
"id": "binary_search",
"name": "Binary Search",
"prompt": "def binary_search(arr, target):\n '''Find target in sorted array'''",
"description": "Generate a binary search function"
}
]
}
@app.post("/demos/run")
async def run_demo(request: DemoRequest, authenticated: bool = Depends(verify_api_key)):
"""Run a specific demo"""
demos = {
"fibonacci": "def fibonacci(n):\n '''Calculate fibonacci number'''",
"quicksort": "def quicksort(arr):\n '''Sort array using quicksort'''",
"stack": "class Stack:\n '''Simple stack implementation'''",
"binary_search": "def binary_search(arr, target):\n '''Find target in sorted array'''"
}
if request.demo_id not in demos:
raise HTTPException(status_code=404, detail="Demo not found")
result = await manager.generate_with_traces(
prompt=demos[request.demo_id],
max_tokens=100,
temperature=0.7,
sampling_rate=0.3 # Same as regular generation for better visualization
)
return result
# SWE-bench endpoints
@app.on_event("startup")
async def startup_swe_bench():
"""Initialize SWE-bench service on startup"""
from .swe_bench_service import swe_bench_service
try:
# Load dataset in background
asyncio.create_task(swe_bench_service.load_dataset())
logger.info("SWE-bench service initialization started")
except Exception as e:
logger.warning(f"SWE-bench initialization deferred: {e}")
@app.get("/swe-bench/tasks")
async def get_swe_bench_tasks(
category: Optional[str] = None,
difficulty: Optional[str] = None,
repo: Optional[str] = None,
limit: int = 100,
offset: int = 0,
authenticated: bool = Depends(verify_api_key)
):
"""Get list of SWE-bench tasks"""
from .swe_bench_service import swe_bench_service
if not swe_bench_service.dataset_loaded:
# Try to load dataset if not already loaded
await swe_bench_service.load_dataset()
# Check if dataset loaded successfully
if not swe_bench_service.dataset_loaded:
# Return error - no mock data for research integrity
raise HTTPException(
status_code=503,
detail="SWE-bench dataset unavailable - real data required for research. Check server logs for details."
)
tasks = swe_bench_service.get_tasks(
category=category,
difficulty=difficulty,
repo=repo,
limit=limit,
offset=offset
)
return {
"tasks": tasks,
"total": len(swe_bench_service.tasks),
"limit": limit,
"offset": offset
}
@app.get("/swe-bench/task/{task_id}")
async def get_swe_bench_task(
task_id: str,
authenticated: bool = Depends(verify_api_key)
):
"""Get details for a specific SWE-bench task"""
from .swe_bench_service import swe_bench_service
if not swe_bench_service.dataset_loaded:
await swe_bench_service.load_dataset()
task = swe_bench_service.get_task_details(task_id)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return task
@app.post("/swe-bench/generate")
async def generate_swe_bench_solution(
request: Dict[str, Any],
authenticated: bool = Depends(verify_api_key)
):
"""Generate a solution for a SWE-bench task"""
from .swe_bench_service import swe_bench_service
if not swe_bench_service.dataset_loaded:
await swe_bench_service.load_dataset()
task_id = request.get("task_id")
if not task_id:
raise HTTPException(status_code=400, detail="task_id is required")
enable_transparency = request.get("enable_transparency", True)
temperature = request.get("temperature", 0.7)
max_tokens = request.get("max_tokens", 500)
try:
result = await swe_bench_service.generate_solution(
task_id=task_id,
model_manager=manager,
enable_transparency=enable_transparency,
temperature=temperature,
max_tokens=max_tokens
)
return result.to_dict()
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.error(f"SWE-bench generation error: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/swe-bench/evaluate")
async def evaluate_swe_bench_solution(
request: Dict[str, Any],
authenticated: bool = Depends(verify_api_key)
):
"""Evaluate a generated solution"""
from .swe_bench_service import swe_bench_service
task_id = request.get("task_id")
solution = request.get("solution")
run_tests = request.get("run_tests", False)
if not task_id or not solution:
raise HTTPException(status_code=400, detail="task_id and solution are required")
try:
evaluation = await swe_bench_service.evaluate_solution(
task_id=task_id,
solution=solution,
run_tests=run_tests
)
return evaluation
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.error(f"SWE-bench evaluation error: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/swe-bench/metrics")
async def get_swe_bench_metrics(
authenticated: bool = Depends(verify_api_key)
):
"""Get aggregate metrics for SWE-bench evaluations"""
from .swe_bench_service import swe_bench_service
if not swe_bench_service.dataset_loaded:
await swe_bench_service.load_dataset()
return swe_bench_service.get_metrics()
@app.get("/swe-bench/comparison/{task_id}")
async def get_swe_bench_comparison(
task_id: str,
authenticated: bool = Depends(verify_api_key)
):
"""Get comparison results for a task (with vs without transparency)"""
from .swe_bench_service import swe_bench_service
comparison = swe_bench_service.get_comparison_results(task_id)
if not comparison:
raise HTTPException(
status_code=404,
detail="No comparison data available. Generate solutions with and without transparency first."
)
return comparison
# ==============================================================================
# VOCABULARY & TOKENIZATION ENDPOINTS
# ==============================================================================
@app.post("/vocabulary/search")
async def search_vocabulary(
request: Dict[str, Any],
authenticated: bool = Depends(verify_api_key)
):
"""Search vocabulary by query string"""
query = request.get("query", "").lower()
limit = request.get("limit", 50)
if not query:
return {"results": [], "total": 0}
vocab = manager.tokenizer.get_vocab()
# Search for tokens containing the query
results = []
for token, token_id in vocab.items():
if query in token.lower():
results.append({
"token": token,
"token_id": token_id,
"byte_length": len(token.encode('utf-8'))
})
if len(results) >= limit:
break
return {
"results": results,
"total": len(results),
"vocabulary_size": len(vocab)
}
@app.get("/vocabulary/browse")
async def browse_vocabulary(
page: int = 0,
page_size: int = 100,
filter_type: str = "all", # all, programming, common, functions
authenticated: bool = Depends(verify_api_key)
):
"""Browse vocabulary with pagination and smart filtering"""
vocab = manager.tokenizer.get_vocab()
# Smart filtering for programming tokens
if filter_type == "programming":
# Python keywords and common programming terms
programming_keywords = {
"def", "class", "return", "import", "from", "if", "else", "elif",
"for", "while", "break", "continue", "pass", "try", "except",
"finally", "with", "as", "lambda", "yield", "async", "await",
"None", "True", "False", "and", "or", "not", "in", "is"
}
filtered_vocab = {k: v for k, v in vocab.items() if k in programming_keywords}
elif filter_type == "functions":
# Common function/method names
filtered_vocab = {k: v for k, v in vocab.items()
if any(term in k.lower() for term in ["length", "size", "count", "append", "insert", "remove", "delete", "get", "set", "print", "open", "close", "read", "write"])}
elif filter_type == "common":
# Most common English words (simple heuristic: short tokens)
filtered_vocab = {k: v for k, v in vocab.items() if len(k) <= 4 and k.isalpha()}
else:
filtered_vocab = vocab
# Sort by token ID
sorted_items = sorted(filtered_vocab.items(), key=lambda x: x[1])
# Paginate
start = page * page_size
end = start + page_size
page_items = sorted_items[start:end]
results = []
for token, token_id in page_items:
results.append({
"token": token,
"token_id": token_id,
"byte_length": len(token.encode('utf-8'))
})
return {
"items": results,
"total": len(filtered_vocab),
"page": page,
"page_size": page_size,
"total_pages": (len(filtered_vocab) + page_size - 1) // page_size
}
@app.post("/tokenize/preview")
async def tokenize_preview(
request: Dict[str, Any],
authenticated: bool = Depends(verify_api_key)
):
"""Live tokenization preview for arbitrary text"""
from .tokenizer_utils import TokenizerMetadata, get_tokenizer_stats
text = request.get("text", "")
if not text:
return {"tokens": [], "stats": {}}
# Tokenize
token_ids = manager.tokenizer.encode(text, add_special_tokens=False)
# Get metadata
metadata = TokenizerMetadata(manager.tokenizer)
token_analysis = metadata.analyze_tokens(token_ids)
stats = get_tokenizer_stats(manager.tokenizer, text)
return {
"text": text,
"tokens": token_analysis,
"stats": stats,
"token_count": len(token_ids)
}
@app.post("/tokenize/compare")
async def compare_tokenizers(
request: Dict[str, Any],
authenticated: bool = Depends(verify_api_key)
):
"""Compare tokenization across different models"""
from transformers import AutoTokenizer
from .tokenizer_utils import get_tokenizer_stats
text = request.get("text", "")
models = request.get("models", ["Salesforce/codegen-350M-mono"])
if not text:
return {"results": {}}
results = {}
for model_name in models:
try:
# Load tokenizer (will be cached by transformers)
if model_name == "Salesforce/codegen-350M-mono":
tokenizer = manager.tokenizer
else:
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Tokenize
tokens = tokenizer.tokenize(text)
token_ids = tokenizer.encode(text, add_special_tokens=False)
token_texts = [tokenizer.decode([tid]) for tid in token_ids]
stats = get_tokenizer_stats(tokenizer, text)
results[model_name] = {
"tokens": tokens,
"token_ids": token_ids,
"token_texts": token_texts,
"token_count": len(token_ids),
"stats": stats
}
except Exception as e:
logger.error(f"Error loading tokenizer {model_name}: {e}")
results[model_name] = {"error": str(e)}
return {"text": text, "results": results}
@app.post("/token/metadata")
async def get_token_metadata(
request: Dict[str, Any],
authenticated: bool = Depends(verify_api_key)
):
"""Get comprehensive metadata for a specific token"""
from .tokenizer_utils import TokenizerMetadata
token_id = request.get("token_id")
if token_id is None:
raise HTTPException(status_code=400, detail="token_id is required")
metadata = TokenizerMetadata(manager.tokenizer)
# Get token text
token_text = manager.tokenizer.decode([token_id])
# Get BPE pieces
bpe_pieces = metadata.get_subword_pieces(token_id)
# Get byte length
byte_length = metadata.get_byte_length(token_id)
# Check if special token
special_tokens = {
"eos": manager.tokenizer.eos_token_id,
"bos": manager.tokenizer.bos_token_id,
"pad": manager.tokenizer.pad_token_id,
"unk": manager.tokenizer.unk_token_id
}
is_special = token_id in special_tokens.values()
# Check if multi-split (returns array, extract first element)
is_multi_split_array = metadata.is_multi_split_identifier([token_id])
is_multi_split = is_multi_split_array[0] if is_multi_split_array else False
return {
"token_id": token_id,
"text": token_text,
"bpe_pieces": bpe_pieces,
"byte_length": byte_length,
"is_special": is_special,
"is_multi_split": is_multi_split,
"num_pieces": len(bpe_pieces),
"tokenizer_type": metadata.tokenizer_type
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |