File size: 129,163 Bytes
a2ffd07 | 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 | import torch as t
from torch import Tensor
from .Graph_Template import Graph, GraphName, Node, Index
from typing import List, Tuple, Dict, Union, Callable, Any
from tqdm import tqdm
from transformer_lens.hook_points import HookPoint
from transformer_lens import (
utils,
HookedTransformer,
ActivationCache,
)
from copy import deepcopy
from collections import OrderedDict, defaultdict
from warnings import warn
from contextlib import contextmanager
from sae_lens import (
HookedSAETransformer,
)
from functools import partial
from itertools import product
from collections import OrderedDict
from .Graph_utils import nested_dict_to_string
from .Sparse_act import SparseAct
from torch import sparse_coo_tensor
import einops
import torch.autograd as atg
def rademacher_sample(size) -> Tensor:
return t.randint(0, 2, size, dtype=t.float32) * 2 - 1
def diag_H(g: Tensor, x: Tensor, niter: int = 100) -> Tensor:
diag_H = t.zeros_like(x)
for _ in range(niter):
v = rademacher_sample(x.shape).to(x.device)
Hv = atg.grad(
g, x, grad_outputs=v, retain_graph=True, allow_unused=True
)[0]
diag_H.add_(v * Hv)
return diag_H
def diag_H_mask(g: Tensor, x: Tensor, mask: Tensor, niter: int = 100) -> Tensor:
x_mask = x[mask]
g_mask = g[mask]
diag_H = t.zeros_like(x_mask)
for _ in range(niter):
v = rademacher_sample(x_mask.shape).to(x.device)
Hv = atg.grad(
g_mask, x, grad_outputs=v, retain_graph=True, allow_unused=True
)[0][mask]
diag_H.add_(v * Hv)
return diag_H
def cache_to_sparseact(
cache: Dict[str, Tensor] | ActivationCache,
act_name: str,
res_name: str | None = None,
resc_name: str | None = None,
) -> SparseAct:
return SparseAct(
act=cache[act_name],
res=cache[res_name] if res_name is not None else None,
resc=cache[resc_name] if resc_name is not None else None,
)
def interpolate(start: Tensor, end: Tensor, frac: float,) -> Tensor:
assert 0 <= frac <= 1, "frac must be in [0, 1]"
return start * frac + end * (1 - frac)
def create_list(dict: Dict[str, Tensor], name: str) -> Dict[str, Tensor]:
if name not in dict:
dict[name] = 0 # type: ignore
return dict
class ConnectionNode(Node):
def __init__(self, name: str):
self._name = name
@property
def name(self) -> str:
return self._name
def __eq__(self, other) -> bool:
if isinstance(other, ConnectionNode):
return self._name == other.name
elif isinstance(other, str):
return self._name == other
else:
raise NotImplementedError("other is not an instance of ConnectionNode or str")
def __repr__(self) -> str:
return self.name
def __hash__(self) -> int:
return hash(self.name)
class ConnectionIndex(Index):
def __init__(
self,
list_index: tuple[int|None, ...] | None = None,
):
if list_index is None:
self.list_index = (None,)
else:
for index in list_index:
assert type(index) == int or index == None, "index is not an instance of int or None"
self.list_index = list_index
@property
def as_index(self) -> Tuple[int | slice, ...]:
return tuple(slice(None) if x is None else x for x in self.list_index) # for indexing
def __repr__(self) -> str:
ret = "["
for idx, x in enumerate(self.list_index):
if idx > 0:
ret += ", "
if x is None:
ret += ":"
elif type(x) == int:
ret += str(x)
else:
raise NotImplementedError(x)
ret += "]"
return ret
def __eq__(self, other) -> bool:
if isinstance(other, ConnectionIndex):
return self.list_index == other.list_index
elif isinstance(other, tuple):
return self.list_index == other
else:
raise NotImplementedError("other is not an instance of ConnectionIndex or tuple")
def __hash__(self) -> int:
return hash(self.list_index)
class FeatureIndex(ConnectionIndex):
def __init__(
self,
idx: Tuple[int, ...] | List[int],
length = 2,
):
self.idx = tuple(idx)
super().__init__(return_idx(idx, length))
class FeatureErrorIndex(ConnectionIndex):
def __init__(
self,
idx: Tuple[int, ...] | List[int],
length = 2,
):
self.idx = tuple(idx)
super().__init__(return_idx(idx, length))
class ErrorIndex(ConnectionIndex):
def __init__(
self,
idx: Tuple[int, ...] | List[int],
length = 1,
):
self.idx = tuple(idx)
super().__init__(return_idx(idx, length))
def sae_hook_name(sae_name: str) -> str:
return f'{sae_name}.hook_sae_acts_post' # e.g. ...hook_resid_pre.hook_sae_acts_post
def error_term_name(sae_name: str) -> str:
return f'{sae_name}.hook_sae_error'
def output_hook_name(sae_name: str) -> str:
return f'{sae_name}.hook_sae_output'
def input_hook_name(sae_name: str) -> str:
return f'{sae_name}.hook_sae_input'
def recons_hook_name(sae_name: str) -> str:
return f'{sae_name}.hook_sae_recons'
def revert_hook_name(sae_name: str) -> str:
return ".".join(sae_name.split(".")[:-1]) # e.g. ...hook_resid_pre.hook_sae_acts_post -> ...hook_resid_pre
def return_idx(idx: Tuple | List, length: int = 2) -> Tuple:
assert len(idx) <= length, "The length of idx must be less than or equal to length"
return tuple([None for _ in range(length - len(idx))] + list(idx))
class Feature_Graph(Graph):
def __init__(
self,
model: HookedSAETransformer,
saes: Dict[int, List[Tuple[str, Any]]], # {layer: list[{hook_position: HookedSAE}]}, can define granularity here
use_error_term: bool = False,
):
'''
'''
self.model = model
self.cfg = model.cfg
self.use_error_term = use_error_term
self.device = self.cfg.device
self.n_layers = self.cfg.n_layers
# self.n_heads = self.cfg.n_heads
assert len(saes) == self.n_layers, "please provide SAEs"
self.saes = saes
self.dict_saes: Dict[str, Any] = self.extract_saes(saes)
self.reset_graph()
def graph_type(self) -> str:
return GraphName.feature_graph
def extract_saes(self, saes: Dict[int, List[Tuple[str, Any]]]) -> Dict[str, Any]:
dict_saes = {}
for layer in range(self.n_layers):
for hook_position, sae in saes[layer]:
dict_saes[hook_position] = sae
return dict_saes
def build_default_connection(
self,
seq_length: int,
token_wise: bool = False,
inter: bool = True,
intra: bool = False,
) -> Dict:
'''
Sample tokens to get the shape of the activations, necessary to build the graph of features
If token_wise, the each node is a feature of a token, else, the graph is built feature-wise
'''
self.reset_graph()
for layer in range(self.n_layers):
# Setup
self.connection[layer] = OrderedDict()
for hook_position, _ in self.saes[layer]:
self.connection[layer][(ConnectionNode(hook_position), ConnectionIndex())] = []
# Inter-layer connections
if inter:
for i, (hook_position_end, _) in reversed(list(enumerate(self.saes[layer]))):
for j, (hook_position_start, _) in enumerate(self.saes[layer]):
if i > j:
self.connection[layer][(ConnectionNode(hook_position_end), ConnectionIndex())].append(
(ConnectionNode(hook_position_start), ConnectionIndex())
)
# Intra-layer connections
if intra:
for prev_layer in range(layer):
for hook_position_end, _ in self.saes[layer]:
for hook_position_start, _ in self.saes[prev_layer]:
self.connection[layer][(ConnectionNode(hook_position_end), ConnectionIndex())].append(
(ConnectionNode(hook_position_start), ConnectionIndex())
)
# Sequential connection layer-1 --> layer
else:
if layer == 0:
continue
for hook_position_start, _ in self.saes[layer-1]:
# connect to the first node of the next layer
hook_position_end = self.saes[layer][0][0]
self.connection[layer][(ConnectionNode(hook_position_end), ConnectionIndex())].append(
(ConnectionNode(hook_position_start), ConnectionIndex())
)
self._build_nodes(seq_length, token_wise)
self._build_graphs()
return self.connection
def _build_nodes(self, seq_length: int, token_wise: bool) -> None:
self.seq_length = seq_length
self.token_wise = token_wise
for sae_name, sae in self.dict_saes.items():
node_shape = (self.seq_length, sae.cfg.d_sae)
self.nodes[(ConnectionNode(sae_name), ConnectionIndex())] = SparseAct(
t.ones(node_shape, requires_grad=False).to(self.device),
None,
t.ones(self.seq_length, requires_grad=False).to(self.device) if self.use_error_term else None,
)
self.node_scores[(ConnectionNode(sae_name), ConnectionIndex())] = SparseAct(
t.zeros(node_shape, requires_grad=False).to(self.device),
None,
t.zeros(self.seq_length, requires_grad=False).to(self.device) if self.use_error_term else None,
)
def _build_graphs(self) -> None:
assert self.nodes, "Please build the nodes first"
for _, connections in self.connection.items():
for hook_position_end, list_hook_positions_start in connections.items():
self.edges[hook_position_end] = OrderedDict()
self.edge_scores[hook_position_end] = OrderedDict()
for hook_position_start in list_hook_positions_start:
self.edges[hook_position_end][hook_position_start] = t.zeros([0]) # place holder
self.edge_scores[hook_position_end][hook_position_start] = t.zeros([0]) # place holder
def reset_graph(self) -> None:
self.connection: OrderedDict[int, OrderedDict[Tuple[Node, Index], List[Tuple[Node, Index]]]] = OrderedDict() # {layer: {hook_position_end: [hook_position_start]}}
self.nodes: Dict[Tuple[Node, Index], SparseAct] = {} # {hook_position: SparseAct[act: Tensor['seq d_sae'], resc: Tensor['seq']]}
self.node_scores: Dict[Tuple[Node, Index], SparseAct] = {}
self.edges: OrderedDict[Tuple[Node, Index], OrderedDict[Tuple[Node, Index], Tensor]] = OrderedDict() # {hook_position_end: {hook_position_start: Tensor}}
self.edge_scores: OrderedDict[Tuple[Node, Index], OrderedDict[Tuple[Node, Index], Tensor]] = OrderedDict()
self.seq_length: int | None = None
self.token_wise: bool | None = None
def _check_graph(self) -> None:
assert len(self.connection) > 0, "Graph is empty"
assert len(self.nodes) > 0, "Nodes is empty"
assert len(self.node_scores) > 0, "Node scores is empty"
assert len(self.edges) > 0, "Edges is empty"
assert len(self.edge_scores) > 0, "Edge scores is empty"
assert self.seq_length is not None
assert self.token_wise is not None
def __repr__(self) -> str:
self._check_graph()
return nested_dict_to_string(self.connection, indent=4)
def _check_feat_idx(self, feat_idx: Tuple | List) -> None:
if self.token_wise:
assert len(feat_idx) == 2, "Please provide the correct index"
else:
assert len(feat_idx) == 1, "Please provide the correct index"
def _check_error_idx(self, error_idx: Tuple | List) -> None:
if self.token_wise:
assert len(error_idx) == 1, "Please provide the correct index"
else:
assert len(error_idx) == 0, "Please provide the correct index"
def _active_nodes(
self,
sae_name: Node,
node_idx: Index,
reverse: bool = False,
) -> Tuple[List, ...]:
self._check_graph()
if self.token_wise:
node = self.nodes[(sae_name, node_idx)] # act: (seq, d_sae), resc: (seq)
else:
node = self.nodes[(sae_name, node_idx)].mean(dim=0) # act: (d_sae), resc: () - COLAPSED TENSOR
if reverse:
active_node = (node.act == 0).nonzero().tolist()
active_error = (node.resc == 0).nonzero().tolist() if self.use_error_term else [] # type: ignore
else:
active_node = node.act.nonzero().tolist()
active_error = node.resc.nonzero().tolist() if self.use_error_term else [] # type: ignore
return active_node, active_error
def active_nodes(
self,
sae_name: Node,
node_idx: Index,
reverse: bool = False,
) -> List[Tuple[Node, Index]]:
active_node, active_error = self._active_nodes(sae_name, node_idx, reverse)
feat_list = [
(sae_name, FeatureIndex(idx))
for idx in active_node
]
error_list = [
(sae_name, ErrorIndex(idx))
for idx in active_error
]
return feat_list + error_list # type: ignore
def add_node(
self,
sae_name: Node,
node_idx: Index,
) -> None:
self._check_graph()
pass # no implementation needed
def add_edge(
self,
sae_name_start: Node,
node_idx_start: Index,
sae_name_end: Node,
node_idx_end: Index,
) -> None:
self._check_graph()
pass # no implementation needed
def delete_node(
self,
sae_name: Node,
node_idx: Index,
) -> None:
self._check_graph()
pass # no implementation needed
def delete_edge(
self,
sae_name_start: Node,
node_idx_start: Index,
sae_name_end: Node,
node_idx_end: Index,
) -> None:
self._check_graph()
pass # no implementation needed
def _check_node_shape(self, sae_name: Node, sparseact: SparseAct):
try:
if self.token_wise:
assert sparseact.act.shape == t.Size([self.seq_length, self.dict_saes[sae_name.name].cfg.d_sae]) # type: ignore
else:
assert sparseact.act.shape == t.Size([self.dict_saes[sae_name.name].cfg.d_sae])
if self.use_error_term:
if self.token_wise:
assert sparseact.resc.shape == t.Size([self.seq_length]) # type: ignore
else:
assert sparseact.resc.numel() == 1 # type: ignore
except:
raise ValueError("Wrong input shape for nodes.")
def update_node(
self,
sae_name: Node,
node_idx: Index,
value_and_mask: Tuple[SparseAct, SparseAct],
) -> None:
self._check_graph()
value, mask = value_and_mask
assert isinstance(value, SparseAct), "value is not an instance of SparseAct"
assert isinstance(mask, SparseAct), "mask is not an instance of SparseAct"
self._check_node_shape(sae_name, value)
if not self.token_wise:
# convert to the right format of (seq, d_sae) and (seq)
value_act = einops.repeat(value.act, 'd_sae -> seq d_sae', seq=self.seq_length)
mask_act = einops.repeat(mask.act, 'd_sae -> seq d_sae', seq=self.seq_length)
value_resc = einops.repeat(value.resc, ' -> seq', seq=self.seq_length) if self.use_error_term else None
mask_resc = einops.repeat(mask.resc, ' -> seq', seq=self.seq_length) if self.use_error_term else None
value = SparseAct(value_act, None, value_resc)
mask = SparseAct(mask_act, None, mask_resc)
self.nodes[(sae_name, node_idx)] = mask.to(t.float32)
self.node_scores[(sae_name, node_idx)] = value
def update_edge(
self,
sae_name_start: Node,
node_idx_start: Index,
sae_name_end: Node,
node_idx_end: Index,
value_and_mask: Tuple[Tensor, Tensor],
) -> None:
self._check_graph()
value, mask = value_and_mask
assert isinstance(value, Tensor), "value is not an instance of Tensor"
assert isinstance(mask, Tensor), "mask is not an instance of Tensor"
self.edges[(sae_name_end, node_idx_end)][(sae_name_start, node_idx_start)] = mask
self.edge_scores[(sae_name_end, node_idx_end)][(sae_name_start, node_idx_start)] = value
def find_deleted_nodes(self, reverse = False) -> List[Tuple[Node, Index]]:
self._check_graph()
all_list = []
for sae_name, node_idx in self.nodes.keys():
inactive_node, inactive_error = self._active_nodes(sae_name, node_idx, not reverse)
feat_list = [
(sae_name, FeatureIndex(idx))
for idx in inactive_node
]
error_list = [
(sae_name, ErrorIndex(idx))
for idx in inactive_error
]
all_list += feat_list + error_list
return all_list
def find_deleted_edges(self, reverse = False) -> List[Tuple[Node, Index, Node, Index]]:
self._check_graph()
all_list = []
for end_node, end_idx in self.edges.keys():
for start_node, start_idx in self.edges[(end_node, end_idx)].keys():
edge = self.edges[(end_node, end_idx)][(start_node, start_idx)]
if not reverse:
inactive_node = (edge.values() == 0) # (num_active, seq, d_sae+1) or (num_active, d_sae+1)
else:
inactive_node = edge.values()
d_sae_end = self.dict_saes[end_node.name].cfg.d_sae
d_sae_start = self.dict_saes[start_node.name].cfg.d_sae
active_idx = [index for _, index in self.active_nodes(start_node, start_idx)]
revised_active_nodes = [
index.idx if isinstance(index, FeatureIndex) else index.idx + (d_sae_start,) # type: ignore
for index in active_idx
]
for num_active_idx in range(edge.indices().shape[1]):
end_node_idx = edge.indices()[:, num_active_idx].tolist()
# check if the end_node_idx is the error term
check_error = True if self.use_error_term and end_node_idx[-1] == d_sae_end else False
# create the end_index class to be used in the tuple
end_index = FeatureIndex(end_node_idx) if not check_error else ErrorIndex(end_node_idx[:-1])
for i, idx in enumerate(revised_active_nodes):
if inactive_node[(num_active_idx,) + idx] > 0:
all_list.append(
(
start_node,
active_idx[i],
end_node,
end_index,
)
)
return all_list
def iterate_nodes(self) -> List[Tuple[Node, Index]]:
self._check_graph()
return list(self.nodes.keys())
def iterate_edges(self) -> List[Tuple[Node, Index, Node, Index]]:
self._check_graph()
all_edges = []
for end, edges in self.edges.items():
for start, edge in edges.items():
all_edges.append(start + end)
return all_edges
def add_single_feature(
self,
sae_name: Node,
node_idx: Index,
feat_idx: Tuple[int, ...] | List[int] | FeatureIndex,
) -> None:
self._check_graph()
self._set_feat_value(sae_name, node_idx, feat_idx, 1)
def delete_single_feature(
self,
sae_name: Node,
node_idx: Index,
feat_idx: Tuple[int, ...] | List[int] | FeatureIndex,
) -> None:
self._check_graph()
self._set_feat_value(sae_name, node_idx, feat_idx, 0)
def update_single_feature(
self,
sae_name: Node,
node_idx: Index,
feat_idx: Tuple[int, ...] | List[int] | FeatureIndex,
value: int | float | Tensor,
) -> None:
self._check_graph()
assert isinstance(value, (int, float, Tensor)), "The value must be int, float or Tensor."
self._set_feat_value(sae_name, node_idx, feat_idx, value)
def add_single_error(
self,
sae_name: Node,
node_idx: Index,
error_idx: Tuple[int, ...] | List[int] | ErrorIndex,
) -> None:
self._check_graph()
self._set_error_value(sae_name, node_idx, error_idx, 1)
def delete_single_error(
self,
sae_name: Node,
node_idx: Index,
error_idx: Tuple[int, ...] | List[int] | ErrorIndex,
) -> None:
self._check_graph()
self._set_error_value(sae_name, node_idx, error_idx, 0)
def update_single_error(
self,
sae_name: Node,
node_idx: Index,
error_idx: Tuple[int, ...] | List[int] | ErrorIndex,
value: int | float | Tensor,
) -> None:
self._check_graph()
assert isinstance(value, (int, float, Tensor)), "The value must be int, float or Tensor."
self._set_error_value(sae_name, node_idx, error_idx, value)
def _set_feat_value(
self,
sae_name: Node,
node_idx: Index,
feat_idx: Tuple[int, ...] | List[int] | FeatureIndex,
value: int | float | Tensor,
) -> None:
self._check_graph()
if isinstance(feat_idx, (tuple, list)):
self._check_feat_idx(feat_idx)
self.nodes[(sae_name, node_idx)].act[return_idx(feat_idx)] = value
elif isinstance(feat_idx, FeatureIndex):
self.nodes[(sae_name, node_idx)].act[feat_idx.as_index] = value
else:
raise ValueError(f"feat_idx of type {type(feat_idx)} is not supported.")
def _set_error_value(
self,
sae_name: Node,
node_idx: Index,
error_idx: Tuple[int, ...] | List[int] | ErrorIndex,
value: int | float | Tensor,
) -> None:
if not self.use_error_term: # nothing to delete
return
if isinstance(error_idx, (tuple, list)):
self._check_error_idx(error_idx)
self.nodes[(sae_name, node_idx)].resc[return_idx(error_idx, 1)] = value # type: ignore
elif isinstance(error_idx, ErrorIndex):
self.nodes[(sae_name, node_idx)].resc[error_idx.as_index] = value # type: ignore
else:
raise ValueError(f"error_idx of type {type(error_idx)} is not supported.")
def remove_error_term(self) -> None:
if self.use_error_term:
for sae_name, node_idx in self.nodes.keys():
if self.nodes[(sae_name, node_idx)].resc is not None:
self.nodes[(sae_name, node_idx)].resc = t.zeros(self.seq_length, requires_grad=False).to(self.device) # type: ignore
def forward(
self,
clean_token: Tensor,
corrupt_cache: ActivationCache | Dict[str, Tensor] | None,
patch_deleted_comp: bool = False,
**kwargs,
) -> Tuple[Tensor, Dict[str, SparseAct]]:
'''
Forward pass of the graph with clean tokens, if the edge exists, replace the activation with corrupted activation
'''
self._check_graph()
self.model.reset_hooks()
self.model_setup()
fwd_cache = {}
def hook_sae_fwd(act: Tensor, hook: HookPoint, sae_name: str) -> Tensor:
if hook.name == sae_hook_name(sae_name):
if patch_deleted_comp and corrupt_cache is not None:
act_mask = self.nodes[(sae_name, (None,))].act == 0 # type: ignore
act[:, act_mask] = corrupt_cache[sae_hook_name(sae_name)][:, act_mask]
fwd_cache[sae_hook_name(sae_name)] = act.detach()
elif hook.name == error_term_name(sae_name) and self.use_error_term:
if patch_deleted_comp and corrupt_cache is not None:
resc_mask = self.nodes[(sae_name, (None,))].resc == 0 # type: ignore
act[:, resc_mask] = corrupt_cache[error_term_name(sae_name)][:, resc_mask]
fwd_cache[error_term_name(sae_name)] = act.detach()
# if "resid_post" in hook.name: # type: ignore
# print(act.max())
return act
with t.no_grad():
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
with self.model.hooks(
fwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(hook_sae_fwd, sae_name=sae_name))
for sae_name in self.dict_saes.keys()
],
):
logits = self.model(clean_token)
cache = {}
for sae_name in self.dict_saes.keys():
cache[sae_name] = SparseAct(
act=fwd_cache[sae_hook_name(sae_name)],
res=fwd_cache[error_term_name(sae_name)] if self.use_error_term else None,
)
for sae in self.dict_saes.values():
sae.reset_hooks()
self.model.reset_hooks()
return logits, cache
def __call__(self, *args, **kwargs) -> Tuple[Tensor, Dict[str, SparseAct]]:
return self.forward(*args, **kwargs)
def forward_backward_gradient(
self,
clean_token: Tensor,
corrupt_cache: ActivationCache | Dict[str, Tensor],
metric: Callable[[Tensor], Tensor],
retain_graph: bool = False,
mode: str = 'node',
gradient_mode: str = 'standard',
pass_through_grad: bool = False,
verbose: bool = False,
**kwargs,
) -> Tuple[
Dict[Tuple[Node, Index], SparseAct], # node effects
Dict[Tuple[Node, Index, Node, Index], Tensor], # edge effects
]:
if mode == 'node':
if verbose:
print("Calculating node gradients...")
if gradient_mode == "standard":
node_grads, clean_cache = self._gradient_wrt_nodes(
clean_token, metric, retain_graph, pass_through_grad, **kwargs
)
elif gradient_mode == "ig":
node_grads, clean_cache = self._gradient_wrt_nodes_ig(
clean_token, corrupt_cache, metric, retain_graph, verbose, **kwargs
)
else:
raise NotImplementedError(f"gradient_mode {gradient_mode} is not supported")
node_effect = self._attrib_effect_node(node_grads, corrupt_cache, clean_cache)
return node_effect, {}
elif mode == 'edge':
if kwargs.get('node_grads', None) is None or kwargs.get('node_effect', None) is None:
# run the _gradient_wrt_nodes to get node_grads, and use node_effect to prune out unimportant nodes
if verbose:
print("Calculating node gradients...")
if gradient_mode == "standard":
node_grads, clean_cache = self._gradient_wrt_nodes(
clean_token, metric, retain_graph, pass_through_grad, **kwargs
)
elif gradient_mode == "ig":
node_grads, clean_cache = self._gradient_wrt_nodes_ig(
clean_token, corrupt_cache, metric, retain_graph, verbose, **kwargs
)
else:
raise NotImplementedError(f"gradient_mode {gradient_mode} is not supported")
node_effect = self._attrib_effect_node(node_grads, corrupt_cache, clean_cache)
else:
node_grads: Dict[Tuple[Node, Index], SparseAct] = kwargs.get('node_grads') # type: ignore
node_effect: Dict[Tuple[Node, Index], SparseAct] = kwargs.get('node_effect') # type: ignore
# Pruning
if kwargs.get('prune', False):
if verbose:
print("Pruning nodes...")
self._prune_nodes(node_effect, verbose, **kwargs)
if kwargs.get('gradient_only', False):
if verbose:
print("Returning edge gradients only...")
for name, sparse_act in node_grads.items():
node_grads[name] = sparse_act.to_sparse_like_self(t.ones_like(sparse_act.to_tensor()))
del sparse_act
edge_grads, _ = self._gradient_wrt_edges(
clean_token, corrupt_cache, node_grads, verbose, **kwargs
)
return node_effect, edge_grads
else:
raise NotImplementedError(f"mode {mode} is not supported")
def _attrib_effect_node(
self,
grads: Dict,
corrupt_cache: ActivationCache | Dict[str, Tensor],
clean_cache: Dict[str, SparseAct],
) -> Dict:
attrib_effect = {}
aggregate_dim = [0] if self.token_wise else [0, 1]
for (node, index), grad in grads.items():
corrupt_sparse_act = cache_to_sparseact(
corrupt_cache,
sae_hook_name(node.name),
error_term_name(node.name) if self.use_error_term else None,
)
attrib_effect[(node, index)] = ( # act: (seq, d_sae), resc: (seq) || act: (d_sae), resc: ()
grad @
(corrupt_sparse_act - clean_cache[node.name])
).sum(aggregate_dim)
return attrib_effect
def _gradient_wrt_nodes(
self,
clean_token: Tensor,
metric: Callable[[Tensor], Tensor],
retain_graph: bool = False,
pass_through_grad: bool = False,
verbose: bool = False,
**kwargs,
) -> Tuple[
Dict[Tuple[Node, Index], SparseAct], # node effects
Dict[str, SparseAct]
]:
'''
Forward pass of the graph with clean tokens, if the edge exists, replace the activation with corrupted activation
Backward pass on the graph wrt the metric
Return the gradients wrt nodes, edges, and activation cache
'''
self._check_graph()
self.model_setup()
self.model.reset_hooks()
for _, sae in self.dict_saes.items():
sae.reset_hooks()
bwd_cache = {}
pass_through_cache = {}
def hook_sae_bwd(grad: Tensor, hook: HookPoint, sae_name: str) -> None:
if hook.name == sae_hook_name(sae_name):
bwd_cache[sae_hook_name(sae_name)] = grad.detach()
elif hook.name == output_hook_name(sae_name):
if self.use_error_term:
# we have: output = recon + stop_grad(error_term)
# so, the TRUE error_grad (if not stop_grad) is output_grad
# due to: output = recon + error_term
bwd_cache[error_term_name(sae_name)] = grad.detach()
if pass_through_grad:
pass_through_cache[output_hook_name(sae_name)] = grad.detach()
elif hook.name == input_hook_name(sae_name):
if pass_through_grad:
# we have to modify inplace instead of grad = ... and then return grad
# because, returning a tensor in bwd pass hook is buggy somehow
grad.copy_(pass_through_cache[output_hook_name(sae_name)])
fwd_cache = {}
def hook_sae_fwd(act: Tensor, hook: HookPoint, sae_name: str) -> Tensor:
if hook.name == sae_hook_name(sae_name):
fwd_cache[sae_hook_name(sae_name)] = act.detach()
elif error_term_name(sae_name) == hook.name and self.use_error_term:
fwd_cache[error_term_name(sae_name)] = act.detach()
return act
with t.set_grad_enabled(True):
with self._detach_error_term(True):
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
with self.model.hooks(
fwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(hook_sae_fwd, sae_name=sae_name))
for sae_name in self.dict_saes.keys()
],
bwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(hook_sae_bwd, sae_name=sae_name))
for sae_name in self.dict_saes.keys()
],
):
metric(self.model(clean_token)).backward(retain_graph=retain_graph)
node_grads = {}
for node, index in self.nodes.keys():
node_grads[(node, index)] = cache_to_sparseact(
bwd_cache,
sae_hook_name(node.name),
error_term_name(node.name) if self.use_error_term else None,
)
cache = {}
for sae_name in self.dict_saes.keys():
cache[sae_name] = cache_to_sparseact(
fwd_cache,
sae_hook_name(sae_name),
error_term_name(sae_name) if self.use_error_term else None,
)
self.model.reset_hooks()
for sae in self.dict_saes.values():
sae.reset_hooks()
return node_grads, cache
def _gradient_wrt_nodes_ig(
self,
clean_token: Tensor,
corrupt_cache: ActivationCache | Dict[str, Tensor],
metric: Callable[[Tensor], Tensor],
retain_graph: bool = False,
verbose: bool = False,
**kwargs,
) -> Tuple[
Dict[Tuple[Node, Index], SparseAct], # node effects
Dict[str, SparseAct]
]:
steps = kwargs.get('steps', 10)
self._check_graph()
self.model_setup()
self.model.reset_hooks()
for _, sae in self.dict_saes.items():
sae.reset_hooks()
bwd_cache: Dict[str, Tensor] = {}
def hook_sae_bwd(grad: Tensor, hook: HookPoint, sae_name: str) -> None:
if hook.name == sae_hook_name(sae_name):
create_list(bwd_cache, sae_hook_name(sae_name))
bwd_cache[sae_hook_name(sae_name)] += grad.detach()
elif hook.name == output_hook_name(sae_name):
if self.use_error_term:
# we have: output = recon + stop_grad(error_term)
# so, the TRUE error_grad (if not stop_grad) is output_grad
# due to: output = recon + error_term
create_list(bwd_cache, error_term_name(sae_name))
bwd_cache[error_term_name(sae_name)] += grad.detach()
fwd_cache = {}
def hook_sae_fwd(act: Tensor, hook: HookPoint, sae_name: str, target_name: str, frac: float) -> Tensor:
if hook.name == sae_hook_name(sae_name):
# interpolate for integrated gradients
if hook.name == sae_hook_name(target_name):
act = interpolate(
corrupt_cache[sae_hook_name(sae_name)],
act,
frac,
)
fwd_cache[sae_hook_name(sae_name)] = act.detach()
elif error_term_name(sae_name) == hook.name and self.use_error_term:
# interpolate for integrated gradients
if hook.name == error_term_name(target_name):
act = interpolate(
corrupt_cache[error_term_name(sae_name)],
act,
frac,
)
fwd_cache[error_term_name(sae_name)] = act.detach()
return act
with t.set_grad_enabled(True):
with self._detach_error_term(True):
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
for target_name in self.dict_saes.keys():
for step in range(steps):
frac = step / steps
with self.model.hooks(
fwd_hooks=[
(
lambda name, sae_name=sae_name: sae_name in name,
partial(hook_sae_fwd, sae_name=sae_name, target_name=target_name, frac=frac)
) for sae_name in self.dict_saes.keys()
],
bwd_hooks=[
(
lambda name, target_name=target_name: target_name in name,
partial(hook_sae_bwd, sae_name=target_name)
)
],
):
metric(self.model(clean_token)).backward(retain_graph=retain_graph)
# average the gradients
for key in bwd_cache.keys():
bwd_cache[key] /= steps
node_grads = {}
for node, index in self.nodes.keys():
node_grads[(node, index)] = cache_to_sparseact(
bwd_cache,
sae_hook_name(node.name),
error_term_name(node.name) if self.use_error_term else None,
)
cache = {}
for sae_name in self.dict_saes.keys():
cache[sae_name] = cache_to_sparseact(
fwd_cache,
sae_hook_name(sae_name),
error_term_name(sae_name) if self.use_error_term else None,
)
self.model.reset_hooks()
for sae in self.dict_saes.values():
sae.reset_hooks()
return node_grads, cache
def _gradient_wrt_edges(
self,
clean_token: Tensor,
corrupt_cache: ActivationCache | Dict[str, Tensor],
node_grads: Dict[Tuple[Node, Index], SparseAct],
verbose: bool = False,
**kwargs,
) -> Tuple[
Dict[Tuple[Node, Index, Node, Index], Tensor], # edge effects
Dict[str, SparseAct]
]:
self._check_graph()
self.model_setup()
self.model.reset_hooks()
for _, sae in self.dict_saes.items():
sae.reset_hooks()
gradient_mode = kwargs.get('edge_gradient_mode', 'gradient')
_, clean_cache = self.forward(clean_token, corrupt_cache=None)
edge_grads: Dict[Tuple[Node, Index, Node, Index], Tensor] = {}
for layer, connection in tqdm(self.connection.items(), disable=not verbose):
if verbose:
print(f"Layer {layer}:")
for hook_position_end, list_hook_positions_start in tqdm(connection.items(), disable=not verbose):
assert hook_position_end in node_grads, f"Node gradient of {hook_position_end} is not provided."
for hook_position_start in list_hook_positions_start:
corrupt_sparse_act = cache_to_sparseact(
corrupt_cache,
sae_hook_name(hook_position_start[0].name),
error_term_name(hook_position_start[0].name) if self.use_error_term else None,
)
right_vec = corrupt_sparse_act - clean_cache[hook_position_start[0].name]
if gradient_mode == "gradient":
edge_grads[hook_position_start + hook_position_end] = self._edge_attribution(
clean_token,
hook_position_end,
hook_position_start,
node_grads[hook_position_end],
right_vec,
layer,
**kwargs,
)
elif gradient_mode == "ig":
edge_grads[hook_position_start + hook_position_end] = self._edge_attribution_ig(
clean_token,
corrupt_cache,
hook_position_end,
hook_position_start,
node_grads[hook_position_end],
right_vec,
layer,
**kwargs,
)
else:
raise NotImplementedError(f"gradient_mode {gradient_mode} is not supported")
return edge_grads, clean_cache
def _edge_attribution(
self,
clean_token: Tensor,
hook_position_end: Tuple[Node, Index],
hook_position_start: Tuple[Node, Index],
leftvec: SparseAct,
rightvec: SparseAct,
layer: int,
**kwargs,
) -> Tensor:
def hook_sae_bwd(grad: Tensor, hook: HookPoint, sae_name: str, bwd_cache: Dict) -> None:
if hook.name == sae_hook_name(hook_position_start[0].name):
# only store the gradient at the start position
bwd_cache[sae_hook_name(hook_position_start[0].name)] = grad.detach()
elif hook.name == output_hook_name(hook_position_start[0].name):
# we have: output = recon + stop_grad(error_term)
# so, the TRUE error_grad (if not stop_grad) is output_grad
# due to: output = recon + error_term
if self.use_error_term:
# only store the gradient at the start position
bwd_cache[error_term_name(hook_position_start[0].name)] = grad.detach()
# IMPORTANT NOTE for reproducibility:
# we zero grad of intermediate components
# but zero grad the output hook of SAE will ALSO ZERO GRAD the resid mid / post --> no downstream grads
# so, we instead zero grad of the input hook of SAE
elif hook.name == input_hook_name(sae_name):
if hook.name != input_hook_name(hook_position_end[0].name):
grad.zero_()
def hook_sae_fwd(act: Tensor, hook: HookPoint, to_bwd_cache: Dict) -> Tensor:
if hook.name == sae_hook_name(hook_position_end[0].name):
# store activation for backward later
to_bwd_cache[sae_hook_name(hook_position_end[0].name)] = act
elif error_term_name(hook_position_end[0].name) == hook.name and self.use_error_term:
# store activation for backward later
to_bwd_cache[error_term_name(hook_position_end[0].name)] = act
return act
d_sae_end = self.dict_saes[hook_position_end[0].name].cfg.d_sae
d_sae_start = self.dict_saes[hook_position_start[0].name].cfg.d_sae
to_bwd_cache = {}
bwd_cache = {}
edge_effect = OrderedDict()
with t.set_grad_enabled(True):
with self._detach_error_term(False, hook_position_end[0].name):
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
with self.model.hooks(
fwd_hooks=[
(lambda name: True, partial(
hook_sae_fwd,
to_bwd_cache=to_bwd_cache,
))
],
bwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(
hook_sae_bwd,
sae_name=sae_name,
bwd_cache=bwd_cache,
)) for sae_name in self.dict_saes.keys()
],
):
self.model.forward(clean_token, return_type=None, stop_at_layer=layer+1)
aggregate_dim = [0] if self.token_wise else [0, 1]
to_bwd = ( # (seq, d_sae+1) || (d_sae+1)
cache_to_sparseact(
to_bwd_cache,
sae_hook_name(hook_position_end[0].name),
error_term_name(hook_position_end[0].name) if self.use_error_term else None,
) @ leftvec.detach()
).sum(aggregate_dim).to_tensor()
del to_bwd_cache
for active_idx, (end_node, end_index) in enumerate(self.active_nodes(*hook_position_end)):
if isinstance(end_index, ErrorIndex):
# the last index is error: shape (d_sae+1) so last index is d_sae
to_bwd[end_index.idx + (d_sae_end,)].backward(retain_graph=True)
index = t.tensor(list(end_index.idx + (d_sae_end,)), device=self.device)
elif isinstance(end_index, FeatureIndex):
to_bwd[end_index.idx].backward(retain_graph=True)
index = t.tensor(list(end_index.idx), device=self.device)
else:
raise ValueError(f"end_index of type {type(end_index)} is not supported.")
'''
edge_effect shape (seq, d_sae+1, seq, d_sae+1) or (d_sae+1, d_sae+1) in sparse_coo tensor
the sparse_coo will have the shape:
--> indices of shape (2, num_active) or (1, num_active)
--> values of shape (num_active, seq, d_sae+1) or (num_active, d_sae+1)
'''
edge_effect[active_idx] = (
index,
( # (seq, d_sae+1) || (d_sae+1)
cache_to_sparseact(
bwd_cache,
sae_hook_name(hook_position_start[0].name),
error_term_name(hook_position_start[0].name) if self.use_error_term else None,
) @ rightvec
).sum(aggregate_dim).to_tensor()
)
del bwd_cache
seq = int(self.seq_length) # type: ignore
num_end = d_sae_end
num_start = d_sae_start
if self.use_error_term:
num_end += 1
num_start += 1
if len(edge_effect.keys()) != 0:
indices = t.stack([val[0] for val in edge_effect.values()], dim=0).T # shape (2, num_active) or (1, num_active)
values = t.stack([val[1] for val in edge_effect.values()], dim=0) # shape (num_active, seq, d_sae+1) or (num_active, d_sae+1)
# if no active nodes, return empty tensor
else:
indices = t.empty((2, 0) if self.token_wise else (1, 0), dtype=t.long).to(self.device)
values = t.empty((0, seq, num_start) if self.token_wise else (0, num_start), dtype=t.float).to(self.device)
if self.token_wise:
return t.sparse_coo_tensor(indices, values, size=(seq, num_end, seq, num_start)).coalesce()
else:
return t.sparse_coo_tensor(indices, values, size=(num_end, num_start)).coalesce()
def _edge_attribution_ig(
self,
clean_token: Tensor,
corrupt_cache: Dict[str, Tensor] | ActivationCache,
hook_position_end: Tuple[Node, Index],
hook_position_start: Tuple[Node, Index],
leftvec: SparseAct,
rightvec: SparseAct,
layer: int,
**kwargs,
) -> Tensor:
steps = kwargs.get('steps', 10)
def hook_sae_bwd(grad: Tensor, hook: HookPoint, sae_name: str, bwd_cache: Dict) -> None:
if hook.name == sae_hook_name(hook_position_start[0].name):
# only store the gradient at the start position
bwd_cache[sae_hook_name(hook_position_start[0].name)] = grad.detach()
elif hook.name == output_hook_name(hook_position_start[0].name):
# we have: output = recon + stop_grad(error_term)
# so, the TRUE error_grad (if not stop_grad) is output_grad
# due to: output = recon + error_term
if self.use_error_term:
# only store the gradient at the start position
bwd_cache[error_term_name(hook_position_start[0].name)] = grad.detach()
# IMPORTANT NOTE for reproducibility:
# we zero grad of intermediate components
# but zero grad the output hook of SAE will ALSO ZERO GRAD the resid mid / post --> no downstream grads
# so, we instead zero grad of the input hook of SAE
elif hook.name == input_hook_name(sae_name):
if hook.name != input_hook_name(hook_position_end[0].name):
grad.zero_()
def hook_sae_fwd(act: Tensor, hook: HookPoint, to_bwd_cache: Dict, frac: float) -> Tensor:
if hook.name == sae_hook_name(hook_position_end[0].name):
# store activation for backward later
to_bwd_cache[sae_hook_name(hook_position_end[0].name)] = act
elif error_term_name(hook_position_end[0].name) == hook.name and self.use_error_term:
# store activation for backward later
to_bwd_cache[error_term_name(hook_position_end[0].name)] = act
if hook.name == sae_hook_name(hook_position_start[0].name):
# interpolate activation for intergrated gradients
act = interpolate(
corrupt_cache[sae_hook_name(hook_position_start[0].name)],
act,
frac,
)
elif error_term_name(hook_position_start[0].name) == hook.name and self.use_error_term:
# interpolate activation for intergrated gradients
act = interpolate(
corrupt_cache[error_term_name(hook_position_start[0].name)],
act,
frac,
)
return act
d_sae_end = self.dict_saes[hook_position_end[0].name].cfg.d_sae
d_sae_start = self.dict_saes[hook_position_start[0].name].cfg.d_sae
edge_effect = OrderedDict()
with t.set_grad_enabled(True):
with self._detach_error_term(False, hook_position_end[0].name):
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
for step in range(steps):
frac = step / steps
to_bwd_cache = {}
bwd_cache = {}
with self.model.hooks(
fwd_hooks=[
(lambda name: True, partial(
hook_sae_fwd,
to_bwd_cache=to_bwd_cache,
frac=frac,
))
],
bwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(
hook_sae_bwd,
sae_name=sae_name,
bwd_cache=bwd_cache,
)) for sae_name in self.dict_saes.keys()
],
):
self.model.forward(clean_token, return_type=None, stop_at_layer=layer+1)
aggregate_dim = [0] if self.token_wise else [0, 1]
to_bwd = ( # (seq, d_sae+1) || (d_sae+1)
cache_to_sparseact(
to_bwd_cache,
sae_hook_name(hook_position_end[0].name),
error_term_name(hook_position_end[0].name) if self.use_error_term else None,
) @ leftvec.detach()
).sum(aggregate_dim).to_tensor()
del to_bwd_cache
for active_idx, (end_node, end_index) in enumerate(self.active_nodes(*hook_position_end)):
if isinstance(end_index, ErrorIndex):
# the last index is error: shape (d_sae+1) so last index is d_sae
to_bwd[end_index.idx + (d_sae_end,)].backward(retain_graph=True)
index = t.tensor(list(end_index.idx + (d_sae_end,)), device=self.device)
elif isinstance(end_index, FeatureIndex):
to_bwd[end_index.idx].backward(retain_graph=True)
index = t.tensor(list(end_index.idx), device=self.device)
else:
raise ValueError(f"end_index of type {type(end_index)} is not supported.")
'''
edge_effect shape (seq, d_sae+1, seq, d_sae+1) or (d_sae+1, d_sae+1) in sparse_coo tensor
the sparse_coo will have the shape:
--> indices of shape (2, num_active) or (1, num_active)
--> values of shape (num_active, seq, d_sae+1) or (num_active, d_sae+1)
'''
if active_idx not in edge_effect:
edge_effect[active_idx] = (
index,
( # (seq, d_sae+1) || (d_sae+1)
cache_to_sparseact(
bwd_cache,
sae_hook_name(hook_position_start[0].name),
error_term_name(hook_position_start[0].name) if self.use_error_term else None,
) @ rightvec
).sum(aggregate_dim).to_tensor()
)
else:
# accumulate the gradients
prev_index, prev_value = edge_effect[active_idx]
edge_effect[active_idx] = (
prev_index,
prev_value + ( # (seq, d_sae+1) || (d_sae+1)
cache_to_sparseact(
bwd_cache,
sae_hook_name(hook_position_start[0].name),
error_term_name(hook_position_start[0].name) if self.use_error_term else None,
) @ rightvec
).sum(aggregate_dim).to_tensor()
)
del bwd_cache
# average the gradients
for active_idx, (prev_index, prev_value) in edge_effect.items():
edge_effect[active_idx] = (
prev_index,
prev_value / steps
)
seq = int(self.seq_length) # type: ignore
num_end = d_sae_end
num_start = d_sae_start
if self.use_error_term:
num_end += 1
num_start += 1
if len(edge_effect.keys()) != 0:
indices = t.stack([val[0] for val in edge_effect.values()], dim=0).T # shape (2, num_active) or (1, num_active)
values = t.stack([val[1] for val in edge_effect.values()], dim=0) # shape (num_active, seq, d_sae+1) or (num_active, d_sae+1)
# if no active nodes, return empty tensor
else:
indices = t.empty((2, 0) if self.token_wise else (1, 0), dtype=t.long).to(self.device)
values = t.empty((0, seq, num_start) if self.token_wise else (0, num_start), dtype=t.float).to(self.device)
if self.token_wise:
return t.sparse_coo_tensor(indices, values, size=(seq, num_end, seq, num_start)).coalesce()
else:
return t.sparse_coo_tensor(indices, values, size=(num_end, num_start)).coalesce()
def _prune_nodes(
self,
node_effect: Dict[Tuple[Node, Index], SparseAct],
verbose: bool = False,
**kwargs,
) -> None:
if kwargs.get("node_threshold", None) is None:
raise ValueError("Please provide the node_threshold")
else:
node_threshold = kwargs.get("node_threshold")
assert isinstance(node_threshold, (float, int, Tensor)), "node_threshold must be a int, float, or Tensor"
for node, index in tqdm(node_effect.keys(), disable=not verbose):
if kwargs.get("reverse_prune_node", False):
effect_feat_mask = node_effect[(node, index)].act.abs() < node_threshold
else:
effect_feat_mask = node_effect[(node, index)].act.abs() > node_threshold
if verbose:
num_pruned = (~effect_feat_mask).sum().item()
print(f"{(node, index)}: pruned ({num_pruned / effect_feat_mask.numel() * 100:.5f}%) features")
if self.use_error_term:
if kwargs.get("reverse_prune_node", False):
effect_error_mask = node_effect[(node, index)].resc.abs() < node_threshold # type: ignore
else:
effect_error_mask = node_effect[(node, index)].resc.abs() > node_threshold # type: ignore
if verbose:
num_pruned = (~effect_error_mask).sum().item()
print(f"{(node, index)}: pruned ({num_pruned / effect_error_mask.numel() * 100:.5f}%) errors")
# replace the nodes with mask to prune
mask = SparseAct(
act=effect_feat_mask,
resc=effect_error_mask if self.use_error_term else None, # type: ignore
)
self.nodes[(node, index)] = self.nodes[(node, index)] * mask
def model_setup(self):
pass
def run_model(
self,
toks: Tensor,
use_error_term: bool | None = None,
) -> Tuple[Tensor, ActivationCache]:
return self.model.run_with_cache_with_saes( # type: ignore
toks,
saes=self._saes_to_list(),
use_error_term=self.use_error_term if use_error_term is None else use_error_term,
names_filter=lambda name: "sae" in name,
)
def _saes_to_list(self) -> List[Any]:
return [sae for _, sae in self.dict_saes.items()]
@contextmanager
def _detach_error_term(self, detach: bool, sae_name: str | None = None):
orig_detach_error_term = {}
orig_disable_error_grad = {}
try:
for name, sae in self.dict_saes.items():
if sae_name is None or sae_name == name:
orig_detach_error_term[name] = sae.detach_error_term
sae.detach_error_term = detach
else:
orig_detach_error_term[name] = sae.detach_error_term
sae.detach_error_term = True # default detach error term
orig_disable_error_grad[name] = sae.disable_error_grad
sae.disable_error_grad = False # allow grad flows through error hook
yield
finally:
for name, sae in self.dict_saes.items():
sae.detach_error_term = orig_detach_error_term[name]
sae.disable_error_grad = orig_disable_error_grad[name]
class ESAE_FG(Feature_Graph):
def __init__(
self,
model: HookedSAETransformer,
saes: Dict[int, List[Tuple[str, Any]]],
esaes: Dict[int, List[Tuple[str, Any]]],
use_esae_error_term: bool = False,
) -> None:
super().__init__(model, saes, use_error_term=True)
self.esaes = esaes
self.dict_esaes = self.extract_saes(esaes)
self.use_esae_error_term = use_esae_error_term
self._check_valid_esaes()
def _build_nodes(self, seq_length: int, token_wise: bool) -> None:
self.seq_length = seq_length
self.token_wise = token_wise
for sae_name, sae in self.dict_saes.items():
node_shape = (self.seq_length, sae.cfg.d_sae)
esae = self.dict_esaes[sae_name]
error_shape = (self.seq_length, esae.cfg.d_sae)
self.nodes[(ConnectionNode(sae_name), ConnectionIndex())] = SparseAct(
t.ones(node_shape, requires_grad=False).to(self.device),
t.ones(error_shape, requires_grad=False).to(self.device) if self.use_error_term else None,
t.ones(self.seq_length, requires_grad=False).to(self.device) if self.use_esae_error_term else None,
)
self.node_scores[(ConnectionNode(sae_name), ConnectionIndex())] = SparseAct(
t.zeros(node_shape, requires_grad=False).to(self.device),
t.zeros(error_shape, requires_grad=False).to(self.device) if self.use_error_term else None,
t.zeros(self.seq_length, requires_grad=False).to(self.device) if self.use_esae_error_term else None,
)
def _check_error_feature_idx(self, error_idx: Tuple | List) -> None:
if self.token_wise:
assert len(error_idx) == 2, "Please provide the correct index"
else:
assert len(error_idx) == 1, "Please provide the correct index"
def _active_nodes(
self,
sae_name: Node,
node_idx: Index,
reverse: bool = False,
) -> Tuple[List, ...]:
self._check_graph()
if self.token_wise:
node = self.nodes[(sae_name, node_idx)] # act: (seq, d_sae), resc: (seq, d_esae)
else:
node = self.nodes[(sae_name, node_idx)].mean(dim=0) # act: (d_sae), resc: (d_esae)
if reverse:
active_node = (node.act == 0).nonzero().tolist()
active_feature_error = (node.res == 0).nonzero().tolist() if self.use_error_term else [] # type: ignore
active_error = (node.resc == 0).nonzero().tolist() if self.use_esae_error_term else [] # type: ignore
else:
active_node = node.act.nonzero().tolist()
active_feature_error = node.res.nonzero().tolist() if self.use_error_term else [] # type: ignore
active_error = node.resc.nonzero().tolist() if self.use_esae_error_term else [] # type: ignore
return active_node, active_feature_error, active_error
def active_nodes(
self,
sae_name: Node,
node_idx: Index,
reverse: bool = False,
) -> List[Tuple[Node, Index]]:
active_node, active_feature_error, active_error = self._active_nodes(sae_name, node_idx, reverse)
feat_list = [
(sae_name, FeatureIndex(idx))
for idx in active_node
]
feat_error_list = [
(sae_name, FeatureErrorIndex(idx))
for idx in active_feature_error
]
error_list = [
(sae_name, ErrorIndex(idx))
for idx in active_error
]
return feat_list + feat_error_list + error_list # type: ignore
def _check_node_shape(self, sae_name: Node, sparseact: SparseAct):
try:
if self.token_wise:
assert sparseact.act.shape == t.Size([self.seq_length, self.dict_saes[sae_name.name].cfg.d_sae]) # type: ignore
else:
assert sparseact.act.shape == t.Size([self.dict_saes[sae_name.name].cfg.d_sae])
if self.use_error_term:
if self.token_wise:
assert sparseact.res.shape == t.Size([self.seq_length, self.dict_esaes[sae_name.name].cfg.d_sae]) # type: ignore
else:
assert sparseact.res.shape == t.Size([self.dict_esaes[sae_name.name].cfg.d_sae]) # type: ignore
if self.use_esae_error_term:
if self.token_wise:
assert sparseact.resc.shape == t.Size([self.seq_length]) # type: ignore
else:
assert sparseact.resc.numel() == 1 # type: ignore
except:
raise ValueError("Wrong input shape for nodes.")
def update_node(
self,
sae_name: Node,
node_idx: Index,
value_and_mask: Tuple[SparseAct, SparseAct],
) -> None:
self._check_graph()
value, mask = value_and_mask
assert isinstance(value, SparseAct), "value is not an instance of SparseAct"
assert isinstance(mask, SparseAct), "mask is not an instance of SparseAct"
self._check_node_shape(sae_name, value)
if not self.token_wise:
# convert to the right format of (seq, d_sae) and (seq)
value_act = einops.repeat(value.act, 'd_sae -> seq d_sae', seq=self.seq_length)
mask_act = einops.repeat(mask.act, 'd_sae -> seq d_sae', seq=self.seq_length)
value_res = einops.repeat(value.res, 'd_esae -> seq d_esae', seq=self.seq_length) if self.use_error_term else None
mask_res = einops.repeat(mask.res, 'd_esae -> seq d_esae', seq=self.seq_length) if self.use_error_term else None
value_resc = einops.repeat(value.resc, ' -> seq', seq=self.seq_length) if self.use_esae_error_term else None
mask_resc = einops.repeat(mask.resc, ' -> seq', seq=self.seq_length) if self.use_esae_error_term else None
value = SparseAct(value_act, value_res, value_resc)
mask = SparseAct(mask_act, mask_res, mask_resc)
self.nodes[(sae_name, node_idx)] = mask.to(t.float32)
self.node_scores[(sae_name, node_idx)] = value
def find_deleted_nodes(self, reverse = False) -> List[Tuple[Node, Index]]:
self._check_graph()
all_list = []
for sae_name, node_idx in self.nodes.keys():
inactive_node, inactive_feature_error, inactive_error = self._active_nodes(sae_name, node_idx, not reverse)
feat_list = [
(sae_name, FeatureIndex(idx))
for idx in inactive_node
]
feat_error_list = [
(sae_name, FeatureErrorIndex(idx))
for idx in inactive_feature_error
]
error_list = [
(sae_name, ErrorIndex(idx))
for idx in inactive_error
]
all_list += feat_list + feat_error_list + error_list
return all_list
def find_deleted_edges(self, reverse = False) -> List[Tuple[Node, Index, Node, Index]]:
self._check_graph()
all_list = []
for end_node, end_idx in self.edges.keys():
for start_node, start_idx in self.edges[(end_node, end_idx)].keys():
edge = self.edges[(end_node, end_idx)][(start_node, start_idx)]
if not reverse:
inactive_node = (edge.values() == 0) # (num_active, seq, d_sae+d_esae+1) or (num_active, d_sae+d_esae+1)
else:
inactive_node = edge.values()
d_sae_end = self.dict_saes[end_node.name].cfg.d_sae
d_esae_end = self.dict_esaes[end_node.name].cfg.d_sae
d_sae_start = self.dict_saes[start_node.name].cfg.d_sae
d_esae_start = self.dict_esaes[start_node.name].cfg.d_sae
active_idx = [index for _, index in self.active_nodes(start_node, start_idx)]
revised_active_nodes = []
for index in active_idx:
if isinstance(index, FeatureIndex):
revised_active_nodes.append(index.idx)
elif isinstance(index, FeatureErrorIndex):
revised_index = list(index.idx)
revised_index[-1] += d_sae_start
revised_active_nodes.append(tuple(revised_index))
elif isinstance(index, ErrorIndex):
revised_active_nodes.append(index.idx + (d_sae_start + d_esae_start,))
for num_active_idx in range(edge.indices().shape[1]):
end_node_idx = edge.indices()[:, num_active_idx].tolist()
# check if the end_node_idx is the error term
if self.use_esae_error_term and end_node_idx[-1] == d_sae_end + d_esae_end:
end_index = ErrorIndex(end_node_idx[:-1])
elif self.use_error_term and end_node_idx[-1] == d_sae_end:
end_index = FeatureErrorIndex(end_node_idx)
else:
end_index = FeatureIndex(end_node_idx)
for i, idx in enumerate(revised_active_nodes):
if inactive_node[(num_active_idx,) + idx] > 0:
all_list.append(
(
start_node,
active_idx[i],
end_node,
end_index,
)
)
return all_list
def add_single_feature_error(
self,
sae_name: Node,
node_idx: Index,
feat_error_idx: Tuple[int, ...] | List[int] | FeatureErrorIndex,
) -> None:
self._check_graph()
self._set_error_feature_value(sae_name, node_idx, feat_error_idx, 1)
def delete_single_feature_error(
self,
sae_name: Node,
node_idx: Index,
feat_error_idx: Tuple[int, ...] | List[int] | FeatureErrorIndex,
) -> None:
self._check_graph()
self._set_error_feature_value(sae_name, node_idx, feat_error_idx, 0)
def update_single_feature_error(
self,
sae_name: Node,
node_idx: Index,
feat_error_idx: Tuple[int, ...] | List[int] | FeatureErrorIndex,
value: int | float | Tensor,
) -> None:
self._check_graph()
assert isinstance(value, (int, float, Tensor)), "The value must be int, float or Tensor."
self._set_error_feature_value(sae_name, node_idx, feat_error_idx, value)
def _set_error_feature_value(
self,
sae_name: Node,
node_idx: Index,
error_feat_idx: Tuple[int, ...] | List[int] | FeatureErrorIndex,
value: int | float | Tensor,
) -> None:
if not self.use_error_term: # nothing to delete
return
if isinstance(error_feat_idx, (tuple, list)):
self._check_error_feature_idx(error_feat_idx)
self.nodes[(sae_name, node_idx)].res[return_idx(error_feat_idx)] = value # type: ignore
elif isinstance(error_feat_idx, FeatureErrorIndex):
self.nodes[(sae_name, node_idx)].res[error_feat_idx.as_index] = value # type: ignore
else:
raise ValueError(f"error_feat_idx of type {type(error_feat_idx)} is not supported.")
def forward(
self,
clean_token: Tensor,
corrupt_cache: ActivationCache | Dict[str, Tensor] | None,
patch_deleted_comp: bool = False,
**kwargs,
) -> Tuple[Tensor, Dict[str, SparseAct]]:
'''
Forward pass of the graph with clean tokens, if the edge exists, replace the activation with corrupted activation
'''
self._check_graph()
self.model.reset_hooks()
self.model_setup()
fwd_cache = {}
def hook_sae_fwd(act: Tensor, hook: HookPoint, sae_name: str) -> Tensor:
if hook.name == sae_hook_name(sae_name):
if patch_deleted_comp and corrupt_cache is not None:
act_mask = self.nodes[(sae_name, (None,))].act == 0 # type: ignore
act[:, act_mask] = corrupt_cache[sae_hook_name(sae_name)][:, act_mask]
fwd_cache[sae_hook_name(sae_name)] = act.detach()
elif hook.name == sae_hook_name(error_term_name(sae_name)) and self.use_error_term:
if patch_deleted_comp and corrupt_cache is not None:
res_mask = self.nodes[(sae_name, (None,))].res == 0 # type: ignore
act[:, res_mask] = corrupt_cache[sae_hook_name(error_term_name(sae_name))][:, res_mask]
fwd_cache[sae_hook_name(error_term_name(sae_name))] = act.detach()
elif error_term_name(error_term_name(sae_name)) == hook.name and self.use_esae_error_term:
if patch_deleted_comp and corrupt_cache is not None:
resc_mask: Tensor = self.nodes[(sae_name, (None,))].resc == 0 # type: ignore
act[:, resc_mask] = corrupt_cache[error_term_name(error_term_name(sae_name))][:, resc_mask].detach()
fwd_cache[error_term_name(error_term_name(sae_name))] = act.detach()
return act
with t.no_grad():
with self._hook_esaes_to_saes():
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
with self.model.hooks(
fwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(hook_sae_fwd, sae_name=sae_name))
for sae_name in self.dict_saes.keys()
]
):
logits = self.model(clean_token)
cache = {}
for sae_name in self.dict_saes.keys():
cache[sae_name] = SparseAct(
act=fwd_cache[sae_hook_name(sae_name)],
res=fwd_cache[sae_hook_name(error_term_name(sae_name))] if self.use_error_term else None,
resc=fwd_cache[error_term_name(error_term_name(sae_name))] if self.use_esae_error_term else None,
)
for sae in self.dict_saes.values():
sae.reset_hooks()
self.model.reset_hooks()
return logits, cache
def _attrib_effect_node(
self,
grads: Dict,
corrupt_cache: ActivationCache | Dict[str, Tensor],
clean_cache: Dict[str, SparseAct],
) -> Dict:
attrib_effect = {}
aggregate_dim = [0] if self.token_wise else [0, 1]
for (node, index), grad in grads.items():
corrupt_sparse_act = cache_to_sparseact(
corrupt_cache,
sae_hook_name(node.name),
sae_hook_name(error_term_name(node.name)) if self.use_error_term else None,
error_term_name(error_term_name(node.name)) if self.use_esae_error_term else None,
)
attrib_effect[(node, index)] = ( # act: (seq, d_sae), res: (seq, d_esae), resc: (seq, d_model) || act: (d_sae), res: (d_esae), resc: (d_model)
grad * # this is NOT MATMUL, elementwise because the sparseact.res are now features
(corrupt_sparse_act - clean_cache[node.name])
).sum(aggregate_dim)
if self.use_esae_error_term:
attrib_effect[(node, index)].contract() # resc: (seq) || resc: ()
return attrib_effect
def _gradient_wrt_nodes(
self,
clean_token: Tensor,
metric: Callable[[Tensor], Tensor],
retain_graph: bool = False,
pass_through_grad: bool = False,
verbose: bool = False,
**kwargs,
) -> Tuple[
Dict[Tuple[Node, Index], SparseAct], # node effects
Dict[str, SparseAct]
]:
'''
Forward pass of the graph with clean tokens, if the edge exists, replace the activation with corrupted activation
Backward pass on the graph wrt the metric
Return the gradients wrt nodes, edges, and activation cache
'''
self._check_graph()
self.model_setup()
self.model.reset_hooks()
for _, sae in self.dict_saes.items():
sae.reset_hooks()
bwd_cache = {}
pass_through_cache = {}
def hook_sae_bwd(grad: Tensor, hook: HookPoint, sae_name: str) -> None:
if hook.name == sae_hook_name(sae_name):
bwd_cache[sae_hook_name(sae_name)] = grad.detach()
elif hook.name == output_hook_name(sae_name):
if pass_through_grad:
pass_through_cache[output_hook_name(sae_name)] = grad.detach()
elif sae_hook_name(error_term_name(sae_name)) == hook.name and self.use_error_term:
bwd_cache[sae_hook_name(error_term_name(sae_name))] = grad.detach()
elif output_hook_name(error_term_name(sae_name)) == hook.name and self.use_esae_error_term:
# the error_grad is the output_grad, due to: output = recon + error_term
bwd_cache[error_term_name(error_term_name(sae_name))] = grad.detach()
elif hook.name == input_hook_name(sae_name):
if pass_through_grad:
# we have to modify inplace instead of grad = ... and then return grad
# because, returning a tensor in bwd pass hook is buggy somehow
grad.copy_(pass_through_cache[output_hook_name(sae_name)])
fwd_cache = {}
def hook_sae_fwd(act: Tensor, hook: HookPoint, sae_name: str) -> Tensor:# cache the feature post activation
if hook.name == sae_hook_name(sae_name):
fwd_cache[sae_hook_name(sae_name)] = act.detach()
# modify the error of the sae
elif sae_hook_name(error_term_name(sae_name)) == hook.name and self.use_error_term:
fwd_cache[sae_hook_name(error_term_name(sae_name))] = act.detach()
elif error_term_name(error_term_name(sae_name)) == hook.name and self.use_esae_error_term:
fwd_cache[error_term_name(error_term_name(sae_name))] = act.detach()
return act
with t.set_grad_enabled(True):
with self._detach_error_term(True):
with self._hook_esaes_to_saes():
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
with self.model.hooks(
fwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(hook_sae_fwd, sae_name=sae_name))
for sae_name in self.dict_saes.keys()
],
bwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(hook_sae_bwd, sae_name=sae_name))
for sae_name in self.dict_saes.keys()
],
):
metric(self.model(clean_token)).backward(retain_graph=retain_graph)
node_grads = {}
for node, index in self.nodes.keys():
node_grads[(node, index)] = cache_to_sparseact(
bwd_cache,
sae_hook_name(node.name),
sae_hook_name(error_term_name(node.name)) if self.use_error_term else None,
error_term_name(error_term_name(node.name)) if self.use_esae_error_term else None,
)
cache = {}
for sae_name in self.dict_saes.keys():
cache[sae_name] = cache_to_sparseact(
fwd_cache,
sae_hook_name(sae_name),
sae_hook_name(error_term_name(sae_name)) if self.use_error_term else None,
error_term_name(error_term_name(sae_name)) if self.use_esae_error_term else None,
)
self.model.reset_hooks()
for sae in self.dict_saes.values():
sae.reset_hooks()
return node_grads, cache
def _gradient_wrt_nodes_ig(
self,
clean_token: Tensor,
corrupt_cache: ActivationCache | Dict[str, Tensor],
metric: Callable[[Tensor], Tensor],
retain_graph: bool = False,
verbose: bool = False,
**kwargs,
) -> Tuple[
Dict[Tuple[Node, Index], SparseAct], # node effects
Dict[str, SparseAct]
]:
steps = kwargs.get("steps", 10)
self._check_graph()
self.model_setup()
self.model.reset_hooks()
for _, sae in self.dict_saes.items():
sae.reset_hooks()
bwd_cache = {}
def hook_sae_bwd(grad: Tensor, hook: HookPoint, sae_name: str) -> None:
if hook.name == sae_hook_name(sae_name):
create_list(bwd_cache, sae_hook_name(sae_name))
bwd_cache[sae_hook_name(sae_name)] += grad.detach()
elif sae_hook_name(error_term_name(sae_name)) == hook.name and self.use_error_term:
create_list(bwd_cache, sae_hook_name(error_term_name(sae_name)))
bwd_cache[sae_hook_name(error_term_name(sae_name))] += grad.detach()
elif output_hook_name(error_term_name(sae_name)) == hook.name and self.use_esae_error_term:
# the error_grad is the output_grad, due to: output = recon + error_term
create_list(bwd_cache, error_term_name(error_term_name(sae_name)))
bwd_cache[error_term_name(error_term_name(sae_name))] += grad.detach()
fwd_cache = {}
def hook_sae_fwd(act: Tensor, hook: HookPoint, sae_name: str, target_name: str, frac: float) -> Tensor:
# cache the feature post activation
if hook.name == sae_hook_name(sae_name):
# interpolate for integrated gradients
if hook.name == sae_hook_name(target_name):
act = interpolate(
corrupt_cache[sae_hook_name(sae_name)],
act,
frac,
)
fwd_cache[sae_hook_name(sae_name)] = act.detach()
# modify the error of the sae
elif sae_hook_name(error_term_name(sae_name)) == hook.name and self.use_error_term:
# interpolate for integrated gradients
if hook.name == sae_hook_name(error_term_name(target_name)):
act = interpolate(
corrupt_cache[sae_hook_name(error_term_name(sae_name))],
act,
frac,
)
fwd_cache[sae_hook_name(error_term_name(sae_name))] = act.detach()
elif error_term_name(error_term_name(sae_name)) == hook.name and self.use_esae_error_term:
# interpolate for integrated gradients
if hook.name == error_term_name(error_term_name(target_name)):
act = interpolate(
corrupt_cache[error_term_name(error_term_name(sae_name))],
act,
frac,
)
fwd_cache[error_term_name(error_term_name(sae_name))] = act.detach()
return act
with t.set_grad_enabled(True):
with self._detach_error_term(True):
with self._hook_esaes_to_saes():
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
for target_name in self.dict_saes.keys():
for step in range(steps):
frac = step / steps
with self.model.hooks(
fwd_hooks=[
(
lambda name, sae_name=sae_name: sae_name in name,
partial(hook_sae_fwd, sae_name=sae_name, target_name=target_name, frac=frac)
) for sae_name in self.dict_saes.keys()
],
bwd_hooks=[
(
lambda name, target_name=target_name: target_name in name,
partial(hook_sae_bwd, sae_name=target_name)
)
],
):
metric(self.model(clean_token)).backward(retain_graph=retain_graph)
# average the gradients
for key in bwd_cache.keys():
bwd_cache[key] /= steps
node_grads = {}
for node, index in self.nodes.keys():
node_grads[(node, index)] = cache_to_sparseact(
bwd_cache,
sae_hook_name(node.name),
sae_hook_name(error_term_name(node.name)) if self.use_error_term else None,
error_term_name(error_term_name(node.name)) if self.use_esae_error_term else None,
)
cache = {}
for sae_name in self.dict_saes.keys():
cache[sae_name] = cache_to_sparseact(
fwd_cache,
sae_hook_name(sae_name),
sae_hook_name(error_term_name(sae_name)) if self.use_error_term else None,
error_term_name(error_term_name(sae_name)) if self.use_esae_error_term else None,
)
self.model.reset_hooks()
for sae in self.dict_saes.values():
sae.reset_hooks()
return node_grads, cache
def _gradient_wrt_edges(
self,
clean_token: Tensor,
corrupt_cache: ActivationCache | Dict[str, Tensor],
node_grads: Dict[Tuple[Node, Index], SparseAct],
verbose: bool = False,
**kwargs,
) -> Tuple[
Dict[Tuple[Node, Index, Node, Index], Tensor], # edge effects
Dict[str, SparseAct]
]:
self._check_graph()
self.model_setup()
self.model.reset_hooks()
for _, sae in self.dict_saes.items():
sae.reset_hooks()
gradient_mode = kwargs.get('edge_gradient_mode', 'gradient')
_, clean_cache = self.forward(clean_token, corrupt_cache=None)
edge_grads: Dict[Tuple[Node, Index, Node, Index], Tensor] = {}
for layer, connection in tqdm(self.connection.items(), disable=not verbose):
if verbose:
print(f"Layer {layer}:")
for hook_position_end, list_hook_positions_start in tqdm(connection.items(), disable=not verbose):
assert hook_position_end in node_grads, f"Node gradient of {hook_position_end} is not provided."
for hook_position_start in list_hook_positions_start:
corrupt_sparse_act = cache_to_sparseact(
corrupt_cache,
sae_hook_name(hook_position_start[0].name),
sae_hook_name(error_term_name(hook_position_start[0].name)) if self.use_error_term else None,
error_term_name(error_term_name(hook_position_start[0].name)) if self.use_esae_error_term else None,
)
right_vec = corrupt_sparse_act - clean_cache[hook_position_start[0].name]
if gradient_mode == "gradient":
edge_grads[hook_position_start + hook_position_end] = self._edge_attribution(
clean_token,
hook_position_end,
hook_position_start,
node_grads[hook_position_end],
right_vec,
layer,
**kwargs,
)
elif gradient_mode == "ig":
edge_grads[hook_position_start + hook_position_end] = self._edge_attribution_ig(
clean_token,
hook_position_end,
hook_position_start,
node_grads[hook_position_end],
right_vec,
layer,
**kwargs,
)
else:
raise NotImplementedError(f"gradient_mode {gradient_mode} is not supported")
return edge_grads, clean_cache
def _edge_attribution(
self,
clean_token: Tensor,
hook_position_end: Tuple[Node, Index],
hook_position_start: Tuple[Node, Index],
leftvec: SparseAct,
rightvec: SparseAct,
layer: int,
**kwargs,
) -> Tensor:
def hook_sae_bwd(grad: Tensor, hook: HookPoint, sae_name: str, bwd_cache: Dict) -> None:
if hook.name == sae_hook_name(hook_position_start[0].name):
# only store the gradient at the start position
bwd_cache[sae_hook_name(hook_position_start[0].name)] = grad.detach()
elif sae_hook_name(error_term_name(hook_position_start[0].name)) == hook.name and self.use_error_term:
# only store the gradient at the start position
bwd_cache[sae_hook_name(error_term_name(hook_position_start[0].name))] = grad.detach()
elif output_hook_name(error_term_name(hook_position_start[0].name)) == hook.name and self.use_esae_error_term:
# only store the gradient at the start position
# the error_grad is the output_grad, due to: output = recon + error_term
bwd_cache[error_term_name(error_term_name(hook_position_start[0].name))] = grad.detach()
# IMPORTANT NOTE for reproducibility:
# we zero grad of intermediate components
# but zero grad the output hook of SAE will ALSO ZERO GRAD the resid mid / post --> no downstream grads
# so, we instead zero grad of the input hook of SAE
elif hook.name == input_hook_name(sae_name):
if hook.name != input_hook_name(hook_position_end[0].name):
grad.zero_()
def hook_sae_fwd(act: Tensor, hook: HookPoint, to_bwd_cache: Dict) -> Tensor:
# cache the feature of SAE post activation
if hook.name == sae_hook_name(hook_position_end[0].name):
# store activation for backward later
to_bwd_cache[sae_hook_name(hook_position_end[0].name)] = act
# cache the feature of ESAE post activation
elif hook.name == sae_hook_name(error_term_name(hook_position_end[0].name)):
# store activation for backward later
to_bwd_cache[sae_hook_name(error_term_name(hook_position_end[0].name))] = act
elif error_term_name(error_term_name(hook_position_end[0].name)) == hook.name and self.use_esae_error_term:
to_bwd_cache[error_term_name(error_term_name(hook_position_end[0].name))] = act
return act
d_sae_end = self.dict_saes[hook_position_end[0].name].cfg.d_sae
d_esae_end = self.dict_esaes[hook_position_end[0].name].cfg.d_sae
d_sae_start = self.dict_saes[hook_position_start[0].name].cfg.d_sae
d_esae_start = self.dict_esaes[hook_position_start[0].name].cfg.d_sae
to_bwd_cache = {}
bwd_cache = {}
edge_effect = OrderedDict()
with t.set_grad_enabled(True):
with self._detach_error_term(False, hook_position_end[0].name):
with self._hook_esaes_to_saes():
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
with self.model.hooks(
fwd_hooks=[
(lambda name: True, partial(
hook_sae_fwd,
to_bwd_cache=to_bwd_cache,
))
],
bwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(
hook_sae_bwd,
sae_name=sae_name,
bwd_cache=bwd_cache,
)) for sae_name in self.dict_saes.keys()
],
):
self.model.forward(clean_token, return_type=None, stop_at_layer=layer+1)
aggregate_dim = [0] if self.token_wise else [0, 1]
to_bwd = (
cache_to_sparseact(
to_bwd_cache,
sae_hook_name(hook_position_end[0].name),
sae_hook_name(error_term_name(hook_position_end[0].name)) if self.use_error_term else None,
error_term_name(error_term_name(hook_position_end[0].name)) if self.use_esae_error_term else None,
) * leftvec.detach()
).sum(aggregate_dim)
if self.use_esae_error_term:
to_bwd = to_bwd.contract()
to_bwd = to_bwd.to_tensor() # (seq, d_sae+d_esae+1) || (d_sae+d_esae+1)
del to_bwd_cache
for active_idx, (end_node, end_index) in enumerate(self.active_nodes(*hook_position_end)):
if isinstance(end_index, ErrorIndex):
# the last index is error: shape (d_sae+d_esae+1) so last index is d_sae+d_esae
to_bwd[end_index.idx + (d_sae_end+d_esae_end,)].backward(retain_graph=True)
index = t.tensor(list(end_index.idx + (d_sae_end+d_esae_end,)), device=self.device)
elif isinstance(end_index, FeatureErrorIndex):
revised_index = list(end_index.idx)
revised_index[-1] += d_sae_end
to_bwd[tuple(revised_index)].backward(retain_graph=True)
index = t.tensor(revised_index, device=self.device)
elif isinstance(end_index, FeatureIndex):
to_bwd[end_index.idx].backward(retain_graph=True)
index = t.tensor(list(end_index.idx), device=self.device)
else:
raise ValueError(f"end_index of type {type(end_index)} is not supported.")
'''
edge_effect shape (seq, d_sae+d_esae+1, seq, d_sae+d_esae+1) or (d_sae+d_esae+1, d_sae+d_esae+1) in sparse_coo tensor
the sparse_coo will have the shape:
--> indices of shape (2, num_active) or (1, num_active)
--> values of shape (num_active, seq, d_sae+d_esae+1) or (num_active, d_sae+d_esae+1)
'''
effect = (
cache_to_sparseact(
bwd_cache,
sae_hook_name(hook_position_start[0].name),
sae_hook_name(error_term_name(hook_position_start[0].name)) if self.use_error_term else None,
error_term_name(error_term_name(hook_position_start[0].name)) if self.use_esae_error_term else None,
) * rightvec
).sum(aggregate_dim)
if self.use_esae_error_term:
effect.contract()
edge_effect[active_idx] = (index, effect.to_tensor()) # (seq, d_sae+d_esae+1) || (d_sae+d_esae+1)
del bwd_cache
seq = int(self.seq_length) # type: ignore
num_end = d_sae_end
num_start = d_sae_start
if self.use_error_term:
num_end += d_esae_end
num_start += d_esae_start
if self.use_esae_error_term:
num_end += 1
num_start += 1
if len(edge_effect.keys()) != 0:
indices = t.stack([val[0] for val in edge_effect.values()], dim=0).T # shape (2, num_active) or (1, num_active)
values = t.stack([val[1] for val in edge_effect.values()], dim=0) # shape (num_active, seq, d_sae+d_esae+1) or (num_active, d_sae+d_esae+1)
# if no active nodes, return empty tensor
else:
indices = t.empty((2, 0) if self.token_wise else (1, 0), dtype=t.long).to(self.device)
values = t.empty((0, seq, num_start) if self.token_wise else (0, num_start), dtype=t.float).to(self.device)
if self.token_wise:
return t.sparse_coo_tensor(indices, values, size=(seq, num_end, seq, num_start)).coalesce()
else:
return t.sparse_coo_tensor(indices, values, size=(num_end, num_start)).coalesce()
def _edge_attribution_ig(
self,
clean_token: Tensor,
hook_position_end: Tuple[Node, Index],
hook_position_start: Tuple[Node, Index],
leftvec: SparseAct,
rightvec: SparseAct,
layer: int,
**kwargs,
) -> Tensor:
steps = kwargs.get('steps', 10)
def hook_sae_bwd(grad: Tensor, hook: HookPoint, sae_name: str, bwd_cache: Dict) -> None:
if hook.name == sae_hook_name(hook_position_start[0].name):
# only store the gradient at the start position
bwd_cache[sae_hook_name(hook_position_start[0].name)] = grad.detach()
elif sae_hook_name(error_term_name(hook_position_start[0].name)) == hook.name and self.use_error_term:
# only store the gradient at the start position
bwd_cache[sae_hook_name(error_term_name(hook_position_start[0].name))] = grad.detach()
elif output_hook_name(error_term_name(hook_position_start[0].name)) == hook.name and self.use_esae_error_term:
# only store the gradient at the start position
# the error_grad is the output_grad, due to: output = recon + error_term
bwd_cache[error_term_name(error_term_name(hook_position_start[0].name))] = grad.detach()
# IMPORTANT NOTE for reproducibility:
# we zero grad of intermediate components
# but zero grad the output hook of SAE will ALSO ZERO GRAD the resid mid / post --> no downstream grads
# so, we instead zero grad of the input hook of SAE
elif hook.name == input_hook_name(sae_name):
if hook.name != input_hook_name(hook_position_end[0].name):
grad.zero_()
def hook_sae_fwd(act: Tensor, hook: HookPoint, to_bwd_cache: Dict) -> Tensor:
# cache the feature of SAE post activation
if hook.name == sae_hook_name(hook_position_end[0].name):
# store activation for backward later
to_bwd_cache[sae_hook_name(hook_position_end[0].name)] = act
# cache the feature of ESAE post activation
elif hook.name == sae_hook_name(error_term_name(hook_position_end[0].name)):
# store activation for backward later
to_bwd_cache[sae_hook_name(error_term_name(hook_position_end[0].name))] = act
elif error_term_name(error_term_name(hook_position_end[0].name)) == hook.name and self.use_esae_error_term:
to_bwd_cache[error_term_name(error_term_name(hook_position_end[0].name))] = act
return act
d_sae_end = self.dict_saes[hook_position_end[0].name].cfg.d_sae
d_esae_end = self.dict_esaes[hook_position_end[0].name].cfg.d_sae
d_sae_start = self.dict_saes[hook_position_start[0].name].cfg.d_sae
d_esae_start = self.dict_esaes[hook_position_start[0].name].cfg.d_sae
edge_effect = OrderedDict()
with t.set_grad_enabled(True):
with self._detach_error_term(False, hook_position_end[0].name):
with self._hook_esaes_to_saes():
with self.model.saes(saes=self._saes_to_list(), use_error_term=self.use_error_term):
for step in range(steps):
frac = step / steps
to_bwd_cache = {}
bwd_cache = {}
with self.model.hooks(
fwd_hooks=[
(lambda name: True, partial(
hook_sae_fwd,
to_bwd_cache=to_bwd_cache,
))
],
bwd_hooks=[
(lambda name, sae_name=sae_name: sae_name in name, partial(
hook_sae_bwd,
sae_name=sae_name,
bwd_cache=bwd_cache,
)) for sae_name in self.dict_saes.keys()
],
):
self.model.forward(clean_token, return_type=None, stop_at_layer=layer+1)
aggregate_dim = [0] if self.token_wise else [0, 1]
to_bwd = (
cache_to_sparseact(
to_bwd_cache,
sae_hook_name(hook_position_end[0].name),
sae_hook_name(error_term_name(hook_position_end[0].name)) if self.use_error_term else None,
error_term_name(error_term_name(hook_position_end[0].name)) if self.use_esae_error_term else None,
) * leftvec.detach()
).sum(aggregate_dim)
if self.use_esae_error_term:
to_bwd = to_bwd.contract()
to_bwd = to_bwd.to_tensor() # (seq, d_sae+d_esae+1) || (d_sae+d_esae+1)
del to_bwd_cache
for active_idx, (end_node, end_index) in enumerate(self.active_nodes(*hook_position_end)):
if isinstance(end_index, ErrorIndex):
# the last index is error: shape (d_sae+d_esae+1) so last index is d_sae+d_esae
to_bwd[end_index.idx + (d_sae_end+d_esae_end,)].backward(retain_graph=True)
index = t.tensor(list(end_index.idx + (d_sae_end+d_esae_end,)), device=self.device)
elif isinstance(end_index, FeatureErrorIndex):
revised_index = list(end_index.idx)
revised_index[-1] += d_sae_end
to_bwd[tuple(revised_index)].backward(retain_graph=True)
index = t.tensor(revised_index, device=self.device)
elif isinstance(end_index, FeatureIndex):
to_bwd[end_index.idx].backward(retain_graph=True)
index = t.tensor(list(end_index.idx), device=self.device)
else:
raise ValueError(f"end_index of type {type(end_index)} is not supported.")
'''
edge_effect shape (seq, d_sae+d_esae+1, seq, d_sae+d_esae+1) or (d_sae+d_esae+1, d_sae+d_esae+1) in sparse_coo tensor
the sparse_coo will have the shape:
--> indices of shape (2, num_active) or (1, num_active)
--> values of shape (num_active, seq, d_sae+d_esae+1) or (num_active, d_sae+d_esae+1)
'''
effect = (
cache_to_sparseact(
bwd_cache,
sae_hook_name(hook_position_start[0].name),
sae_hook_name(error_term_name(hook_position_start[0].name)) if self.use_error_term else None,
error_term_name(error_term_name(hook_position_start[0].name)) if self.use_esae_error_term else None,
) * rightvec
).sum(aggregate_dim)
if self.use_esae_error_term:
effect.contract()
if active_idx not in edge_effect:
edge_effect[active_idx] = (index, effect.to_tensor()) # (seq, d_sae+d_esae+1) || (d_sae+d_esae+1)
else:
_, existing_effect = edge_effect[active_idx]
edge_effect[active_idx] = (index, existing_effect + effect.to_tensor())
del bwd_cache
# average the gradients
for active_idx, (prev_index, prev_value) in edge_effect.items():
edge_effect[active_idx] = (
prev_index,
prev_value / steps
)
seq = int(self.seq_length) # type: ignore
num_end = d_sae_end
num_start = d_sae_start
if self.use_error_term:
num_end += d_esae_end
num_start += d_esae_start
if self.use_esae_error_term:
num_end += 1
num_start += 1
if len(edge_effect.keys()) != 0:
indices = t.stack([val[0] for val in edge_effect.values()], dim=0).T # shape (2, num_active) or (1, num_active)
values = t.stack([val[1] for val in edge_effect.values()], dim=0) # shape (num_active, seq, d_sae+d_esae+1) or (num_active, d_sae+d_esae+1)
# if no active nodes, return empty tensor
else:
indices = t.empty((2, 0) if self.token_wise else (1, 0), dtype=t.long).to(self.device)
values = t.empty((0, seq, num_start) if self.token_wise else (0, num_start), dtype=t.float).to(self.device)
if self.token_wise:
return t.sparse_coo_tensor(indices, values, size=(seq, num_end, seq, num_start)).coalesce()
else:
return t.sparse_coo_tensor(indices, values, size=(num_end, num_start)).coalesce()
def _prune_nodes(
self,
node_effect: Dict[Tuple[Node, Index], SparseAct],
verbose: bool = False,
**kwargs,
) -> None:
if kwargs.get("node_threshold", None) is None:
raise ValueError("Please provide the node_threshold")
else:
node_threshold = kwargs.get("node_threshold")
assert isinstance(node_threshold, (float, int, Tensor)), "node_threshold must be a int, float, or Tensor"
for node, index in tqdm(node_effect.keys(), disable=not verbose):
if kwargs.get("reverse_prune_node", False):
effect_feat_mask = node_effect[(node, index)].act.abs() < node_threshold
else:
effect_feat_mask = node_effect[(node, index)].act.abs() > node_threshold
if verbose:
num_pruned = (~effect_feat_mask).sum().item()
print(f"{(node, index)}: pruned ({num_pruned / effect_feat_mask.numel() * 100:.5f}%) features")
if self.use_error_term:
if kwargs.get("reverse_prune_node", False):
effect_feat_error_mask = node_effect[(node, index)].res.abs() < node_threshold # type: ignore
else:
effect_feat_error_mask = node_effect[(node, index)].res.abs() > node_threshold # type: ignore
if verbose:
num_pruned = (~effect_feat_error_mask).sum().item()
print(f"{(node, index)}: pruned ({num_pruned / effect_feat_error_mask.numel() * 100:.5f}%) error features")
if self.use_esae_error_term:
if kwargs.get("reverse_prune_node", False):
effect_error_mask = node_effect[(node, index)].resc.abs() < node_threshold # type: ignore
else:
effect_error_mask = node_effect[(node, index)].resc.abs() > node_threshold # type: ignore
if verbose:
num_pruned = (~effect_error_mask).sum().item()
print(f"{(node, index)}: pruned ({num_pruned / effect_error_mask.numel() * 100:.5f}%) errors")
# replace the nodes with mask to prune
mask = SparseAct(
act=effect_feat_mask,
res=effect_feat_error_mask if self.use_error_term else None, # type: ignore
resc=effect_error_mask if self.use_esae_error_term else None, # type: ignore
)
self.nodes[(node, index)] = self.nodes[(node, index)] * mask
def run_model(
self,
toks: Tensor,
use_error_term: bool | None = None
) -> Tuple[Tensor, ActivationCache]:
with self._hook_esaes_to_saes(use_esae_error_term=use_error_term):
out = self.model.run_with_cache_with_saes(
toks,
saes=self._saes_to_list(),
use_error_term=True,
names_filter=lambda name: "sae" in name,
)
return out # type: ignore
def _saes_to_list(self) -> List[Any]:
return [sae for _, sae in self.dict_saes.items()]
def _check_valid_esaes(self):
for hook_name in self.dict_saes.keys():
assert hook_name in self.dict_esaes, f"Hook name {hook_name} is not found in ESAEs."
@contextmanager
def _hook_esaes_to_saes(self, reset_esaes_end: bool = True, reset_saes_error_term: bool = True, use_esae_error_term: bool | None = None):
self._check_valid_esaes()
use_esae_error_term = self.use_esae_error_term if use_esae_error_term is None else use_esae_error_term
orig_use_error_term = {}
try:
for sae_name, sae in self.dict_saes.items():
sae.add_sae(self.dict_esaes[sae_name], use_error_term=use_esae_error_term)
orig_use_error_term[sae_name] = sae.use_error_term
sae.use_error_term = self.use_error_term
yield
finally:
for sae_name, sae in self.dict_saes.items():
if reset_esaes_end:
sae.reset_saes()
if reset_saes_error_term:
sae.use_error_term = orig_use_error_term[sae_name]
@contextmanager
def _detach_error_term(self, detach: bool, sae_name: str | None = None):
orig_detach_error_term = {}
orig_disable_error_grad = {}
orig_detach_esae_error_term = {}
orig_disable_esae_error_grad = {}
def __detach(dict_saes: Dict[str, Any], detach: bool, detach_error_term: Dict, disable_error_grad: Dict, sae_name: str | None = None):
for name, sae in dict_saes.items():
if sae_name is None or sae_name in name:
detach_error_term[name] = sae.detach_error_term
sae.detach_error_term = detach
else:
detach_error_term[name] = sae.detach_error_term
sae.detach_error_term = True # default detach error term
disable_error_grad[name] = sae.disable_error_grad
sae.disable_error_grad = False # allow grad flows through error hook
def __recover(dict_saes: Dict[str, Any], detach_error_term: Dict, disable_error_grad: Dict):
for name, sae in dict_saes.items():
sae.detach_error_term = detach_error_term[name]
sae.disable_error_grad = disable_error_grad[name]
try:
__detach(
self.dict_saes, detach, orig_detach_error_term, orig_disable_error_grad, sae_name
)
__detach(
self.dict_esaes, detach, orig_detach_esae_error_term, orig_disable_esae_error_grad, sae_name
)
yield
finally:
__recover(
self.dict_saes, orig_detach_error_term, orig_disable_error_grad
)
__recover(
self.dict_esaes, orig_detach_esae_error_term, orig_disable_esae_error_grad
)
if __name__ == "__main__":
'''
To debug graph
'''
from sae_lens import SAE
device = t.device("cuda:0" if t.cuda.is_available() else "cpu")
gpt2: HookedSAETransformer = HookedSAETransformer.from_pretrained("gpt2-small", device=device)
list_hook_names = [utils.get_act_name("resid_pre", layer) for layer in range(gpt2.cfg.n_layers)]
dict_saes = {}
list_saes: List[SAE] = []
for layer, hook_name in enumerate(list_hook_names):
gpt2_sae, _, _ = SAE.from_pretrained(
release="gpt2-small-res-jb",
sae_id=hook_name,
device=str(device),
)
dict_saes[layer] = [(hook_name, gpt2_sae)]
list_saes.append(gpt2_sae)
use_error_term = True
clean_data = "hello, my name is T"
corrupt_data = "hi, his name is T"
clean_token = gpt2.to_tokens(clean_data)
corrupt_token = gpt2.to_tokens(corrupt_data)
fg = Feature_Graph(
gpt2,
dict_saes,
use_error_term=use_error_term,
)
fg.build_default_connection(clean_token.shape[1], token_wise=True, inter=True, intra=False)
import random
d_sae = list_saes[0].cfg.d_sae
seq = clean_token.shape[1]
n_layers = gpt2.cfg.n_layers
delete_feats = [
(
ConnectionNode(f"blocks.{random.randint(0, n_layers-1)}.hook_resid_pre"),
ConnectionIndex(),
FeatureIndex((random.randint(0, seq-1), random.randint(0, d_sae-1))),
) for _ in range(5000)
]
delete_errors = [
(
ConnectionNode(f"blocks.{random.randint(0, n_layers-1)}.hook_resid_pre"),
ConnectionIndex(),
ErrorIndex((random.randint(0, seq-1),)),
) for _ in range(3)
]
if use_error_term:
for error in delete_errors:
fg.delete_single_error(*error)
for feat in delete_feats:
fg.delete_single_feature(*feat)
print(fg.active_nodes(ConnectionNode("blocks.0.hook_resid_pre"), ConnectionIndex())[-5])
_, corrupt_cache = gpt2.run_with_cache_with_saes(
corrupt_token,
saes=list_saes,
use_error_term=use_error_term,
names_filter=lambda name: "sae" in name,
)
fg_logit, patched_cache = fg(clean_token, corrupt_cache, patch_deleted_comp=True)
if not use_error_term:
for sae in list_saes:
sae.use_error_term = False
def ablate_sae_latent(
sae_acts: Tensor,
hook: HookPoint,
) -> Tensor:
for sae_name, _, feat_idx in delete_feats:
if hook.name == sae_hook_name(sae_name.name):
sae_acts[ConnectionIndex(return_idx(feat_idx.list_index, 3)).as_index] = corrupt_cache[hook.name][ConnectionIndex(return_idx(feat_idx.list_index, 3)).as_index] # type: ignore
return sae_acts
logit = gpt2.run_with_hooks_with_saes(
clean_token,
saes=list_saes,
fwd_hooks=[(lambda name: "sae" in name, ablate_sae_latent)],
)
else:
for sae in list_saes:
sae.use_error_term = True
def ablate_sae_latent(
sae_acts: Tensor,
hook: HookPoint,
) -> Tensor:
for sae_name, _, feat_idx in delete_feats:
if hook.name == sae_hook_name(sae_name.name):
sae_acts[ConnectionIndex(return_idx(feat_idx.list_index, 3)).as_index] = corrupt_cache[hook.name][ConnectionIndex(return_idx(feat_idx.list_index, 3)).as_index] # type: ignore
for sae_name, _, error_idx in delete_errors:
if hook.name == error_term_name(sae_name.name):
sae_acts[ConnectionIndex(return_idx(error_idx.list_index, 2)).as_index] = corrupt_cache[hook.name][ConnectionIndex(return_idx(error_idx.list_index, 2)).as_index] # type: ignore
return sae_acts
logit = gpt2.run_with_hooks_with_saes(
clean_token,
saes=list_saes,
fwd_hooks=[(lambda name: "sae" in name, ablate_sae_latent)],
)
t.testing.assert_close(logit, fg_logit, rtol=1e-5, atol=1e-5)
# '''
# To debug gradients
# '''
# device = t.device("cuda:0" if t.cuda.is_available() else "cpu")
# gpt2: HookedSAETransformer = HookedSAETransformer.from_pretrained("gpt2-small", device=device)
# list_hook_names = [utils.get_act_name("resid_pre", layer) for layer in range(gpt2.cfg.n_layers)]
# dict_saes = {}
# list_saes = []
# for layer, hook_name in enumerate(list_hook_names):
# gpt2_sae, _, _ = SAE.from_pretrained(
# release="gpt2-small-res-jb",
# sae_id=hook_name,
# device=str(device),
# )
# dict_saes[layer] = [(hook_name, gpt2_sae)]
# list_saes.append(gpt2_sae)
# import random
# from itertools import product
# names = [" John", " Mary"]
# name_tokens = [gpt2.to_single_token(name) for name in names]
# prompt_template = "When{A} and{B} went to the shops,{S} gave the bag to"
# prompts = [
# prompt_template.format(A=names[i], B=names[1 - i], S=names[j]) for i, j in product(range(2), range(2))
# ]
# correct_answers = names[::-1] * 2
# incorrect_answers = names * 2
# correct_toks = gpt2.to_tokens(correct_answers, prepend_bos=False)[:, 0].tolist()
# incorrect_toks = gpt2.to_tokens(incorrect_answers, prepend_bos=False)[:, 0].tolist()
# corrupt_prompts = [
# prompt_template.format(A=names[i], B=names[1 - i], S=names[1 - j]) for i, j in product(range(2), range(2))
# ]
# clean_token = gpt2.to_tokens(prompts)
# corrupt_token = gpt2.to_tokens(corrupt_prompts)
# def logits_to_ave_logit_diff(
# logits: Tensor,
# correct_toks: list[int] = correct_toks,
# incorrect_toks: list[int] = incorrect_toks,
# reduction: str | None = "mean",
# ) -> Tensor:
# """
# Returns the avg logit diff on a set of prompts, with fixed s2 pos and stuff.
# """
# correct_logits = logits[range(len(logits)), -1, correct_toks]
# incorrect_logits = logits[range(len(logits)), -1, incorrect_toks]
# logit_diff = correct_logits - incorrect_logits
# if reduction is not None:
# logit_diff = logit_diff.mean() if reduction == "mean" else logit_diff.sum()
# return logit_diff
# names_filters = [gpt2_sae.cfg.hook_name + ".hook_sae_acts_post" for gpt2_sae in list_saes]
# use_error_term = True
# fg = Feature_Graph(
# gpt2,
# dict_saes,
# use_error_term=use_error_term,
# )
# fg.build_default_connection(clean_token.shape[1], token_wise=True, inter=True, intra=True)
# corrupt_logit, corrupt_cache = gpt2.run_with_cache_with_saes(
# corrupt_token,
# saes=list_saes,
# use_error_term=use_error_term,
# names_filter=lambda name: "sae" in name,
# )
# clean_logit = gpt2.run_with_saes(clean_token, saes=list_saes, use_error_term=use_error_term)
# ioi_metric = partial(logits_to_ave_logit_diff, reduction='sum')
# node_grads, _, clean_cache = fg.forward_backward_gradient(
# clean_token, corrupt_cache, ioi_metric, show_warnings=True, retain_graph=True, mode='node', patch_deleted_comp=True
# )
# attrib_effect = {}
# for (node, index), grad in node_grads.items():
# corrupt_sparse_act = SparseAct(
# act=corrupt_cache[sae_hook_name(node.name)],
# res=corrupt_cache[error_term_name(node.name)] if use_error_term else None,
# )
# a = clean_cache[node.name]
# attrib_effect[(node, index)] = (
# grad @
# (corrupt_sparse_act - a)
# ).sum(0)
# name_to_try = "blocks.2.hook_resid_pre"
# s2_pos = 10
# assert gpt2.to_str_tokens(prompts[0])[s2_pos] == " John"
# active_latents = (clean_cache[name_to_try].act[:, s2_pos] > 0.0).any(0).nonzero().cpu().tolist()
# ablation_effect = []
# clean_metric = ioi_metric(clean_logit) # type: ignore
# all_list_to_try = []
# with t.no_grad():
# for active_node_idx in tqdm(active_latents):
# list_to_try = [active_node_idx]
# all_list_to_try.append(list_to_try)
# fwd_cache = {}
# def ablate_sae_latent(
# sae_acts: Tensor,
# hook: HookPoint,
# ) -> Tensor:
# if hook.name == sae_hook_name(name_to_try):
# for node_idx in list_to_try:
# sae_acts[:, s2_pos, node_idx] = corrupt_cache[sae_hook_name(name_to_try)][:, s2_pos, node_idx]
# if hook.name == output_hook_name(f"blocks.{hook.layer()}.hook_resid_pre"):
# if use_error_term:
# sae_acts += clean_cache[f"blocks.{hook.layer()}.hook_resid_pre"].res
# return sae_acts
# # NOTE: use_error_term = True might be wrong
# gpt2.reset_hooks()
# patched_logits = gpt2.run_with_hooks_with_saes(
# clean_token,
# saes=list_saes,
# # fwd_hooks=[(names_filters[i], ablate_sae_latent) for i in range(len(names_filters))],
# fwd_hooks=[(lambda name: "sae" in name, ablate_sae_latent)],
# )
# ablation_effect.append((ioi_metric(patched_logits) - clean_metric).cpu().item())
# attrib_list = [
# sum([
# attrib_effect[ConnectionNode(name_to_try), ConnectionIndex()].act[s2_pos, active_node_idx].cpu().item()
# for active_node_idx in list_to_try
# ])
# for list_to_try in all_list_to_try
# ]
# from plotly import express as px
# import pandas as pd
# df = pd.DataFrame({
# 'ablation': ablation_effect,
# 'attribution': attrib_list,
# })
# # Create scatter plot
# fig = px.scatter(df, x='attribution', y='ablation', labels={'attribution': 'attribution', 'ablation': 'ablation'},
# title='Scatter Plot of Two Dictionaries')
# # Add text labels
# fig.update_traces(textposition='top center')
# # Add y = x line
# fig.add_shape(type='line', x0=min(df['ablation']), y0=min(df['ablation']),
# x1=max(df['ablation']), y1=max(df['ablation']),
# line=dict(color='red', dash='dash'))
# # Show plot
# fig.show() |