VoyagerXHF commited on
Commit
7d92fd7
·
verified ·
1 Parent(s): ec66211

Upload SAE model: SAE-Res-Qwen3.5-9B-Base-W64K-L0_50

Browse files
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Alibaba Cloud
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: qwen
4
+ license_link: https://huggingface.co/Qwen/SAE-Res-Qwen3.5-9B-Base-W64K-L0_50/blob/main/LICENSE
5
+ language:
6
+ - en
7
+ tags:
8
+ - sparse-autoencoder
9
+ - sae
10
+ - mechanistic-interpretability
11
+ - interpretability
12
+ - qwen-scope
13
+ base_model: Qwen/Qwen3.5-9B
14
+ ---
15
+
16
+ ## Qwen-Scope: Decoding Intelligence, Unleashing Potential
17
+
18
+ ![Overview](https://qianwen-res.oss-cn-beijing.aliyuncs.com/qwen-scope/Figures/overview.png)
19
+
20
+ We are excited to introduce Qwen-Scope, an interpretability module trained on the Qwen3 and Qwen3.5 series models. Specifically, we integrated and trained Sparse Autoencoders (SAEs) within Qwen’s hidden layers. By implementing sparsity constraints, we can automatically extract data features that are highly decoupled, low-redundancy, and significantly more interpretable. Qwen-Scope can be used not only to analyze the internal mechanisms of Qwen’s behavior but also holds immense potential for model optimization. Application scenarios include steerable inference control, evaluation sample distribution analysis and comparison, data classification and synthesis, and model training and optimization.
21
+
22
+ ## Model Details
23
+
24
+ | Property | Value |
25
+ |---|---|
26
+ | Base model | [Qwen3.5-9B](https://huggingface.co/Qwen/Qwen3.5-9B) |
27
+ | SAE width (`d_sae`) | 65536 |
28
+ | Hidden size (`d_model`) | 4096 |
29
+ | Expansion factor | 16× |
30
+ | Top-K | 50 |
31
+ | Hook point | Residual stream |
32
+ | Layers covered | 0 – 31 (32 layers total) |
33
+ | File format | PyTorch `.pt` dict |
34
+
35
+ ## Architecture
36
+
37
+ This is a **TopK SAE** — at each forward pass, exactly **50** features are kept non-zero.
38
+
39
+ Each checkpoint file `layer{n}.sae.pt` is a Python `dict` with four tensors:
40
+
41
+ | Key | Shape | Description |
42
+ |---|---|---|
43
+ | `W_enc` | `(65536, 4096)` | Encoder weight matrix |
44
+ | `W_dec` | `(4096, 65536)` | Decoder weight matrix |
45
+ | `b_enc` | `(65536,)` | Encoder bias |
46
+ | `b_dec` | `(4096,)` | Decoder bias |
47
+
48
+ ## Files
49
+
50
+ This repository contains one SAE checkpoint per transformer layer (layers 0–31):
51
+
52
+ ```
53
+ layer0.sae.pt
54
+ layer1.sae.pt
55
+ ...
56
+ layer31.sae.pt
57
+ ```
58
+
59
+ ## Feature Activation Extraction
60
+
61
+ End-to-end demo: run the base LLM, hook the residual stream at a chosen layer, and extract sparse SAE feature activations.
62
+ For most of the situations, using SAEs trained on base models to explore the internal process of post-training checkpoints is also reasonable.
63
+
64
+ ```python
65
+ import torch
66
+ from transformers import AutoTokenizer, AutoModelForCausalLM
67
+
68
+ # ── 1. Load base model ────────────────────────────────────────────────────────
69
+ model_name = "Qwen/Qwen3.5-9B"
70
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
71
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32)
72
+ model.eval()
73
+
74
+ # ── 2. Load SAE for a target layer ───────────────────────────────────────────
75
+ LAYER = 0 # choose any layer in 0–31
76
+ sae = torch.load(f"layer{LAYER}.sae.pt", map_location="cpu")
77
+ W_enc = sae["W_enc"] # (65536, 4096)
78
+ b_enc = sae["b_enc"] # (65536,)
79
+
80
+ def get_feature_acts(residual: torch.Tensor) -> torch.Tensor:
81
+ """residual: (..., 4096) → sparse feature activations (..., 65536)"""
82
+ pre_acts = residual @ W_enc.T + b_enc
83
+ topk_vals, topk_idx = pre_acts.topk(50, dim=-1)
84
+ acts = torch.zeros_like(pre_acts)
85
+ acts.scatter_(-1, topk_idx, topk_vals)
86
+ return acts
87
+
88
+ # ── 3. Hook residual stream after the target transformer layer ────────────────
89
+ captured = {}
90
+
91
+ def _hook(module, input, output):
92
+ hidden = output[0] if isinstance(output, tuple) else output
93
+ captured["residual"] = hidden.detach().cpu()
94
+
95
+ hook = model.model.layers[LAYER].register_forward_hook(_hook)
96
+
97
+ # ── 4. Forward pass ───────────────────────────────────────────────────────────
98
+ text = "The capital of France is"
99
+ inputs = tokenizer(text, return_tensors="pt")
100
+ with torch.no_grad():
101
+ model(**inputs)
102
+ hook.remove()
103
+
104
+ # ── 5. Extract feature activations ───────────────────────────────────────────
105
+ residual = captured["residual"] # (1, seq_len, 4096)
106
+ feature_acts = get_feature_acts(residual) # (1, seq_len, 65536)
107
+
108
+ # Inspect active features for the last token
109
+ last_token_acts = feature_acts[0, -1] # (65536,)
110
+ active_idx = last_token_acts.nonzero(as_tuple=True)[0]
111
+ print(f"Active features : {active_idx.tolist()}")
112
+ print(f"Feature values : {last_token_acts[active_idx].tolist()}")
113
+ ```
114
+
115
+ ## Gradio Demo
116
+
117
+ We also provide a gradio demo `app.py`. You can run it locally:
118
+ ```
119
+ python app.py \
120
+ --model Qwen/Qwen3.5-9B \
121
+ --model-name-sae-trained-from qwen3.5-9b-base \
122
+ --model-name-analyzing-now qwen3.5-9b \
123
+ --sae-path Qwen/SAE-Res-Qwen3.5-9B-Base-W64K-L0_50 \
124
+ --top-k 50 \
125
+ --num-layers 32 \
126
+ --sae-width 65536 \
127
+ --d-model 4096 \
128
+ --server-port 7860
129
+ ```
130
+
131
+ ## Caution
132
+ It is strictly prohibited to use interpretability tools for non-scientific research purposes to interfere with model capabilities, or to fabricate, generate, and disseminate harmful information that violates public order, good morals, and socialist core values, including pornographic, violent, discriminatory, or incendiary content. Violators will have their authorization automatically terminated and shall bear all legal liabilities arising therefrom. The right of final interpretation of this statement belongs to the project owner.
133
+
134
+ ## Citation
135
+
136
+ If you use these SAEs in your research, please cite:
137
+
138
+ ```bibtex
139
+ @misc{qwenscope,
140
+ title = {{Qwen-Scope}: Turning Sparse Features into Development Tools for Large Language Models},
141
+ author = {{Qwen Team}},
142
+ month = {April},
143
+ year = {2026}
144
+ }
145
+ ```
app.py ADDED
@@ -0,0 +1,1786 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ app.py — SAE Feature Explorer for Qwen3 models, whether pretrain (base) or posttrain (thinking/instruct) models.
3
+ """
4
+
5
+ import argparse
6
+ import html as _html
7
+ import json as _json
8
+ import os
9
+ from collections import OrderedDict
10
+
11
+ import gradio as gr
12
+ import torch
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer
14
+
15
+ # ─── CLI arguments ────────────────────────────────────────────────────────────
16
+ _parser = argparse.ArgumentParser(description="SAE Feature Explorer")
17
+ _parser.add_argument(
18
+ '--model',
19
+ default='Qwen/Qwen3-30B-A3B-Base',
20
+ help='Path to the base model directory (default: %(default)s)',
21
+ )
22
+ _parser.add_argument(
23
+ '--model-name-sae-trained-from',
24
+ default='qwen3-30b-a3b-base',
25
+ help='The name of model which present representations for SAE training (default: %(default)s)',
26
+ )
27
+ _parser.add_argument(
28
+ '--model-name-analyzing-now',
29
+ default='qwen3-30b-a3b',
30
+ help='The name of model which is used for analyzing now (default: %(default)s)',
31
+ )
32
+ _parser.add_argument(
33
+ '--sae-path',
34
+ default='Qwen/SAE-Res-Qwen3-30B-A3B-Base-W128K-L0_100',
35
+ help='Path to the directory containing layer*.sae.pt files (default: %(default)s)',
36
+ )
37
+ _parser.add_argument(
38
+ '--top-k',
39
+ type=int,
40
+ default=100,
41
+ help='Number of top features to display (default: %(default)s)',
42
+ )
43
+ _parser.add_argument(
44
+ '--num-layers',
45
+ type=int,
46
+ default=48,
47
+ help='Number of transformer layers in the model (default: %(default)s)',
48
+ )
49
+ _parser.add_argument(
50
+ '--sae-width',
51
+ type=int,
52
+ default=131_072,
53
+ help='SAE dictionary width / number of features (default: %(default)s)',
54
+ )
55
+ _parser.add_argument(
56
+ '--d-model',
57
+ type=int,
58
+ default=2048,
59
+ help='Model hidden dimension (default: %(default)s)',
60
+ )
61
+ _parser.add_argument(
62
+ '--sae-cache-max',
63
+ type=int,
64
+ default=8,
65
+ help='Maximum number of SAE layers to keep in memory at once (default: %(default)s)',
66
+ )
67
+ _parser.add_argument(
68
+ '--server-port',
69
+ type=int,
70
+ default=7860,
71
+ help='Port number for server',
72
+ )
73
+ _args = _parser.parse_args()
74
+
75
+ # ─── Config ──────────────────────────────────────────────────────────────────
76
+ MODEL_PATH = _args.model
77
+ MODEL_NAME_SAE_TRAINED_FROM = _args.model_name_sae_trained_from
78
+ MODEL_NAME_ANALYZING_NOW = _args.model_name_analyzing_now
79
+ SAE_PATH = _args.sae_path
80
+ TOP_K = _args.top_k
81
+ NUM_LAYERS = _args.num_layers
82
+ SAE_WIDTH = _args.sae_width
83
+ D_MODEL = _args.d_model
84
+ SAE_CACHE_MAX = _args.sae_cache_max
85
+ PORT = _args.server_port
86
+
87
+ # ─── Generation defaults (from model's generation_config.json) ────────────────
88
+
89
+ _gen_cfg: dict = {}
90
+ _gen_cfg_path = os.path.join(MODEL_PATH, 'generation_config.json')
91
+ if os.path.exists(_gen_cfg_path):
92
+ with open(_gen_cfg_path) as _f:
93
+ _gen_cfg = _json.load(_f)
94
+ print(f"Loaded generation_config.json from {_gen_cfg_path}")
95
+ else:
96
+ print(f"No generation_config.json found at {_gen_cfg_path}; using built-in defaults.")
97
+
98
+ GEN_DO_SAMPLE = bool(_gen_cfg.get('do_sample', False))
99
+ GEN_TEMPERATURE = float(_gen_cfg.get('temperature', 1.0))
100
+ GEN_TOP_P = float(_gen_cfg.get('top_p', 1.0))
101
+ GEN_TOP_K = int(_gen_cfg.get('top_k', 1))
102
+ GEN_REP_PENALTY = float(_gen_cfg.get('repetition_penalty', 1.0))
103
+ STEER_DISPLAY_K = 10 # top-k candidates shown in the per-token probability panel
104
+
105
+ # ─── Device resolution ───────────────────────────────────────────────────────
106
+
107
+ def _resolve_sae_device() -> torch.device:
108
+ """
109
+ Pick the device for SAE weights and encoder/decoder computations.
110
+
111
+ CUDA_VISIBLE_DEVICES remaps physical GPUs so that the first listed GPU
112
+ always appears as cuda:0 inside this process. We simply use cuda:0
113
+ when any CUDA device is visible; fall back to CPU otherwise.
114
+ """
115
+ if not torch.cuda.is_available():
116
+ print("SAE device: cpu (no CUDA visible)")
117
+ return torch.device('cpu')
118
+ cvd = os.environ.get('CUDA_VISIBLE_DEVICES', '<unset>')
119
+ device = torch.device('cuda:0')
120
+ print(f"SAE device: {device} — {torch.cuda.get_device_name(device)}"
121
+ f" [CUDA_VISIBLE_DEVICES={cvd}]")
122
+ return device
123
+
124
+ SAE_DEVICE = _resolve_sae_device()
125
+
126
+ # ─── Global singletons ───────────────────────────────────────────────────────
127
+ _model = None
128
+ _tokenizer = None
129
+ _sae_lru: OrderedDict = OrderedDict()
130
+ _orig_cache: dict | None = None # cached unsteered generation result
131
+
132
+
133
+ def get_model():
134
+ global _model, _tokenizer
135
+ if _model is None:
136
+ print("Loading model…")
137
+ _model = AutoModelForCausalLM.from_pretrained(
138
+ MODEL_PATH, device_map='auto', torch_dtype='auto'
139
+ )
140
+ _tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
141
+ _model.eval()
142
+ print("Model ready.")
143
+ return _model, _tokenizer
144
+
145
+
146
+ def get_sae(layer: int) -> dict:
147
+ if layer in _sae_lru:
148
+ _sae_lru.move_to_end(layer)
149
+ return _sae_lru[layer]
150
+ if len(_sae_lru) >= SAE_CACHE_MAX:
151
+ _sae_lru.popitem(last=False)
152
+ path = os.path.join(SAE_PATH, f'layer{layer}.sae.pt')
153
+ try:
154
+ sae = torch.load(path, map_location=SAE_DEVICE, weights_only=True)
155
+ except TypeError:
156
+ sae = torch.load(path, map_location=SAE_DEVICE)
157
+ # Pre-convert and transpose encoder weights once on load so compute_sae_features
158
+ # never repeats the conversion on every call.
159
+ sae['_W_enc'] = sae['W_enc'].T.to(dtype=torch.float32) # [d_model, sae_width]
160
+ sae['_b_enc'] = sae['b_enc'].to(dtype=torch.float32) # [sae_width]
161
+ _sae_lru[layer] = sae
162
+ return sae
163
+
164
+
165
+ # ─── Core math ───────────────────────────────────────────────────────────────
166
+
167
+ def topk_relu(x: torch.Tensor, k: int = TOP_K) -> torch.Tensor:
168
+ # Scatter top-k ReLU values directly — avoids creating a full-size boolean mask
169
+ # and an element-wise multiply, saving two [seq, SAE_WIDTH] allocations.
170
+ relu_x = torch.relu(x)
171
+ values, indices = torch.topk(relu_x, k, dim=-1)
172
+ out = torch.zeros_like(relu_x)
173
+ out.scatter_(-1, indices, values)
174
+ return out
175
+
176
+
177
+ @torch.no_grad()
178
+ def capture_hidden(model, input_ids: torch.Tensor, layer: int) -> torch.Tensor:
179
+ buf = {}
180
+ def _hook(module, inp, out):
181
+ # Qwen3MoE decoder layers return a plain tensor [batch, seq, hidden].
182
+ # out[0] removes the batch dim → [seq, hidden]; then move to SAE_DEVICE.
183
+ buf['h'] = out[0].detach().to(SAE_DEVICE, dtype=torch.float32)
184
+ handle = model.model.layers[layer].register_forward_hook(_hook)
185
+ model(input_ids)
186
+ handle.remove()
187
+ return buf['h'] # [seq_len, d_model]
188
+
189
+
190
+ @torch.no_grad()
191
+ def capture_all_hiddens(model, input_ids: torch.Tensor, layers: list) -> dict:
192
+ """
193
+ Capture residual-stream hidden states at multiple layers in a single
194
+ forward pass by registering simultaneous hooks. Tensors are stored on
195
+ SAE_DEVICE as float32 so downstream SAE matmuls need no extra transfer.
196
+ """
197
+ buf = {}
198
+ handles = []
199
+ for layer in layers:
200
+ def make_hook(l):
201
+ def _hook(module, inp, out):
202
+ buf[l] = out[0].detach().to(SAE_DEVICE, dtype=torch.float32)
203
+ return _hook
204
+ handles.append(model.model.layers[layer].register_forward_hook(make_hook(layer)))
205
+ model(input_ids)
206
+ for h in handles:
207
+ h.remove()
208
+ return buf # {layer_idx: Tensor[seq, d_model] on SAE_DEVICE}
209
+
210
+
211
+ def compute_sae_features(hidden: torch.Tensor, sae: dict,
212
+ raw: bool = False) -> torch.Tensor:
213
+ # Use pre-converted weights cached on load (avoids .float()/.T on every call)
214
+ W_enc = sae['_W_enc'] # [d_model, sae_width] float32 on SAE_DEVICE
215
+ b_enc = sae['_b_enc'] # [sae_width] float32 on SAE_DEVICE
216
+ pre = hidden @ W_enc + b_enc # [seq, sae_width] — pre-activation on SAE_DEVICE
217
+ if raw:
218
+ return pre # keep negative values intact; caller handles device
219
+ return topk_relu(pre, TOP_K) # stays on SAE_DEVICE; caller calls .tolist() as needed
220
+
221
+
222
+ # ─── UI helpers ──────────────────────────────────────────────────────────────
223
+
224
+
225
+ def parse_positions(s: str):
226
+ """
227
+ Parse a position string into 'all' or a sorted list of int indices.
228
+
229
+ Supported syntax (comma-separated, combinable):
230
+ all → every token position
231
+ 5 → single position
232
+ 3-7 → inclusive range (positions 3, 4, 5, 6, 7)
233
+ 0,2,5-8 → mix of individual positions and ranges
234
+ """
235
+ s = s.strip().lower()
236
+ if s == 'all':
237
+ return 'all'
238
+ try:
239
+ positions: list[int] = []
240
+ for part in s.split(','):
241
+ part = part.strip()
242
+ if not part:
243
+ continue
244
+ if '-' in part:
245
+ lo, hi = part.split('-', 1)
246
+ positions.extend(range(int(lo.strip()), int(hi.strip()) + 1))
247
+ else:
248
+ positions.append(int(part))
249
+ return sorted(set(positions))
250
+ except Exception:
251
+ return 'all'
252
+
253
+
254
+ def feature_heatmap_to_html(tokens: list, features: torch.Tensor, top_k: int, skip_first: bool = False) -> str:
255
+ """
256
+ Build a 2-D HTML heatmap:
257
+ rows = top-k features (ranked by mean activation across all positions)
258
+ cols = token positions
259
+ color = activation value (white → red, normalised per feature row by row max)
260
+ """
261
+
262
+ seq_len, sae_width = features.shape
263
+ top_k = min(int(top_k), sae_width)
264
+
265
+ # ── Optionally exclude the first token ────────────────────────────────────
266
+ if skip_first and seq_len > 1:
267
+ features = features[1:]
268
+ tokens = tokens[1:]
269
+ seq_len -= 1
270
+
271
+ # ── Select top-k features by mean activation across all positions ─────────
272
+ mean_per_feat = features.mean(dim=0) # [sae_width]
273
+ top_vals, top_idx = torch.topk(mean_per_feat, top_k)
274
+ feat_acts = features[:, top_idx] # [seq_len, top_k]
275
+
276
+ # ── Token column headers ──────────────────────────────────────────────────
277
+ TH_STYLE = (
278
+ "min-width:38px;max-width:70px;padding:4px 3px;"
279
+ "text-align:center;font-weight:500;font-size:11px;"
280
+ "color:#444;border-bottom:2px solid #c7d2e8;"
281
+ "overflow:hidden;white-space:nowrap;vertical-align:bottom;"
282
+ )
283
+ tok_headers = []
284
+ for i, tok in enumerate(tokens):
285
+ raw = tok.strip() or f"[{i}]"
286
+ short = _html.escape(raw[:6] + "…" if len(raw) > 6 else raw)
287
+ full = _html.escape(raw)
288
+ tok_headers.append(
289
+ f'<th style="{TH_STYLE}" title="pos {i}: {full}">{short}</th>'
290
+ )
291
+
292
+ # ── Data rows ─────────────────────────────────────────────────────────────
293
+ FEAT_TD = (
294
+ "font-family:ui-monospace,monospace;font-size:11px;"
295
+ "padding:3px 8px;color:#2563eb;white-space:nowrap;"
296
+ "border-right:2px solid #c7d2e8;background:#f8faff;"
297
+ "position:sticky;left:0;z-index:1;"
298
+ )
299
+ AVG_TD = (
300
+ "font-size:10px;padding:3px 6px;color:#777;white-space:nowrap;"
301
+ "border-right:1px solid #e4e7ef;text-align:right;"
302
+ )
303
+ CELL_BASE = (
304
+ "border:1px solid rgba(0,0,0,0.05);min-width:38px;height:30px;"
305
+ "text-align:center;vertical-align:middle;"
306
+ )
307
+
308
+ rows_html = []
309
+ for fi in range(top_k):
310
+ feat_i = int(top_idx[fi])
311
+ avg_val = float(top_vals[fi])
312
+ row_acts = feat_acts[:, fi] # [seq_len]
313
+ row_max = float(row_acts.max())
314
+ norm = row_max if row_max > 0 else 1.0
315
+
316
+ cells = []
317
+ for pos in range(seq_len):
318
+ v = float(row_acts[pos])
319
+ t = max(0.0, min(1.0, v / norm))
320
+ # white → amber → deep red
321
+ r = 255
322
+ g = int(255 * (1 - 0.8 * t))
323
+ b = int(255 * (1 - t))
324
+ cells.append(
325
+ f'<td style="{CELL_BASE}background:rgb({r},{g},{b});"'
326
+ f' title="feat #{feat_i} | pos {pos} | act={v:.4f}">'
327
+ f'</td>'
328
+ )
329
+
330
+ rows_html.append(
331
+ f'<tr>'
332
+ f'<td style="{FEAT_TD}">#{feat_i}</td>'
333
+ f'<td style="{AVG_TD}">{avg_val:.3f}</td>'
334
+ + "".join(cells)
335
+ + "</tr>"
336
+ )
337
+
338
+ # ── Assemble table ────────────────────────────────────────────────────────
339
+ header_row = (
340
+ '<tr>'
341
+ '<th style="padding:4px 8px;text-align:left;font-size:11px;font-weight:700;'
342
+ 'color:#2563eb;border-bottom:2px solid #c7d2e8;border-right:2px solid #c7d2e8;'
343
+ 'background:#f8faff;position:sticky;left:0;z-index:2;">Feature</th>'
344
+ '<th style="padding:4px 6px;font-size:11px;font-weight:700;color:#777;'
345
+ 'border-bottom:2px solid #c7d2e8;border-right:1px solid #e4e7ef;">'
346
+ 'Avg&nbsp;act.</th>'
347
+ + "".join(tok_headers)
348
+ + "</tr>"
349
+ )
350
+
351
+ legend = (
352
+ '<div style="display:flex;align-items:center;gap:10px;margin-top:10px;'
353
+ 'font-size:11px;color:#888;">'
354
+ '<span>0</span>'
355
+ '<div style="width:140px;height:12px;border-radius:6px;'
356
+ 'background:linear-gradient(to right,#fff,#ff6600,#cc0000);'
357
+ 'border:1px solid #ddd;"></div>'
358
+ '<span>peak activation (per-feature row-max scale)</span>'
359
+ '</div>'
360
+ )
361
+
362
+ return (
363
+ '<div style="overflow-x:auto;max-height:520px;overflow-y:auto;">'
364
+ '<table style="border-collapse:collapse;width:100%;'
365
+ 'font-family:ui-monospace,monospace;">'
366
+ f'<thead style="position:sticky;top:0;background:#fff;z-index:3;">'
367
+ f'{header_row}</thead>'
368
+ f'<tbody>{"".join(rows_html)}</tbody>'
369
+ '</table>'
370
+ '</div>'
371
+ + legend
372
+ )
373
+
374
+
375
+ def tokens_with_positions_html(tokens: list, positions) -> str:
376
+ """
377
+ Render tokenized prompt as coloured token chips.
378
+
379
+ Steered positions (amber/gold) are visually distinct from unsteered ones (grey).
380
+ positions: 'all' → every index is highlighted
381
+ list → only those indices
382
+ """
383
+
384
+ if not tokens:
385
+ return (
386
+ '<div style="padding:10px;color:#bbb;font-size:13px;">'
387
+ 'Enter a prompt above to preview token positions.</div>'
388
+ )
389
+
390
+ all_positions = positions if isinstance(positions, list) else []
391
+ pos_set = (
392
+ set(range(len(tokens))) if positions == 'all'
393
+ else {p for p in all_positions if 0 <= p < len(tokens)}
394
+ )
395
+ # Positions beyond the prompt — will be steered in the generated text
396
+ generated_positions = (
397
+ [] if positions == 'all'
398
+ else sorted(p for p in all_positions if p >= len(tokens))
399
+ )
400
+
401
+ parts = []
402
+ for i, tok in enumerate(tokens):
403
+ steered = i in pos_set
404
+ txt = _html.escape(tok)
405
+ title = _html.escape(repr(tok.strip()), quote=True)
406
+
407
+ if steered:
408
+ bg, border, text_color = "#fef3c7", "2px solid #f59e0b", "#92400e"
409
+ else:
410
+ bg, border, text_color = "#f1f5f9", "1px solid #e2e8f0", "#475569"
411
+
412
+ parts.append(
413
+ f'<span style="background:{bg};color:{text_color};'
414
+ f'padding:3px 7px;margin:2px 1px;border-radius:5px;'
415
+ f'display:inline-block;border:{border};'
416
+ f'font-family:ui-monospace,monospace;font-size:12px;" '
417
+ f'title="pos {i}: {title}">'
418
+ f'<sub style="opacity:.55;font-size:9px;margin-right:2px">{i}</sub>'
419
+ f'{txt}</span>'
420
+ )
421
+
422
+ n_steered = len(pos_set)
423
+ summary = (
424
+ f'<div style="margin-top:6px;font-size:11px;color:#888;">'
425
+ f'{len(tokens)}&nbsp;tokens total&nbsp;&nbsp;·&nbsp;&nbsp;'
426
+ f'<span style="color:#92400e;font-weight:600;">{n_steered}&nbsp;steered</span>'
427
+ f'&nbsp;<span style="color:#f59e0b;">■</span>'
428
+ f'</div>'
429
+ )
430
+
431
+ generated_note = ''
432
+ if generated_positions:
433
+ gp_str = ', '.join(str(p) for p in generated_positions)
434
+ generated_note = (
435
+ f'<div style="margin-top:4px;font-size:11px;padding:4px 8px;'
436
+ f'background:#eff6ff;border:1px solid #bfdbfe;border-radius:4px;color:#1d4ed8;">'
437
+ f'Positions {gp_str} are beyond the prompt — they will be steered '
438
+ f'in the <em>generated</em> text during autoregressive decoding.'
439
+ f'</div>'
440
+ )
441
+
442
+ return (
443
+ '<div style="padding:8px 4px;line-height:2.8;">'
444
+ + ' '.join(parts)
445
+ + summary
446
+ + generated_note
447
+ + '</div>'
448
+ )
449
+
450
+
451
+ def cb_feature_heatmap(state, top_k: int, skip_first: bool):
452
+ if state is None:
453
+ return (
454
+ '<div style="min-height:80px;display:flex;align-items:center;'
455
+ 'justify-content:center;color:#bbb;font-size:13px;">'
456
+ 'Run analysis first to see the feature heatmap.</div>'
457
+ )
458
+ tokens, features = state
459
+ return feature_heatmap_to_html(tokens, features, int(top_k), bool(skip_first))
460
+
461
+
462
+ # ─── Gradio callbacks ────────────────────────────────────────────────────────
463
+
464
+ def cb_analyze(text: str, layer: int):
465
+ try:
466
+ model, tokenizer = get_model()
467
+ input_ids = tokenizer.encode(text, return_tensors='pt').to(
468
+ next(model.parameters()).device
469
+ )
470
+ tokens = [tokenizer.decode([t]) for t in input_ids[0].tolist()]
471
+ hidden = capture_hidden(model, input_ids, int(layer))
472
+ features = compute_sae_features(hidden, get_sae(int(layer)))
473
+ return (tokens, features)
474
+ except Exception as e:
475
+ raise gr.Error(f"Analysis failed: {e}")
476
+
477
+
478
+
479
+ def _steering_strength_from_mode(mode: str, diff_lookup, layer: int, feat_idx: int,
480
+ custom_val: float = 5.0) -> float:
481
+ """Map Light/Medium/Strong/Custom to an actual steering strength.
482
+
483
+ Looks up the feature-specific diff for (layer, feat_idx) from the
484
+ Feature Comparison results. Falls back to the global max across all
485
+ compared features, then to fixed defaults when no data is available.
486
+ """
487
+ if mode == "Custom":
488
+ return float(custom_val)
489
+ d = 0.0
490
+ if diff_lookup and isinstance(diff_lookup, dict):
491
+ key = (int(layer), int(feat_idx))
492
+ if key in diff_lookup:
493
+ d = float(diff_lookup[key])
494
+ else:
495
+ d = float(max(diff_lookup.values(), default=0.0))
496
+ if d <= 0:
497
+ return {"Light": 5.0, "Medium": 20.0, "Strong": 100.0}.get(mode, 5.0)
498
+ return {"Light": round(d * 0.5, 2),
499
+ "Medium": round(d * 2.0, 2),
500
+ "Strong": round(d * 10.0, 2)}.get(mode, round(d, 2))
501
+
502
+
503
+ def cb_generate(prompt, layer, feat_idx, pos_str, steer_mode, compare_diff,
504
+ steer_output_only, max_tok, greedy, top_k_tok, top_p, rep_penalty, temp,
505
+ custom_strength=5.0):
506
+ try:
507
+ return _cb_generate_inner(prompt, layer, feat_idx, pos_str, steer_mode, compare_diff,
508
+ steer_output_only, max_tok, greedy, top_k_tok, top_p, rep_penalty, temp,
509
+ custom_strength)
510
+ except gr.Error:
511
+ raise
512
+ except Exception as e:
513
+ raise gr.Error(f"Generation failed: {e}")
514
+
515
+
516
+ def cb_update_steer_preview(prompt: str, pos_str: str):
517
+ """Tokenise the prompt and return an HTML token-position preview."""
518
+ if not prompt.strip():
519
+ return (
520
+ '<div style="padding:10px;color:#bbb;font-size:13px;">'
521
+ 'Enter a prompt above to preview steered positions.</div>'
522
+ )
523
+ try:
524
+ _, tokenizer = get_model()
525
+ input_ids = tokenizer.encode(prompt)
526
+ tokens = [tokenizer.decode([t]) for t in input_ids]
527
+ positions = parse_positions(pos_str)
528
+ return tokens_with_positions_html(tokens, positions)
529
+ except Exception as e:
530
+ return (
531
+ f'<div style="padding:10px;color:#dc2626;font-size:13px;">'
532
+ f'Preview error: {e}</div>'
533
+ )
534
+
535
+
536
+ def _extract_probs(gen_out, input_len: int, tokenizer, display_k: int):
537
+ """
538
+ Extract per-step token probabilities from a `return_dict_in_generate=True,
539
+ output_scores=True` GenerateOutput.
540
+
541
+ Returns (text, tokens, chosen_probs, topk_data) where:
542
+ tokens : list[str] — decoded token strings
543
+ chosen_probs : list[float] — probability of the chosen token (0-1)
544
+ topk_data : list[list[[str, float, bool]]] — top-k candidates at each step,
545
+ each entry is [token_str, prob, is_chosen]
546
+ """
547
+ new_ids = gen_out.sequences[0][input_len:]
548
+ new_id_list = new_ids.tolist()
549
+
550
+ # Batch-decode chosen tokens and all top-k candidates in two passes
551
+ # instead of O(n * display_k) individual tokenizer.decode() calls.
552
+ all_topk_ids: list[list[int]] = []
553
+ chosen_probs: list[float] = []
554
+ topk_vals_list: list = []
555
+ chosen_in_top_list: list[bool]= []
556
+
557
+ for score_t, tok_id in zip(gen_out.scores, new_id_list):
558
+ probs = torch.softmax(score_t[0].float(), dim=-1)
559
+ chosen_probs.append(float(probs[tok_id]))
560
+ top_vals, top_ids = torch.topk(probs, display_k)
561
+ tid_list = top_ids.tolist()
562
+ chosen_in_top = tok_id in tid_list
563
+ all_topk_ids.append(tid_list)
564
+ topk_vals_list.append(top_vals.tolist())
565
+ chosen_in_top_list.append(chosen_in_top)
566
+
567
+ # Single batch_decode call for all chosen tokens
568
+ tokens: list[str] = tokenizer.batch_decode(
569
+ [[t] for t in new_id_list], skip_special_tokens=False
570
+ )
571
+
572
+ # Single batch_decode call for all top-k candidate tokens
573
+ flat_ids = [tid for ids in all_topk_ids for tid in ids]
574
+ flat_decoded = tokenizer.batch_decode(
575
+ [[t] for t in flat_ids], skip_special_tokens=False
576
+ )
577
+
578
+ topk_data = []
579
+ flat_idx = 0
580
+ for i, (tok_id, ids, vals, chosen_in_top, chosen_prob) in enumerate(
581
+ zip(new_id_list, all_topk_ids, topk_vals_list, chosen_in_top_list, chosen_probs)
582
+ ):
583
+ entry = []
584
+ for tid, tv in zip(ids, vals):
585
+ entry.append([flat_decoded[flat_idx], tv, tid == tok_id])
586
+ flat_idx += 1
587
+ if not chosen_in_top:
588
+ entry.append([tokens[i], chosen_prob, True])
589
+ topk_data.append(entry)
590
+
591
+ text = tokenizer.decode(new_ids, skip_special_tokens=True)
592
+ return text, tokens, chosen_probs, topk_data
593
+
594
+
595
+ def probs_to_html(tokens: list, chosen_probs: list, topk_data: list,
596
+ panel_id: str, theme: str = 'blue') -> str:
597
+ """
598
+ Render per-token generation probabilities as coloured chips.
599
+ Clicking a chip pins its top-k candidate table in the panel below;
600
+ clicking the same chip again or another chip toggles/switches the display.
601
+ Scroll-stable: no hover events that fire on page scroll.
602
+
603
+ theme: 'blue' for original output, 'red' for steered output.
604
+ """
605
+
606
+ if not tokens:
607
+ return ('<div style="padding:10px;color:#bbb;font-size:13px;">'
608
+ 'No tokens generated.</div>')
609
+
610
+ # ── Chip colour (white → saturated) based on probability ─────────────────
611
+ def _colors(prob: float):
612
+ t = max(0.0, min(1.0, prob))
613
+ if theme == 'blue':
614
+ r, g, b = int(255 * (1 - t * 0.85)), int(255 * (1 - t * 0.65)), 255
615
+ txt = '#1e3a8a' if t < 0.55 else '#ffffff'
616
+ else:
617
+ r, g, b = 255, int(255 * (1 - t * 0.82)), int(255 * (1 - t))
618
+ txt = '#7f1d1d' if t < 0.55 else '#ffffff'
619
+ return f'rgb({r},{g},{b})', txt
620
+
621
+ # ── Pre-build the top-k panel HTML in Python ──────────────────────────────
622
+ TH = 'padding:2px 8px;font-size:11px;color:#6b7280;border-bottom:1px solid #e4e7ef;'
623
+
624
+ def _panel_html(entry: list) -> str:
625
+ rows = []
626
+ for rank, (tok_str, prob, is_chosen) in enumerate(entry, 1):
627
+ bg = 'background:#dbeafe;' if is_chosen else ''
628
+ fw = 'font-weight:700;' if is_chosen else ''
629
+ mk = ' ✓' if is_chosen else ''
630
+ rows.append(
631
+ f'<tr style="border-bottom:1px solid #f4f6ff;{bg}">'
632
+ f'<td style="padding:2px 8px;text-align:right;font-size:11px;color:#9ca3af;">{rank}</td>'
633
+ f'<td style="padding:2px 8px;font-family:monospace;font-size:12px;{fw}">{_html.escape(tok_str)}{mk}</td>'
634
+ f'<td style="padding:2px 8px;text-align:right;font-family:monospace;font-size:12px;">{prob:.4f}</td>'
635
+ f'<td style="padding:2px 8px;text-align:right;font-family:monospace;font-size:12px;">{prob * 100:.2f}%</td>'
636
+ f'</tr>'
637
+ )
638
+ return (
639
+ '<table style="border-collapse:collapse;width:100%;font-size:12px;">'
640
+ f'<thead style="background:#f8faff;"><tr>'
641
+ f'<th style="{TH}text-align:right;">Rank</th>'
642
+ f'<th style="{TH}text-align:left;">Token</th>'
643
+ f'<th style="{TH}text-align:right;">Prob</th>'
644
+ f'<th style="{TH}text-align:right;">%</th>'
645
+ f'</tr></thead>'
646
+ f'<tbody>{"".join(rows)}</tbody>'
647
+ '</table>'
648
+ )
649
+
650
+ # ── Inline JS — click to pin, click again to unpin ───────────────────────
651
+ # Uses data-prob-root to scope sibling chips without global IDs.
652
+ # Single-quoted JS string literals are safe inside double-quoted HTML attrs.
653
+ # Non-f-string parts: { } are literal characters (no f-string substitution).
654
+ JS_CLICK = (
655
+ "var root=this.closest('[data-prob-root]');"
656
+ "if(!root)return;"
657
+ "var p=root.querySelector('[data-topk-panel]');"
658
+ "if(!p)return;"
659
+ "var sel=this.dataset.selected==='1';"
660
+ "root.querySelectorAll('[data-chip]').forEach(function(e){"
661
+ "e.dataset.selected='0';e.style.outline='';});"
662
+ "if(sel){"
663
+ "p.innerHTML='';p.style.display='none';"
664
+ "}else{"
665
+ "this.dataset.selected='1';"
666
+ "this.style.outline='2px solid #94a3b8';"
667
+ "this.style.outlineOffset='-1px';"
668
+ "p.innerHTML=this.getAttribute('data-panel');"
669
+ "p.style.display='block';"
670
+ "}"
671
+ )
672
+
673
+ def _tok_disp(s: str) -> str:
674
+ return s.replace('\n', '↵').replace('\r', '↵').replace('\t', '→')
675
+
676
+ # ── Build chips ───────────────────────────────────────────────────────────
677
+ chips = []
678
+ for tok, prob, entry in zip(tokens, chosen_probs, topk_data):
679
+ bg, txt = _colors(prob)
680
+ panel_attr = _html.escape(_panel_html(entry), quote=True)
681
+ chips.append(
682
+ f'<span data-chip data-selected="0" '
683
+ f'style="background:{bg};color:{txt};padding:3px 8px 2px;margin:1px;'
684
+ f'border-radius:5px;display:inline-block;cursor:pointer;white-space:nowrap;'
685
+ f'font-family:ui-monospace,monospace;font-size:12px;" '
686
+ f'data-panel="{panel_attr}" '
687
+ f'onclick="{JS_CLICK}">'
688
+ f'{_html.escape(_tok_disp(tok))}'
689
+ f'<sub style="opacity:.75;font-size:9px;margin-left:3px;">{prob * 100:.1f}%</sub>'
690
+ f'</span>'
691
+ )
692
+
693
+ return (
694
+ '<div data-prob-root style="padding:2px;">'
695
+ '<div style="font-size:11px;color:#888;margin-bottom:6px;font-style:italic;">'
696
+ 'Click a token to pin its top-k candidates &nbsp;·&nbsp; click again to dismiss.</div>'
697
+ '<div style="padding:4px;line-height:2.8;">'
698
+ + ''.join(chips)
699
+ + '</div>'
700
+ + '<div data-topk-panel style="display:none;margin-top:8px;padding:4px;'
701
+ 'background:#f8faff;border:1px solid #e4e7ef;border-radius:6px;'
702
+ 'max-height:220px;overflow-y:auto;"></div>'
703
+ + '</div>'
704
+ )
705
+
706
+
707
+ def _cb_generate_inner(prompt, layer, feat_idx, pos_str, steer_mode, compare_diff,
708
+ steer_output_only, max_tok, greedy, top_k_tok, top_p, rep_penalty, temp,
709
+ custom_strength=5.0):
710
+ global _orig_cache
711
+ model, tokenizer = get_model()
712
+ layer = int(layer)
713
+ feat_idx = int(feat_idx)
714
+ if not (0 <= feat_idx < SAE_WIDTH):
715
+ raise gr.Error(f"Feature index must be in [0, {SAE_WIDTH - 1}].")
716
+ strength = _steering_strength_from_mode(steer_mode, compare_diff, layer, feat_idx, float(custom_strength))
717
+ positions = parse_positions(pos_str)
718
+
719
+ input_ids = tokenizer.encode(prompt, return_tensors='pt').to(
720
+ next(model.parameters()).device
721
+ )
722
+
723
+ # Build generation kwargs shared by both calls
724
+ gen_kwargs: dict = dict(max_new_tokens=int(max_tok),
725
+ return_dict_in_generate=True, output_scores=True)
726
+ if greedy:
727
+ gen_kwargs['do_sample'] = False
728
+ else:
729
+ gen_kwargs['do_sample'] = True
730
+ gen_kwargs['temperature'] = float(temp)
731
+ gen_kwargs['top_k'] = int(top_k_tok)
732
+ gen_kwargs['top_p'] = float(top_p)
733
+ gen_kwargs['repetition_penalty'] = float(rep_penalty)
734
+
735
+ prompt_len = input_ids.shape[1]
736
+
737
+ # ── Original generation (cached) ─────────────────────────────────────────
738
+ # The unsteered output depends only on the prompt and decoding parameters,
739
+ # not on any steering inputs. Reuse the last result when those are unchanged.
740
+ if greedy:
741
+ orig_key = (prompt, int(max_tok), True)
742
+ else:
743
+ orig_key = (prompt, int(max_tok), False,
744
+ int(top_k_tok), float(top_p), float(rep_penalty), float(temp))
745
+
746
+ if _orig_cache is not None and _orig_cache['key'] == orig_key:
747
+ orig_text = _orig_cache['text']
748
+ orig_probs_html = _orig_cache['probs_html']
749
+ else:
750
+ with torch.no_grad():
751
+ orig_out = model.generate(input_ids, **gen_kwargs)
752
+ orig_text, orig_toks, orig_probs, orig_topk = _extract_probs(
753
+ orig_out, prompt_len, tokenizer, STEER_DISPLAY_K
754
+ )
755
+ orig_probs_html = probs_to_html(orig_toks, orig_probs, orig_topk,
756
+ 'topk-panel-orig', theme='blue')
757
+ _orig_cache = dict(key=orig_key, text=orig_text, probs_html=orig_probs_html)
758
+
759
+ sae = get_sae(layer)
760
+ steering_vec = sae['W_dec'][:, feat_idx].float() # [d_model]
761
+ pos_set = None if positions == 'all' else set(positions)
762
+ counter = [0]
763
+
764
+ def _steer_hook(module, inp, out):
765
+ # out: plain tensor [batch, seq, hidden] for Qwen3MoE
766
+ h = out.clone()
767
+ sv = steering_vec.to(device=h.device, dtype=h.dtype) # one fused transfer
768
+ cur_counter = counter[0]
769
+ counter[0] += 1
770
+ if cur_counter == 0:
771
+ # Prefill: apply position-based steering to the prompt
772
+ if positions == 'all':
773
+ h = h + strength * sv
774
+ else:
775
+ for p in positions:
776
+ if 0 <= p < h.shape[1]:
777
+ h[:, p, :] = h[:, p, :] + strength * sv
778
+ else:
779
+ # Decode step (KV-cache): h is [batch, 1, hidden]
780
+ # Steer if: output-only mode is on, positions='all', or this position is listed
781
+ cur_seq_pos = prompt_len + cur_counter - 1
782
+ if steer_output_only or positions == 'all' or cur_seq_pos in pos_set:
783
+ h[:, 0, :] = h[:, 0, :] + strength * sv
784
+ return h
785
+
786
+ handle = model.model.layers[layer].register_forward_hook(_steer_hook)
787
+ with torch.no_grad():
788
+ steer_out = model.generate(input_ids, **gen_kwargs)
789
+ handle.remove()
790
+ steer_text, steer_toks, steer_probs, steer_topk = _extract_probs(
791
+ steer_out, prompt_len, tokenizer, STEER_DISPLAY_K
792
+ )
793
+
794
+ steer_probs_html = probs_to_html(steer_toks, steer_probs, steer_topk,
795
+ 'topk-panel-steer', theme='red')
796
+
797
+ return orig_text, steer_text, orig_probs_html, steer_probs_html
798
+
799
+
800
+
801
+ # ─── Feature Comparison helpers ──────────────────────────────────────────────
802
+
803
+ def compare_to_html(records: list, text1: str, text2: str,
804
+ tokens1: list = None, tokens2: list = None) -> tuple:
805
+ """
806
+ Render comparison results as two HTML strings:
807
+ - tok_display_html: token rows for the left panel (data-tok-display root)
808
+ - feature_table_html: feature table for the right panel
809
+
810
+ Returns (tok_display_html, feature_table_html).
811
+ """
812
+
813
+ _TOK_PLACEHOLDER = (
814
+ '<div style="min-height:60px;display:flex;align-items:center;'
815
+ 'justify-content:center;color:#bbb;font-size:13px;padding:8px;">'
816
+ 'Run Compare to see token activations here.</div>'
817
+ )
818
+
819
+ if not records:
820
+ return (
821
+ _TOK_PLACEHOLDER,
822
+ '<div style="min-height:80px;display:flex;align-items:center;'
823
+ 'justify-content:center;color:#bbb;font-size:13px;">'
824
+ 'No results — try a wider layer range or larger Top-K.</div>',
825
+ )
826
+
827
+ # ── Token display blocks ──────────────────────────────────────────────────
828
+ TOK_SPAN = (
829
+ "display:inline-block;padding:3px 7px;margin:2px 1px;"
830
+ "border-radius:5px;font-family:ui-monospace,monospace;font-size:12px;"
831
+ "background:#eef2ff;color:#374151;cursor:default;"
832
+ "transition:background .1s;border:1px solid rgba(0,0,0,0.06);"
833
+ )
834
+
835
+ def render_tok_row(tokens, seq_id):
836
+ parts = []
837
+ for i, tok in enumerate(tokens):
838
+ txt = _html.escape(tok)
839
+ title = _html.escape(repr(tok.strip()), quote=True)
840
+ parts.append(
841
+ f'<span data-seq={seq_id} data-pos={i} style="{TOK_SPAN}" '
842
+ f'title="pos {i}: {title}">'
843
+ f'<sub style="opacity:.5;font-size:9px;margin-right:2px">{i}</sub>'
844
+ f'{txt}</span>'
845
+ )
846
+ return " ".join(parts)
847
+
848
+ # Build token display HTML for the left panel
849
+ if tokens1 and tokens2:
850
+ tok_inner = (
851
+ '<div style="margin-bottom:10px;color:#1e293b;">'
852
+ '<div style="font-size:11px;font-weight:700;color:#2563eb;'
853
+ 'text-transform:uppercase;letter-spacing:.5px;margin-bottom:5px;">'
854
+ f'Example 1 &nbsp;<span style="font-weight:400;color:#888;">'
855
+ f'({len(tokens1)} tokens)</span></div>'
856
+ '<div style="line-height:2.8;padding:8px 10px;background:#fafbff;'
857
+ 'border-radius:8px;border:1px solid #e4e7ef;overflow-x:auto;">'
858
+ + render_tok_row(tokens1, 1)
859
+ + '</div></div>'
860
+ '<div style="margin-bottom:8px;color:#1e293b;">'
861
+ '<div style="font-size:11px;font-weight:700;color:#dc2626;'
862
+ 'text-transform:uppercase;letter-spacing:.5px;margin-bottom:5px;">'
863
+ f'Example 2 &nbsp;<span style="font-weight:400;color:#888;">'
864
+ f'({len(tokens2)} tokens)</span></div>'
865
+ '<div style="line-height:2.8;padding:8px 10px;background:#fafbff;'
866
+ 'border-radius:8px;border:1px solid #e4e7ef;overflow-x:auto;">'
867
+ + render_tok_row(tokens2, 2)
868
+ + '</div></div>'
869
+ '<div style="font-size:11px;color:#888;font-style:italic;">'
870
+ 'Hover a feature row on the right to highlight activations.</div>'
871
+ )
872
+ else:
873
+ tok_inner = _TOK_PLACEHOLDER
874
+
875
+ # Wrap with data-tok-display so the JS hover handler can find it across columns
876
+ tok_display_html = f'<div data-tok-display style="padding:2px;">{tok_inner}</div>'
877
+
878
+ # ── Per-layer max for bar-width normalization ─────────────────────────────
879
+ _layer_max: dict = {}
880
+ for _d, _l, *_ in records:
881
+ if _d > _layer_max.get(_l, 0.0):
882
+ _layer_max[_l] = _d
883
+
884
+ # ── Inline JS snippets for hover-highlight ────────────────────────────────
885
+ # Uses document.querySelector('[data-tok-display]') so the handler works
886
+ # across Gradio columns (token panel on left, feature table on right).
887
+ _JS_ENTER = (
888
+ "var d=document.querySelector('[data-tok-display]');"
889
+ "if(!d)return;"
890
+ "var a1=JSON.parse(this.getAttribute('data-acts1'));"
891
+ "var a2=JSON.parse(this.getAttribute('data-acts2'));"
892
+ "if(!a1||!a2)return;"
893
+ "var pk=Math.max.apply(null,a1.map(Math.abs).concat(a2.map(Math.abs)))||0.0001;"
894
+ "function c1(v){var t=Math.abs(v)/pk;"
895
+ "return 'rgb('+Math.round(255*(1-t))+','+Math.round(255*(1-.6*t))+',255)'}"
896
+ "function c2(v){var t=Math.abs(v)/pk;"
897
+ "return 'rgb(255,'+Math.round(255*(1-.8*t))+','+Math.round(255*(1-t))+')'}"
898
+ "d.querySelectorAll('[data-seq]').forEach(function(e){"
899
+ "var s=e.dataset.seq,p=parseInt(e.dataset.pos,10);"
900
+ "if(s==='1'&&p<a1.length)e.style.background=c1(a1[p]);"
901
+ "else if(s==='2'&&p<a2.length)e.style.background=c2(a2[p]);});"
902
+ "this.style.outline='2px solid #94a3b8';"
903
+ "this.style.outlineOffset='-1px';"
904
+ )
905
+ _JS_LEAVE = (
906
+ "var d=document.querySelector('[data-tok-display]');"
907
+ "if(!d)return;"
908
+ "d.querySelectorAll('[data-seq]').forEach(function(e){e.style.background='';});"
909
+ "this.style.outline='';"
910
+ )
911
+
912
+ TR_BASE = "border-bottom:1px solid #f0f4ff;"
913
+ TH = (
914
+ "padding:6px 10px;font-size:11px;font-weight:700;text-transform:uppercase;"
915
+ "letter-spacing:.5px;white-space:nowrap;"
916
+ )
917
+
918
+ rows_html = []
919
+ current_layer = None
920
+ layer_rank = 0
921
+ for _rank, record in enumerate(records, 1):
922
+ diff_val, layer, feat_idx, act1, act2 = record[:5]
923
+ acts1_pos = record[5] if len(record) > 5 else None
924
+ acts2_pos = record[6] if len(record) > 6 else None
925
+
926
+ # Insert a layer-group header row whenever the layer changes
927
+ if layer != current_layer:
928
+ current_layer = layer
929
+ layer_rank = 0
930
+ rows_html.append(
931
+ f'<tr style="background:#eef2ff;border-top:2px solid #c7d2e8;">'
932
+ f'<td colspan="6" style="padding:4px 12px;font-size:11px;font-weight:700;'
933
+ f'color:#2563eb;letter-spacing:.5px;">Layer {layer}</td>'
934
+ f'</tr>'
935
+ )
936
+ layer_rank += 1
937
+
938
+ bar_w = max(2, int(120 * diff_val / (_layer_max.get(layer) or 1.0)))
939
+ if act1 >= act2:
940
+ bar_color = "#2563eb"
941
+ dir_label = "Ex&nbsp;1&nbsp;▲"
942
+ dir_color = "#2563eb"
943
+ row_bg = "background:#f5f8ff;"
944
+ else:
945
+ bar_color = "#dc2626"
946
+ dir_label = "Ex&nbsp;2&nbsp;▲"
947
+ dir_color = "#dc2626"
948
+ row_bg = "background:#fff5f5;"
949
+
950
+ # Embed per-position activation arrays for the hover handler
951
+ if acts1_pos is not None and acts2_pos is not None:
952
+ a1_json = _json.dumps(acts1_pos)
953
+ a2_json = _json.dumps(acts2_pos)
954
+ tr_open = (
955
+ f"<tr style='{TR_BASE}{row_bg}cursor:pointer;'"
956
+ f" data-acts1='{a1_json}'"
957
+ f" data-acts2='{a2_json}'"
958
+ f' onmouseenter="{_JS_ENTER}"'
959
+ f' onmouseleave="{_JS_LEAVE}">'
960
+ )
961
+ else:
962
+ tr_open = f'<tr style="{TR_BASE}{row_bg}">'
963
+
964
+ rows_html.append(
965
+ tr_open
966
+ + f'<td style="padding:5px 10px;text-align:center;color:#9ca3af;font-size:11px;">{layer_rank}</td>'
967
+ + f'<td style="padding:5px 10px;font-family:monospace;color:#2563eb;">#{feat_idx}</td>'
968
+ + f'<td style="padding:5px 8px;text-align:right;font-family:monospace;color:#374151;">{act1:.1%}</td>'
969
+ + f'<td style="padding:5px 8px;text-align:right;font-family:monospace;color:#374151;">{act2:.1%}</td>'
970
+ + f'<td style="padding:5px 10px;">'
971
+ + f' <div style="display:flex;align-items:center;gap:6px;">'
972
+ + f' <div style="width:{bar_w}px;height:10px;background:{bar_color};'
973
+ + f' border-radius:3px;flex-shrink:0;"></div>'
974
+ + f' <span style="font-family:monospace;font-size:12px;color:#374151;">{diff_val:.1%}</span>'
975
+ + f' </div>'
976
+ + f'</td>'
977
+ + f'<td style="padding:5px 10px;font-size:11px;font-weight:700;color:{dir_color};">'
978
+ + f'{dir_label}</td>'
979
+ + '</tr>'
980
+ )
981
+
982
+ ex1_short = _html.escape(text1[:50] + "…" if len(text1) > 50 else text1)
983
+ ex2_short = _html.escape(text2[:50] + "…" if len(text2) > 50 else text2)
984
+
985
+ legend = (
986
+ '<div style="display:flex;flex-wrap:wrap;gap:16px;margin-top:12px;'
987
+ 'font-size:11px;color:#6b7280;">'
988
+ f'<span><span style="color:#2563eb;font-weight:700;">■ Ex 1</span>'
989
+ f' "{ex1_short}"</span>'
990
+ f'<span><span style="color:#dc2626;font-weight:700;">■ Ex 2</span>'
991
+ f' "{ex2_short}"</span>'
992
+ '</div>'
993
+ )
994
+
995
+ table_inner = (
996
+ '<div style="overflow-x:auto;max-height:560px;overflow-y:auto;color:#1e293b;">'
997
+ '<table style="border-collapse:collapse;width:100%;color:#1e293b;'
998
+ 'font-family:ui-monospace,monospace;font-size:13px;">'
999
+ '<thead style="background:#f8faff;color:#1e293b;border-bottom:2px solid #c7d2e8;'
1000
+ 'position:sticky;top:0;z-index:2;">'
1001
+ '<tr>'
1002
+ f'<th style="{TH}color:#9ca3af;">Rank</th>'
1003
+ f'<th style="{TH}color:#2563eb;">Feature</th>'
1004
+ f'<th style="{TH}color:#2563eb;text-align:right;">Rate&nbsp;Ex&nbsp;1</th>'
1005
+ f'<th style="{TH}color:#dc2626;text-align:right;">Rate&nbsp;Ex&nbsp;2</th>'
1006
+ f'<th style="{TH}color:#6b7280;">|Rate diff|</th>'
1007
+ f'<th style="{TH}color:#6b7280;">Higher</th>'
1008
+ '</tr>'
1009
+ '</thead>'
1010
+ f'<tbody>{"".join(rows_html)}</tbody>'
1011
+ '</table>'
1012
+ '</div>'
1013
+ )
1014
+
1015
+ feature_table_html = (
1016
+ '<div style="padding:2px;">'
1017
+ + table_inner
1018
+ + legend
1019
+ + '</div>'
1020
+ )
1021
+
1022
+ return tok_display_html, feature_table_html
1023
+
1024
+
1025
+ def cb_compare(text1: str, text2: str, layer_from: int, layer_to: int,
1026
+ top_k: int, skip_first: bool,
1027
+ remove_common_toks: bool, remove_prefix: bool,
1028
+ raw_acts: bool = False):
1029
+ try:
1030
+ if not text1.strip() or not text2.strip():
1031
+ raise gr.Error("Both examples must be non-empty.")
1032
+
1033
+ model, tokenizer = get_model()
1034
+ layer_from = int(layer_from)
1035
+ layer_to = int(layer_to)
1036
+ top_k = int(top_k)
1037
+ if layer_from > layer_to:
1038
+ layer_from, layer_to = layer_to, layer_from
1039
+ layers = list(range(layer_from, layer_to + 1))
1040
+
1041
+ # ── Tokenise ─────────────────────────────────────────────────────────
1042
+ model_dev = next(model.parameters()).device
1043
+ ids1 = tokenizer.encode(text1, return_tensors='pt').to(model_dev)
1044
+ ids2 = tokenizer.encode(text2, return_tensors='pt').to(model_dev)
1045
+ toks1 = ids1[0].tolist()
1046
+ toks2 = ids2[0].tolist()
1047
+
1048
+ # ── Build per-sequence keep-index lists ───────────────────────────────
1049
+ prefix_len = 0
1050
+ if remove_prefix:
1051
+ for a, b in zip(toks1, toks2):
1052
+ if a == b:
1053
+ prefix_len += 1
1054
+ else:
1055
+ break
1056
+
1057
+ common_tok_ids: set = set()
1058
+ if remove_common_toks:
1059
+ common_tok_ids = set(toks1) & set(toks2)
1060
+
1061
+ def _build_keep(toks: list) -> list:
1062
+ return [
1063
+ i for i, t in enumerate(toks)
1064
+ if not (skip_first and i == 0)
1065
+ and i >= prefix_len
1066
+ and t not in common_tok_ids
1067
+ ]
1068
+
1069
+ keep1 = _build_keep(toks1)
1070
+ keep2 = _build_keep(toks2)
1071
+
1072
+ # ── Capture hidden states for all layers in two forward passes ────────
1073
+ hiddens1 = capture_all_hiddens(model, ids1, layers)
1074
+ hiddens2 = capture_all_hiddens(model, ids2, layers)
1075
+
1076
+ # Decoded token strings for the HTML token display
1077
+ tokens1_str = [tokenizer.decode([t]) for t in toks1]
1078
+ tokens2_str = [tokenizer.decode([t]) for t in toks2]
1079
+
1080
+ # ── Per-layer feature activation-rate difference ──────────────────────
1081
+ # Activation rate = fraction of kept positions where the feature fires
1082
+ # (activation > 0). Ranking by |rate1 − rate2| highlights features
1083
+ # that are selectively active in one example but not the other.
1084
+ # Load one SAE at a time to avoid OOM (each SAE is ~1-2 GB on GPU).
1085
+ candidates = [] # (abs_diff, layer, feat_idx, rate1, rate2,
1086
+ # acts1_per_pos, acts2_per_pos)
1087
+ for layer in layers:
1088
+ sae = get_sae(layer)
1089
+
1090
+ # Full per-position feature activations — stay on SAE_DEVICE for GPU math
1091
+ feats1 = compute_sae_features(hiddens1[layer], sae, raw=raw_acts) # [seq1_len, SAE_WIDTH]
1092
+ feats2 = compute_sae_features(hiddens2[layer], sae, raw=raw_acts) # [seq2_len, SAE_WIDTH]
1093
+
1094
+ # Activation rate = fraction of kept positions where feature fires (> 0)
1095
+ def _rate(feats: torch.Tensor, keep_idx: list) -> torch.Tensor:
1096
+ if not keep_idx:
1097
+ return torch.zeros(feats.shape[1], device=feats.device, dtype=feats.dtype)
1098
+ return (feats[keep_idx] > 0).float().mean(dim=0)
1099
+
1100
+ r1 = _rate(feats1, keep1)
1101
+ r2 = _rate(feats2, keep2)
1102
+ diff = (r1 - r2).abs()
1103
+
1104
+ # Top-k per layer (all kept — no global trim)
1105
+ local_k = min(top_k, SAE_WIDTH)
1106
+ vals, idxs = torch.topk(diff, local_k)
1107
+ for v, fi in zip(vals.tolist(), idxs.tolist()):
1108
+ # Round to 3 dp — enough precision for color interpolation
1109
+ a1_pos = [round(x, 3) for x in feats1[:, fi].tolist()]
1110
+ a2_pos = [round(x, 3) for x in feats2[:, fi].tolist()]
1111
+ candidates.append((v, layer, fi, float(r1[fi]), float(r2[fi]),
1112
+ a1_pos, a2_pos))
1113
+
1114
+ # Free SAE weights and feature tensors before loading the next layer
1115
+ del sae, feats1, feats2, diff
1116
+
1117
+ # Single cache clear after all layers — calling it per-layer is expensive
1118
+ if torch.cuda.is_available():
1119
+ torch.cuda.empty_cache()
1120
+
1121
+ # ── Per-layer sort: group by layer, within each layer sort by diff desc ─
1122
+ candidates.sort(key=lambda x: (x[1], -x[0]))
1123
+ diff_lookup: dict = {}
1124
+ for diff_val, layer, feat_idx, *_ in candidates:
1125
+ key = (layer, feat_idx)
1126
+ if key not in diff_lookup or diff_val > diff_lookup[key]:
1127
+ diff_lookup[key] = diff_val
1128
+ tok_html, table_html = compare_to_html(candidates, text1, text2, tokens1_str, tokens2_str)
1129
+ return tok_html, table_html, diff_lookup
1130
+
1131
+ except gr.Error:
1132
+ raise
1133
+ except Exception as e:
1134
+ raise gr.Error(f"Comparison failed: {e}")
1135
+
1136
+
1137
+ # ─── CSS ─────────────────────────────────────────────────────────────────────
1138
+
1139
+ CSS = """
1140
+ /* ══════════════════════════════════════════════════════════════════
1141
+ Color tokens — single source of truth for light / dark palettes
1142
+ ══════════════════════════════════════════════════════════════════ */
1143
+ :root {
1144
+ --c-page-bg: #f4f6fb;
1145
+ --c-card-bg: #ffffff;
1146
+ --c-card-border: #e4e7ef;
1147
+ --c-card-shadow: 0 1px 4px rgba(0,0,0,0.06), 0 4px 16px rgba(0,0,0,0.04);
1148
+ --c-header-bg: linear-gradient(135deg,#eff6ff 0%,#e0eaff 55%,#ede9fe 100%);
1149
+ --c-header-border:#c7d2fe;
1150
+ --c-header-text: #1e293b;
1151
+ --c-header-h1: #1e3a8a;
1152
+ --c-header-p: #475569;
1153
+ --c-pill-bg: rgba(37,99,235,0.08);
1154
+ --c-pill-border: rgba(37,99,235,0.22);
1155
+ --c-pill-text: #1e3a8a;
1156
+ --c-chip-bg: #eff4ff;
1157
+ --c-chip-text: #2563eb;
1158
+ --c-btn2-bg: #f8faff;
1159
+ --c-btn2-border: #d0d7e8;
1160
+ --c-btn2-text: #374151;
1161
+ --c-outbox-bg: #fafbff;
1162
+ --c-outbox-text: #1e293b;
1163
+ --c-outbox-border:#e4e7ef;
1164
+ --c-tab-text: #374151;
1165
+ --c-tab-sel: #2563eb;
1166
+ --c-divider: #dde3f0;
1167
+ --c-th-bg: #f0f4ff;
1168
+ --c-th-text: #2563eb;
1169
+ }
1170
+
1171
+ /* Dark mode via OS/browser preference */
1172
+ @media (prefers-color-scheme: dark) {
1173
+ :root {
1174
+ --c-page-bg: #0f172a;
1175
+ --c-card-bg: #1e293b;
1176
+ --c-card-border: #334155;
1177
+ --c-card-shadow: 0 1px 4px rgba(0,0,0,0.40), 0 4px 16px rgba(0,0,0,0.25);
1178
+ --c-header-bg: linear-gradient(135deg,#172554 0%,#1e3a8a 55%,#3b0764 100%);
1179
+ --c-header-border:#1e40af;
1180
+ --c-header-text: #e2e8f0;
1181
+ --c-header-h1: #bfdbfe;
1182
+ --c-header-p: #94a3b8;
1183
+ --c-pill-bg: rgba(96,165,250,0.12);
1184
+ --c-pill-border: rgba(96,165,250,0.30);
1185
+ --c-pill-text: #93c5fd;
1186
+ --c-chip-bg: #172554;
1187
+ --c-chip-text: #93c5fd;
1188
+ --c-btn2-bg: #1e293b;
1189
+ --c-btn2-border: #475569;
1190
+ --c-btn2-text: #e2e8f0;
1191
+ --c-outbox-bg: #0f172a;
1192
+ --c-outbox-text: #e2e8f0;
1193
+ --c-outbox-border:#334155;
1194
+ --c-tab-text: #94a3b8;
1195
+ --c-tab-sel: #60a5fa;
1196
+ --c-divider: #334155;
1197
+ --c-th-bg: #172554;
1198
+ --c-th-text: #93c5fd;
1199
+ }
1200
+ }
1201
+
1202
+ /* Dark mode via Gradio's explicit dark-mode class (toggled manually) */
1203
+ .dark {
1204
+ --c-page-bg: #0f172a;
1205
+ --c-card-bg: #1e293b;
1206
+ --c-card-border: #334155;
1207
+ --c-card-shadow: 0 1px 4px rgba(0,0,0,0.40), 0 4px 16px rgba(0,0,0,0.25);
1208
+ --c-header-bg: linear-gradient(135deg,#172554 0%,#1e3a8a 55%,#3b0764 100%);
1209
+ --c-header-border:#1e40af;
1210
+ --c-header-text: #e2e8f0;
1211
+ --c-header-h1: #bfdbfe;
1212
+ --c-header-p: #94a3b8;
1213
+ --c-pill-bg: rgba(96,165,250,0.12);
1214
+ --c-pill-border: rgba(96,165,250,0.30);
1215
+ --c-pill-text: #93c5fd;
1216
+ --c-chip-bg: #172554;
1217
+ --c-chip-text: #93c5fd;
1218
+ --c-btn2-bg: #1e293b;
1219
+ --c-btn2-border: #475569;
1220
+ --c-btn2-text: #e2e8f0;
1221
+ --c-outbox-bg: #0f172a;
1222
+ --c-outbox-text: #e2e8f0;
1223
+ --c-outbox-border:#334155;
1224
+ --c-tab-text: #94a3b8;
1225
+ --c-tab-sel: #60a5fa;
1226
+ --c-divider: #334155;
1227
+ --c-th-bg: #172554;
1228
+ --c-th-text: #93c5fd;
1229
+ }
1230
+
1231
+ /* ── Page background ── */
1232
+ body, .gradio-container { background: var(--c-page-bg) !important; }
1233
+
1234
+ /* ── Header card ── */
1235
+ .header-card {
1236
+ background: var(--c-header-bg);
1237
+ border-radius: 14px;
1238
+ padding: 22px 28px 18px;
1239
+ margin-bottom: 4px;
1240
+ color: var(--c-header-text);
1241
+ box-shadow: 0 4px 20px rgba(37,99,235,0.10);
1242
+ border: 1px solid var(--c-header-border);
1243
+ }
1244
+ .header-card h1 { margin:0 0 6px; font-size:24px; font-weight:700; letter-spacing:-.3px; color:var(--c-header-h1); }
1245
+ .header-card p { margin:0; font-size:13px; color:var(--c-header-p); }
1246
+ .stat-pill {
1247
+ display:inline-block;
1248
+ background:var(--c-pill-bg);
1249
+ border:1px solid var(--c-pill-border);
1250
+ border-radius:20px;
1251
+ padding:3px 13px;
1252
+ font-size:12px;
1253
+ color:var(--c-pill-text);
1254
+ margin:4px 3px 0;
1255
+ }
1256
+
1257
+ /* ── Panel cards ── */
1258
+ .panel-card {
1259
+ background: var(--c-card-bg) !important;
1260
+ border-radius: 12px !important;
1261
+ box-shadow: var(--c-card-shadow) !important;
1262
+ border: 1px solid var(--c-card-border) !important;
1263
+ padding: 18px !important;
1264
+ }
1265
+ .panel-card > .form { gap: 12px !important; }
1266
+
1267
+ /* ── Section label chips ── */
1268
+ .section-chip {
1269
+ font-size: 11px;
1270
+ font-weight: 700;
1271
+ text-transform: uppercase;
1272
+ letter-spacing: .8px;
1273
+ color: var(--c-chip-text);
1274
+ background: var(--c-chip-bg);
1275
+ border-radius: 6px;
1276
+ padding: 2px 10px;
1277
+ display: inline-block;
1278
+ margin-bottom: 10px;
1279
+ }
1280
+
1281
+ /* ── Buttons ── */
1282
+ .btn-primary {
1283
+ background: linear-gradient(135deg, #2563eb, #6d28d9) !important;
1284
+ border: none !important;
1285
+ border-radius: 8px !important;
1286
+ font-weight: 600 !important;
1287
+ font-size: 14px !important;
1288
+ letter-spacing: .2px !important;
1289
+ box-shadow: 0 2px 10px rgba(37,99,235,0.30) !important;
1290
+ transition: all 0.18s ease !important;
1291
+ color: #fff !important;
1292
+ padding: 10px 0 !important;
1293
+ }
1294
+ .btn-primary:hover {
1295
+ transform: translateY(-1px) !important;
1296
+ box-shadow: 0 5px 18px rgba(37,99,235,0.40) !important;
1297
+ }
1298
+ .btn-secondary {
1299
+ border-radius: 8px !important;
1300
+ font-weight: 500 !important;
1301
+ font-size: 13px !important;
1302
+ border: 1px solid var(--c-btn2-border) !important;
1303
+ background: var(--c-btn2-bg) !important;
1304
+ color: var(--c-btn2-text) !important;
1305
+ transition: all 0.15s ease !important;
1306
+ }
1307
+ .btn-secondary:hover {
1308
+ background: var(--c-chip-bg) !important;
1309
+ border-color: var(--c-tab-sel) !important;
1310
+ }
1311
+
1312
+ /* ── Output boxes ── */
1313
+ .output-box textarea {
1314
+ font-family: ui-monospace, monospace !important;
1315
+ font-size: 13px !important;
1316
+ line-height: 1.7 !important;
1317
+ background: var(--c-outbox-bg) !important;
1318
+ color: var(--c-outbox-text) !important;
1319
+ border-color: var(--c-outbox-border) !important;
1320
+ border-radius: 8px !important;
1321
+ }
1322
+
1323
+ /* ── Dataframe ── */
1324
+ .feature-table table { font-family: ui-monospace, monospace; font-size: 13px; }
1325
+ .feature-table th { background: var(--c-th-bg) !important; color: var(--c-th-text) !important;
1326
+ font-weight: 600; font-size: 12px; text-transform: uppercase; }
1327
+
1328
+ /* ── Tab styling ── */
1329
+ .tab-nav button {
1330
+ font-weight: 600 !important;
1331
+ font-size: 14px !important;
1332
+ border-radius: 8px 8px 0 0 !important;
1333
+ color: var(--c-tab-text) !important;
1334
+ }
1335
+ .tab-nav button.selected {
1336
+ color: var(--c-tab-sel) !important;
1337
+ border-bottom: 2px solid var(--c-tab-sel) !important;
1338
+ }
1339
+
1340
+ /* ── Divider ── */
1341
+ .section-divider {
1342
+ border: none;
1343
+ border-top: 1px dashed var(--c-divider);
1344
+ margin: 6px 0 10px;
1345
+ }
1346
+
1347
+ /* ── Slider label ── */
1348
+ label.svelte-1b6s6sv { font-size: 13px !important; font-weight: 500 !important; }
1349
+ """
1350
+
1351
+ # ─── Build the Gradio interface ───────────────────────────────────────────────
1352
+
1353
+ with gr.Blocks(title="Qwen-Scope Feature Explorer") as demo:
1354
+
1355
+ # ── Header ────────────────────────────────────────────────────────────────
1356
+ gr.HTML(
1357
+ '<div class="header-card">'
1358
+ ' <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px;">'
1359
+ ' <img src="https://cdn-avatars.huggingface.co/v1/production/uploads/620760a26e3b7210c2ff1943/-s1gyJfvbE1RgO5iBeNOi.png" alt="Qwen Logo" style="height:24px;width:auto;">'
1360
+ ' <h1 style="margin:0;">Qwen-Scope Feature Explorer</h1>'
1361
+ ' </div>'
1362
+ f' <p>Interpret {MODEL_NAME_ANALYZING_NOW} via Sparse Autoencoders trained on each residual-stream layer from {MODEL_NAME_SAE_TRAINED_FROM}.</p>'
1363
+ ' <div style="margin-top:10px;">'
1364
+ f' <span class="stat-pill">Model: {MODEL_NAME_ANALYZING_NOW}</span>'
1365
+ f' <span class="stat-pill">SAE trained from: {MODEL_NAME_SAE_TRAINED_FROM}</span>'
1366
+ f' <span class="stat-pill">Layers: {NUM_LAYERS}</span>'
1367
+ f' <span class="stat-pill">SAE width: {SAE_WIDTH:,}</span>'
1368
+ f' <span class="stat-pill">Top-k: {TOP_K}</span>'
1369
+ f' <span class="stat-pill">d_model: {D_MODEL}</span>'
1370
+ ' </div>'
1371
+ '</div>'
1372
+ )
1373
+
1374
+ analysis_state = gr.State(None) # (list[str] tokens, Tensor[seq, sae_width] features)
1375
+ compare_diff_state = gr.State({})
1376
+
1377
+ with gr.Tabs(elem_classes="tab-nav"):
1378
+
1379
+ # ══════════════════════════════════════════════════════════════════════
1380
+ # Tab 1 — Feature Comparison
1381
+ # ══════════════════════════════════════════════════════════════════════
1382
+ with gr.Tab("⚖️ Feature Comparison"):
1383
+
1384
+ with gr.Row(equal_height=False):
1385
+
1386
+ # ── Left column: inputs + settings + token preview ─────────────
1387
+ with gr.Column(scale=2, min_width=300):
1388
+
1389
+ with gr.Accordion("Examples", open=True) as t3_examples_accordion:
1390
+ with gr.Group(elem_classes="panel-card"):
1391
+ gr.HTML('<span class="section-chip">Examples</span>')
1392
+ t3_text1 = gr.Textbox(
1393
+ label="Example 1",
1394
+ lines=5,
1395
+ placeholder="Paste first text here…",
1396
+ )
1397
+ t3_text2 = gr.Textbox(
1398
+ label="Example 2",
1399
+ lines=5,
1400
+ placeholder="Paste second text here…",
1401
+ )
1402
+
1403
+ with gr.Accordion("Comparison Settings", open=True) as t3_settings_accordion:
1404
+ with gr.Group(elem_classes="panel-card"):
1405
+ gr.HTML('<span class="section-chip">Comparison Settings</span>')
1406
+ with gr.Row():
1407
+ t3_layer_from = gr.Slider(
1408
+ minimum=0, maximum=NUM_LAYERS - 1,
1409
+ value=0, step=1,
1410
+ label="Layer from",
1411
+ scale=1,
1412
+ )
1413
+ t3_layer_to = gr.Slider(
1414
+ minimum=0, maximum=NUM_LAYERS - 1,
1415
+ value=NUM_LAYERS - 1, step=1,
1416
+ label="Layer to",
1417
+ scale=1,
1418
+ )
1419
+ t3_topk = gr.Number(
1420
+ value=5, precision=0,
1421
+ label="Top-K results",
1422
+ info="Number of (layer, feature) pairs to surface.",
1423
+ )
1424
+ with gr.Accordion("Advanced options", open=False):
1425
+ t3_skip_first = gr.Checkbox(
1426
+ label="Exclude first token",
1427
+ value=False,
1428
+ info="Skip position 0 when computing mean activations.",
1429
+ )
1430
+ t3_remove_common_toks = gr.Checkbox(
1431
+ label="Remove common tokens",
1432
+ value=False,
1433
+ info="Exclude positions whose token ID appears in both examples.",
1434
+ )
1435
+ t3_remove_prefix = gr.Checkbox(
1436
+ label="Remove common prefix",
1437
+ value=False,
1438
+ info="Exclude the longest token-level prefix shared by both examples.",
1439
+ )
1440
+ t3_run = gr.Button(
1441
+ "⚖️ Compare Features",
1442
+ variant="primary",
1443
+ elem_classes="btn-primary",
1444
+ )
1445
+
1446
+ with gr.Accordion("Features", open=True) as t3_features_accordion:
1447
+ with gr.Group(elem_classes="panel-card"):
1448
+ gr.HTML(
1449
+ '<span class="section-chip">Feature Comparison</span>'
1450
+ '<span style="font-size:12px;color:#888;margin-left:8px;">'
1451
+ 'top-K features per layer · ranked by |rate(Ex1) − rate(Ex2)|'
1452
+ ' where rate = fraction of token positions where the feature fires · grouped by layer'
1453
+ '</span>'
1454
+ )
1455
+ t3_out = gr.HTML(
1456
+ value=(
1457
+ '<div style="min-height:80px;display:flex;align-items:center;'
1458
+ 'justify-content:center;color:#bbb;font-size:13px;">'
1459
+ 'Enter two examples and click Compare.</div>'
1460
+ )
1461
+ )
1462
+
1463
+ # ── Right column: token activations ───────────────────────────
1464
+ with gr.Column(scale=3, min_width=380):
1465
+ with gr.Group(elem_classes="panel-card"):
1466
+ gr.HTML(
1467
+ '<span class="section-chip">Token Activations</span>'
1468
+ '<span style="font-size:12px;color:#888;margin-left:8px;">'
1469
+ 'hover a feature row on the left to highlight activations'
1470
+ '</span>'
1471
+ )
1472
+ t3_tok_html = gr.HTML(
1473
+ value=(
1474
+ '<div style="min-height:60px;display:flex;align-items:center;'
1475
+ 'justify-content:center;color:#bbb;font-size:13px;padding:8px;">'
1476
+ 'Run Compare to see token activations here.</div>'
1477
+ )
1478
+ )
1479
+
1480
+ # ══════════════════════════════════════════════════════════════════════
1481
+ # Tab 2 — Feature Steering
1482
+ # ══════════════════════════════════════════════════════════════════════
1483
+ with gr.Tab("🎛️ Feature Steering"):
1484
+
1485
+ with gr.Row(equal_height=False):
1486
+
1487
+ # ── Left column: prompt + steering controls ────────────────
1488
+ with gr.Column(scale=2, min_width=280):
1489
+ with gr.Group(elem_classes="panel-card"):
1490
+ gr.HTML('<span class="section-chip">Prompt</span>')
1491
+ t2_prompt = gr.Textbox(
1492
+ label=None,
1493
+ lines=5,
1494
+ placeholder="Enter a generation prompt…",
1495
+ show_label=False,
1496
+ )
1497
+
1498
+ gr.HTML('<span class="section-chip">Token Position Preview</span>'
1499
+ '<span style="font-size:12px;color:#888;margin-left:8px;">'
1500
+ 'amber = steered &nbsp;·&nbsp; updates as you type'
1501
+ '</span>')
1502
+
1503
+ t2_pos_preview = gr.HTML(
1504
+ value=(
1505
+ '<div style="padding:10px;color:#bbb;font-size:13px;">'
1506
+ 'Enter a prompt above to preview steered positions.</div>'
1507
+ )
1508
+ )
1509
+
1510
+ with gr.Group(elem_classes="panel-card"):
1511
+ gr.HTML('<span class="section-chip">Steering Parameters</span>')
1512
+
1513
+ with gr.Row():
1514
+ t2_layer = gr.Slider(
1515
+ minimum=0, maximum=NUM_LAYERS - 1,
1516
+ value=10, step=1,
1517
+ label="Layer",
1518
+ scale=3,
1519
+ )
1520
+ t2_feat = gr.Number(
1521
+ value=0, precision=0,
1522
+ label="Feature index",
1523
+ info=f"0 – {SAE_WIDTH - 1}",
1524
+ scale=2,
1525
+ )
1526
+
1527
+ t2_pos = gr.Textbox(
1528
+ label="Token positions to steer",
1529
+ value="all",
1530
+ placeholder="all | 0,1,5 | 3-7 | 0,2,5-8",
1531
+ info=(
1532
+ "all → every token | "
1533
+ "0,1,5 → individual positions | "
1534
+ "3-7 → inclusive range | "
1535
+ "combinations e.g. 0,2,5-8"
1536
+ ),
1537
+ )
1538
+ t2_steer_output_only = gr.Checkbox(
1539
+ label="Also steer generated tokens",
1540
+ value=True,
1541
+ info=(
1542
+ "When enabled, every generated token is steered in addition to "
1543
+ "whatever the positions field specifies for the prompt."
1544
+ ),
1545
+ )
1546
+
1547
+ gr.HTML('<span class="section-chip">Steering Strength</span>')
1548
+ t2_steer_mode = gr.Radio(
1549
+ choices=["Light", "Medium", "Strong", "Custom"],
1550
+ value="Light",
1551
+ label=None,
1552
+ show_label=False,
1553
+ info=(
1554
+ "Calibrated to the most different feature found in "
1555
+ "Feature Comparison. Run that tab first."
1556
+ ),
1557
+ )
1558
+ t2_custom_strength = gr.Number(
1559
+ value=5.0,
1560
+ label="Custom strength",
1561
+ info="Direct steering magnitude (used when Custom is selected above).",
1562
+ visible=False,
1563
+ precision=2,
1564
+ )
1565
+ t2_steer_info = gr.HTML(
1566
+ value=(
1567
+ '<div style="font-size:11px;color:#888;padding:4px 6px;'
1568
+ 'background:#f8faff;border-radius:5px;">'
1569
+ 'Light ≈ 5.0 · Medium ≈ 20.0 · Strong ≈ 100.0<br>'
1570
+ '<span style="color:#bbb;">Run Feature Comparison to calibrate.</span>'
1571
+ '</div>'
1572
+ )
1573
+ )
1574
+
1575
+ gr.HTML('<hr class="section-divider">')
1576
+ with gr.Accordion("Sampling options", open=False):
1577
+ t2_maxtok = gr.Slider(
1578
+ minimum=20, maximum=300,
1579
+ value=100, step=10,
1580
+ label="Max new tokens",
1581
+ )
1582
+ t2_greedy = gr.Checkbox(
1583
+ label="Greedy decoding",
1584
+ value=True,
1585
+ info="When enabled, all sampling parameters below are ignored.",
1586
+ )
1587
+ with gr.Row():
1588
+ t2_temperature = gr.Slider(
1589
+ minimum=0.01, maximum=2.0,
1590
+ value=GEN_TEMPERATURE, step=0.01,
1591
+ label="Temperature",
1592
+ interactive=GEN_DO_SAMPLE,
1593
+ )
1594
+ t2_top_p = gr.Slider(
1595
+ minimum=0.0, maximum=1.0,
1596
+ value=GEN_TOP_P, step=0.01,
1597
+ label="Top-p (nucleus)",
1598
+ interactive=GEN_DO_SAMPLE,
1599
+ )
1600
+ with gr.Row():
1601
+ t2_top_k_tok = gr.Slider(
1602
+ minimum=0, maximum=200,
1603
+ value=GEN_TOP_K, step=1,
1604
+ label="Top-k (tokens)",
1605
+ info="0 = disabled",
1606
+ interactive=GEN_DO_SAMPLE,
1607
+ )
1608
+ t2_rep_penalty = gr.Slider(
1609
+ minimum=1.0, maximum=3.0,
1610
+ value=GEN_REP_PENALTY, step=0.05,
1611
+ label="Repetition penalty",
1612
+ info="1.0 = no penalty",
1613
+ interactive=GEN_DO_SAMPLE,
1614
+ )
1615
+
1616
+ t2_run = gr.Button(
1617
+ "▶ Generate Both Outputs",
1618
+ variant="primary",
1619
+ elem_classes="btn-primary",
1620
+ )
1621
+
1622
+ # ── Right column: outputs ──────────────────────────────────
1623
+ with gr.Column(scale=3, min_width=380):
1624
+
1625
+ with gr.Group(elem_classes="panel-card"):
1626
+ gr.HTML(
1627
+ '<span class="section-chip">Original Output</span>'
1628
+ '<span style="font-size:12px;color:#888;margin-left:8px;">'
1629
+ 'No steering applied</span>'
1630
+ )
1631
+ t2_orig = gr.Textbox(
1632
+ label=None, lines=7,
1633
+ interactive=False,
1634
+ show_label=False,
1635
+ placeholder="Original generation will appear here…",
1636
+ elem_classes="output-box",
1637
+ )
1638
+ gr.HTML(
1639
+ '<span class="section-chip" style="margin-top:10px;'
1640
+ 'display:inline-block;">Token Probabilities</span>'
1641
+ '<span style="font-size:12px;color:#888;margin-left:8px;">'
1642
+ 'blue intensity = confidence &nbsp;·&nbsp; hover = top-k</span>'
1643
+ )
1644
+ t2_orig_probs = gr.HTML(
1645
+ value='<div style="padding:10px;color:#bbb;font-size:13px;">'
1646
+ 'Run generation to see token probabilities.</div>'
1647
+ )
1648
+
1649
+ with gr.Group(elem_classes="panel-card"):
1650
+ gr.HTML(
1651
+ '<span class="section-chip" style="background:#fef3f2;color:#dc2626;">'
1652
+ 'Steered Output</span>'
1653
+ '<span style="font-size:12px;color:#888;margin-left:8px;">'
1654
+ 'With SAE feature injection</span>'
1655
+ )
1656
+ t2_steered = gr.Textbox(
1657
+ label=None, lines=7,
1658
+ interactive=False,
1659
+ show_label=False,
1660
+ placeholder="Steered generation will appear here…",
1661
+ elem_classes="output-box",
1662
+ )
1663
+ gr.HTML(
1664
+ '<span class="section-chip" style="background:#fef3f2;color:#dc2626;'
1665
+ 'margin-top:10px;display:inline-block;">Token Probabilities</span>'
1666
+ '<span style="font-size:12px;color:#888;margin-left:8px;">'
1667
+ 'red intensity = confidence &nbsp;·&nbsp; hover = top-k</span>'
1668
+ )
1669
+ t2_steer_probs = gr.HTML(
1670
+ value='<div style="padding:10px;color:#bbb;font-size:13px;">'
1671
+ 'Run generation to see token probabilities.</div>'
1672
+ )
1673
+
1674
+ t2_run.click(
1675
+ cb_generate,
1676
+ inputs=[t2_prompt, t2_layer, t2_feat, t2_pos, t2_steer_mode, compare_diff_state,
1677
+ t2_steer_output_only, t2_maxtok,
1678
+ t2_greedy, t2_top_k_tok, t2_top_p, t2_rep_penalty,
1679
+ t2_temperature, t2_custom_strength],
1680
+ outputs=[t2_orig, t2_steered, t2_orig_probs, t2_steer_probs],
1681
+ )
1682
+ t3_run.click(
1683
+ cb_compare,
1684
+ inputs=[t3_text1, t3_text2, t3_layer_from, t3_layer_to, t3_topk,
1685
+ t3_skip_first, t3_remove_common_toks, t3_remove_prefix],
1686
+ outputs=[t3_tok_html, t3_out, compare_diff_state],
1687
+ ).then(
1688
+ fn=lambda: [gr.update(open=False), gr.update(open=False)],
1689
+ inputs=None,
1690
+ outputs=[t3_examples_accordion, t3_settings_accordion],
1691
+ )
1692
+ _sampling_controls = [
1693
+ t2_temperature, t2_top_p, t2_top_k_tok, t2_rep_penalty
1694
+ ]
1695
+ t2_greedy.change(
1696
+ fn=lambda g: [gr.update(interactive=not g)] * 4,
1697
+ inputs=[t2_greedy],
1698
+ outputs=_sampling_controls,
1699
+ )
1700
+ t2_prompt.change(
1701
+ cb_update_steer_preview,
1702
+ inputs=[t2_prompt, t2_pos],
1703
+ outputs=[t2_pos_preview],
1704
+ )
1705
+ t2_pos.change(
1706
+ cb_update_steer_preview,
1707
+ inputs=[t2_prompt, t2_pos],
1708
+ outputs=[t2_pos_preview],
1709
+ )
1710
+
1711
+ def _update_steer_info(mode: str, diff_lookup, layer, feat_idx):
1712
+ if mode == "Custom":
1713
+ return (
1714
+ '<div style="font-size:11px;color:#555;padding:4px 6px;'
1715
+ 'background:#f8faff;border-radius:5px;">'
1716
+ 'Enter a custom steering strength value above.'
1717
+ '</div>'
1718
+ )
1719
+ d = 0.0
1720
+ source_note = '<span style="color:#bbb;">Run Feature Comparison to calibrate.</span>'
1721
+ if diff_lookup and isinstance(diff_lookup, dict):
1722
+ key = (int(layer), int(feat_idx))
1723
+ if key in diff_lookup:
1724
+ d = float(diff_lookup[key])
1725
+ source_note = (
1726
+ f'<span style="color:#16a34a;">feature #{int(feat_idx)} '
1727
+ f'@ layer {int(layer)} · diff = {d:.3f}</span>'
1728
+ )
1729
+ else:
1730
+ d = float(max(diff_lookup.values(), default=0.0))
1731
+ source_note = (
1732
+ f'<span style="color:#64748b;">feature not in compare results — '
1733
+ f'using global max diff = {d:.3f}</span>'
1734
+ )
1735
+ if d <= 0:
1736
+ vals = {"Light": 5.0, "Medium": 20.0, "Strong": 100.0}
1737
+ else:
1738
+ vals = {
1739
+ "Light": round(d * 0.5, 2),
1740
+ "Medium": round(d * 2.0, 2),
1741
+ "Strong": round(d * 10.0, 2),
1742
+ }
1743
+ return (
1744
+ f'<div style="font-size:11px;color:#555;padding:4px 6px;'
1745
+ f'background:#f8faff;border-radius:5px;">'
1746
+ f'Light ≈ {vals["Light"]} · Medium ≈ {vals["Medium"]} · Strong ≈ {vals["Strong"]}<br>'
1747
+ + source_note + '</div>'
1748
+ )
1749
+
1750
+ _steer_info_inputs = [t2_steer_mode, compare_diff_state, t2_layer, t2_feat]
1751
+ for _trigger in [t2_steer_mode.change, compare_diff_state.change,
1752
+ t2_layer.change, t2_feat.change]:
1753
+ _trigger(
1754
+ fn=_update_steer_info,
1755
+ inputs=_steer_info_inputs,
1756
+ outputs=[t2_steer_info],
1757
+ )
1758
+
1759
+ # Show/hide custom strength input depending on radio selection
1760
+ t2_steer_mode.change(
1761
+ fn=lambda m: gr.update(visible=(m == "Custom")),
1762
+ inputs=[t2_steer_mode],
1763
+ outputs=[t2_custom_strength],
1764
+ )
1765
+
1766
+
1767
+ if __name__ == '__main__':
1768
+ # Pre-load model onto GPU before accepting requests, so the first
1769
+ # button click doesn't stall waiting for a 30 B-param model to load.
1770
+ print("Pre-loading model onto GPU…")
1771
+ get_model()
1772
+ print("Model ready. Starting Gradio server…")
1773
+ demo.queue(max_size=4)
1774
+ demo.launch(
1775
+ server_name="0.0.0.0",
1776
+ server_port=PORT,
1777
+ # share=True creates a public gradio.live URL that bypasses the
1778
+ # Alibaba Cloud DSW gateway (which blocks POST API requests).
1779
+ # The URL printed below is valid for 72 h.
1780
+ share=True,
1781
+ strict_cors=False,
1782
+ show_error=True,
1783
+ ssr_mode=False,
1784
+ theme=gr.themes.Soft(),
1785
+ css=CSS,
1786
+ )
layer0.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69129f6ae26396234ab8e53b98caf074cf75150ff8c8dec3e00cd31d39f979fe
3
+ size 2147764593
layer1.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd4a1339ecb1eeae3b8274440158871c96413492c4d5e640679b1cbb47043513
3
+ size 2147764593
layer10.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:96734ab9b2b10b768677009a20f587ab99ba123313463293c0d83c7d63bccd37
3
+ size 2147764603
layer11.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e742a79a5912597777f63138a9cc6dc32b03b14ab97c26ccd53e0eb0ec37383c
3
+ size 2147764603
layer12.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cea61ef74a4d33d59329f7e3d1ddfb4a8cdf3c24acdbc05fc26209679a262d8
3
+ size 2147764603
layer13.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d3e59e274dde3788878d33a4699b627a3db6df609d925554bde47360481d782
3
+ size 2147764603
layer14.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72068fa563576c2cf56845578b572016983b0b1e16839dfa6164e6b870378718
3
+ size 2147764603
layer15.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfcf588026d0a6f705c0698c0fff35cd60aab2ab8e30068a053a0d3f30870cf4
3
+ size 2147764603
layer16.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee9ed8c3b0ad9db9e693e7dcb2d514c73ecbe5142c9f372181b411728a8dd53c
3
+ size 2147764603
layer17.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6932199f08e4204716eef069c3dbc5ecf4e09b564425d0e057600e984b1257da
3
+ size 2147764603
layer18.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6129684c7157bce8d80f14ced2ff226199e428dfdee1c1628fa14dc8d1326290
3
+ size 2147764603
layer19.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9dea64a8f57adc672d33d5d7eb6803e00bdb03db54d29569092fa149e14a343c
3
+ size 2147764603
layer2.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:beaa1b97df06afcf92bb81635d1324ba66b7e22cb20e82e6e7e8391e234bc8c6
3
+ size 2147764593
layer20.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4edf66b6d80ae68abfd3f4c6fb4abaaa6c5eb3384578430a1f312e64c16a02c
3
+ size 2147764603
layer21.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ea6dca47bfc4f8f87c35d58aa268e9ce4590e9ed382e022a96160fff0db7692
3
+ size 2147764603
layer22.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:783f4fe04adcb6bf304097e5dd0fd5e29c08f242baed03473cb8c12879c2e8c6
3
+ size 2147764603
layer23.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e76df701b50e897b64d022be1223948b62baf7893ecdccc71e298303c4e8c2b4
3
+ size 2147764603
layer24.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de3a8016fb405890542ef39cf7dea75483f300cf3147783068fa6d9488865963
3
+ size 2147764603
layer25.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f68ada68522e042de7b0b57e5f6d283575d55eb5b9f7a00210ffb30cb38fa827
3
+ size 2147764603
layer26.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2ca4d2c2612a8b01fb583ed405e0e54e5cf99b2edf3c01719590a3fdfac4085
3
+ size 2147764603
layer27.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1704cc58e8457d01bcc8017dc0ada9e54705199e045905fa5604410cd1646fa1
3
+ size 2147764603
layer28.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0b35e4c81ca05f3bd90e1b0718a6df7a56ff2216556b92e36d89cd97f6cd6d3
3
+ size 2147764603
layer29.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ca7c8f787832210ad4b917767843c4f4e211fd50246e75b157cc89af2a29818
3
+ size 2147764603
layer3.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01518d66f44f565fda621f51fa8eb330d713b7d998c037c8650f21ca3fb0063b
3
+ size 2147764593
layer30.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:328a4fff07cfb8b3d6c5454e5b66386d3213657f1e9c5ade90608a2375be9898
3
+ size 2147764603
layer31.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0a76e3b4be583344525acbef6306784b26ecd085d73cc3349d86f7e0a3650a4
3
+ size 2147764603
layer4.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ee654feaa411556f93462ce2c8957f7de7914feb958b4da43e89c9fa2ebd14d
3
+ size 2147764593
layer5.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52240b6dc265d60604f8c73d5f85cc35e946952be1df8bd4b3a75449c998a79e
3
+ size 2147764593
layer6.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ea8e99dac31fb9189608850d8f03e83182d0cde9706d3cef7bfb87895d8ea55
3
+ size 2147764593
layer7.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3cd689b403efcb1cec1feb9c65d000bcfa1149f85df152f30098424753ba0817
3
+ size 2147764593
layer8.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7f79a9d930054189bdd76f256e75a8d9363d749e51254dc8beb011c68d1a47f
3
+ size 2147764593
layer9.sae.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:396e3027091cf9df31b639dd4a6916b170e83df3bbb6cedf42108e042dd0bddf
3
+ size 2147764593