Analysis Utilities
This module collects small, framework-light helpers used by logit lens, attribution, and ablation experiments.
Core utilities:
softmax,log_softmax, andlogits_to_log_probs.per_token_cross_entropy_loss,cross_entropy_loss,lm_log_probs,lm_cross_entropy_loss, andlm_accuracy.topk_tokensandlogit_diff.residual_stack_to_logits,compute_head_results_from_z, anddirect_logit_attribution.attention_pattern_score,previous_token_attention_score, andinduction_attention_scorefor causal attention-pattern diagonal workflows, including repeated-token induction stripes viarepeat_length.zero_ablation_hook,mean_ablation_hook, andreplace_activation_hook.
Example:
from SafeLens.core.analysis import cross_entropy_loss, logit_diff
loss = cross_entropy_loss([[0.0, 0.0]], [1])
score = logit_diff([[[1.0, 4.0], [7.0, 2.0]]], 0, 1)
Ablation hooks can be attached to HookPoint or HookedRoot objects:
from SafeLens.core.analysis import zero_ablation_hook
from SafeLens.core.hooked_root import HookedRoot
root = HookedRoot()
hook = root.add_hook_point("blocks.0.hook_resid_pre")
with root.hooks(fwd_hooks=[("blocks.0.hook_resid_pre", zero_ablation_hook)]):
assert hook([1, 2, 3]) == [0, 0, 0]
Small analysis helpers for logits, losses, ablations, and head detection.
and_values(left, right)
Elementwise boolean and for nested-list masks.
Source code in src/SafeLens/core/analysis.py
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 | |
argmax_last_dim(values)
Return argmax indices over the final dimension.
Source code in src/SafeLens/core/analysis.py
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 | |
attention_pattern_score(pattern, offset=-1, *, min_dest_pos=None)
Average attention paid to a fixed source-position offset.
pattern is expected to end in [dest_pos, src_pos], with any number of
leading batch/layer/head dimensions preserved. offset=-1 scores previous
token attention. Causal induction heads also attend backwards in the
attention matrix, so induction-style matching is the same negative diagonal
shifted by the repeat length in repeated-token prompts. min_dest_pos
excludes diagonal entries before a destination position, which is useful for
skipping the first copy of a repeated prompt.
Source code in src/SafeLens/core/analysis.py
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 | |
causal_lm_loss_mask(attention_mask)
Return mask for valid causal LM targets from an input attention mask.
Source code in src/SafeLens/core/analysis.py
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 | |
compute_head_attention_similarity_score(attention_pattern, detection_pattern, *, exclude_bos, exclude_current_token, error_measure)
Compute similarity between a single head pattern and a detector pattern.
Source code in src/SafeLens/core/analysis.py
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 | |
compute_head_results_from_z(z, W_O, *, has_layer_axis=None)
Project per-head z activations through W_O into residual-space results.
z is expected to end in [head, d_head], and W_O should be shaped
[head, d_head, d_model] or [layer, head, d_head, d_model].
Leading batch/position dimensions are preserved. When z is stacked by
layer but omits an explicit batch dimension, pass has_layer_axis=True to
disambiguate the leading axis from a batch/position axis.
Source code in src/SafeLens/core/analysis.py
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 | |
cross_entropy_loss(logits, tokens)
Return mean cross-entropy loss.
Source code in src/SafeLens/core/analysis.py
93 94 95 96 | |
detect_head(model, seq, detection_pattern, heads=None, cache=None, *, exclude_bos=False, exclude_current_token=False, error_measure='mul')
Search cached attention patterns for TransformerLens-style head patterns.
This mirrors transformer_lens.head_detector.detect_head without depending
on TransformerLens. detection_pattern can be one of
"previous_token_head", "duplicate_token_head", "induction_head",
or an explicit square lower-triangular pattern. Returned scores are shaped
[n_layers, n_heads] and unselected heads are set to -1.
Source code in src/SafeLens/core/analysis.py
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 | |
direct_logit_attribution(residual_stack, token_directions)
Project residual components onto token directions.
Source code in src/SafeLens/core/analysis.py
494 495 496 | |
dot_last_dim(left, right)
Dot product over final dimension.
Source code in src/SafeLens/core/analysis.py
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 | |
equal_values(left, right)
Elementwise equality returning numeric 0/1 values for list backends.
Source code in src/SafeLens/core/analysis.py
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 | |
flatten(value)
Flatten nested lists or tensor-like values.
Source code in src/SafeLens/core/analysis.py
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 | |
gather_last_dim(values, indices)
Gather values at final-dimension indices.
Source code in src/SafeLens/core/analysis.py
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 | |
get_duplicate_token_head_detection_pattern(tokens)
Return a pattern whose entries mark earlier equal tokens.
Source code in src/SafeLens/core/analysis.py
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 | |
get_induction_head_detection_pattern(tokens)
Return a duplicate-token pattern shifted right for induction heads.
Source code in src/SafeLens/core/analysis.py
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 | |
get_previous_token_head_detection_pattern(tokens)
Return a lower-triangular pattern for attention to the previous token.
Source code in src/SafeLens/core/analysis.py
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 | |
get_supported_heads()
Print and return supported TransformerLens-style head detector names.
Source code in src/SafeLens/core/analysis.py
799 800 801 802 803 | |
induction_attention_score(pattern, *, offset=-1, repeat_length=None)
Score induction-head style attention on a causal backward diagonal.
For the minimal [A][B][A] -> [B] setup this is the previous-token
diagonal (offset=-1). For a repeated sequence of length N, induction
attention from the second copy to the next token after the first copy is on
offset=1-N.
Source code in src/SafeLens/core/analysis.py
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 | |
is_valid_number(value)
Return whether a flattened scalar should contribute to an aggregate.
Source code in src/SafeLens/core/analysis.py
2202 2203 2204 2205 2206 2207 2208 2209 | |
lm_accuracy(logits, tokens, attention_mask=None, *, per_token=False)
Return next-token prediction accuracy for causal language modeling.
Source code in src/SafeLens/core/analysis.py
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 | |
lm_cross_entropy_loss(logits, tokens, attention_mask=None, *, per_token=False)
Return causal LM cross-entropy using logits before each target token.
Source code in src/SafeLens/core/analysis.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
lm_log_probs(logits, tokens, attention_mask=None)
Return next-token log-probabilities for causal language modeling.
Logits at position i are gathered at token i + 1, matching
TransformerLens' language-model loss convention.
Source code in src/SafeLens/core/analysis.py
99 100 101 102 103 104 105 106 107 108 109 110 | |
log_softmax(values)
Apply log-softmax over the final dimension.
Source code in src/SafeLens/core/analysis.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
logit_diff(logits, correct_token, incorrect_token, *, pos=-1)
Return logit difference at one position.
Source code in src/SafeLens/core/analysis.py
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
logits_to_df(logits, tokenizer=None, top_k=None)
Convert a 1-D logit vector into a probability-sorted pandas DataFrame.
Source code in src/SafeLens/core/analysis.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
logits_to_log_probs(logits, tokens=None)
Convert logits to log probabilities, optionally gathering token log-probs.
Source code in src/SafeLens/core/analysis.py
79 80 81 82 83 84 | |
map_values(value, fn)
Map over nested list leaves.
Source code in src/SafeLens/core/analysis.py
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 | |
mask_values(values, mask)
Set values to None wherever mask is false.
Source code in src/SafeLens/core/analysis.py
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 | |
matmul_last_dim(left, right)
Multiply left[..., d] @ right[d, out] for nested-list values.
Source code in src/SafeLens/core/analysis.py
2409 2410 2411 2412 2413 2414 2415 | |
mean_ablation_hook(activation, hook=None)
Hook that replaces values with the activation mean.
Source code in src/SafeLens/core/analysis.py
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 | |
negate_values(value)
Negate nested values.
Source code in src/SafeLens/core/analysis.py
2212 2213 2214 2215 2216 2217 2218 2219 2220 | |
per_token_cross_entropy_loss(logits, tokens)
Return negative log-probability for each target token.
Source code in src/SafeLens/core/analysis.py
87 88 89 90 | |
previous_token_attention_score(pattern)
Score attention to the immediately previous token.
Source code in src/SafeLens/core/analysis.py
592 593 594 | |
replace_activation_hook(replacement)
Return a hook that replaces the full activation.
Source code in src/SafeLens/core/analysis.py
951 952 953 954 955 956 957 | |
residual_stack_to_logits(residual_stack, unembed, unembed_bias=None)
Project residual components through an unembedding matrix and optional bias.
Source code in src/SafeLens/core/analysis.py
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 | |
sample_logits(final_logits, top_k=None, top_p=None, temperature=1.0, freq_penalty=0.0, repetition_penalty=1.0, tokens=None)
Sample token IDs from final logits with TransformerLens-style controls.
Source code in src/SafeLens/core/analysis.py
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 | |
slice_last_dim(value, *, start=None, stop=None)
Slice the last dimension of tensor-like or nested-list values.
Source code in src/SafeLens/core/analysis.py
2028 2029 2030 2031 2032 2033 2034 2035 | |
slice_second_last_dim(value, *, start=None, stop=None)
Slice the second-last dimension of tensor-like or nested-list values.
Source code in src/SafeLens/core/analysis.py
2038 2039 2040 2041 2042 2043 2044 2045 | |
softmax(values)
Apply softmax over the final dimension.
Source code in src/SafeLens/core/analysis.py
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 | |
test_prompt(*args, **kwargs)
Run a TransformerLens-style prompt sanity check.
Supports both SafeLens' structured call shape
test_prompt(model, prompt, correct_token, incorrect_token=None, ...) and
TransformerLens' exploratory call shape
test_prompt(prompt, answer, model, ...). Both return a structured result;
TL-style calls additionally include answer-token ranks.
Source code in src/SafeLens/core/analysis.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
topk_tokens(logits, k=5)
Return top-k token indices and values for the final dimension.
Source code in src/SafeLens/core/analysis.py
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 | |
zero_ablation_hook(activation, hook=None)
Hook that replaces an activation with zeros.
Source code in src/SafeLens/core/analysis.py
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 | |
zero_mask_values(values, mask)
Set values to zero wherever mask is false.
Source code in src/SafeLens/core/analysis.py
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 | |