Typony commited on
Commit
5b4c2a0
·
verified ·
1 Parent(s): 9ba1a66

initial upload

Browse files
Files changed (3) hide show
  1. JCBScope_utils.py +158 -0
  2. app.py +513 -0
  3. requirements.txt +4 -3
JCBScope_utils.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ from torch import nn
4
+
5
+ def get_lm_head(model):
6
+ if hasattr(model, 'lm_head'): # LLaMA models
7
+ return model.lm_head
8
+ elif hasattr(model, 'embed_out'): # GPTNeoX (Pythia) models
9
+ return model.embed_out
10
+ else:
11
+ raise ValueError(f"Unsupported model architecture: {type(model)}")
12
+
13
+ def get_input_embeddings(model):
14
+ if hasattr(model, 'get_input_embeddings'):
15
+ return model.get_input_embeddings()
16
+ elif hasattr(model, 'gpt_neox'): # GPTNeoX (Pythia) models
17
+ return model.gpt_neox.embed_in
18
+ elif hasattr(model, 'model') and hasattr(model.model, 'embed_tokens'): # LLaMA models
19
+ return model.model.embed_tokens
20
+ else:
21
+ raise ValueError(f"Unsupported model architecture: {type(model)}")
22
+
23
+ def customize_forward_pass(model, residual, presence, input_ids, grad_idx, attention_mask, ):
24
+ lm_head = get_lm_head(model)
25
+ embedding_layer = model.get_input_embeddings()
26
+ vocab_embed = embedding_layer.weight
27
+
28
+ with torch.no_grad():
29
+ input_ids_to_dev = input_ids.to(embedding_layer.weight.device)
30
+ base_embeds = embedding_layer(input_ids_to_dev)
31
+ # base_embeds = embedding_layer(input_ids.to(embedding_layer.weight.device))
32
+
33
+ def build_inputs():
34
+ embeds = base_embeds.clone()
35
+ # add residuals at masked positions
36
+ embeds[0, grad_idx, :] += residual
37
+ return embeds
38
+
39
+ def compute_logits(hidden, built_input_embeds):
40
+ """
41
+ Modify logit of target token to use updated embedding for prediction
42
+ """
43
+
44
+ L = built_input_embeds.size(1)
45
+ # lm_head = vocab_embed.clone()
46
+ # logits = hidden[0,].to(lm_head.device) @ lm_head.T
47
+ logits = hidden[0,].to(lm_head.device) @ vocab_embed.T
48
+
49
+ for t in range(0, L-1):
50
+ target_logit = torch.dot(hidden[0,t],built_input_embeds[0,t+1].to(hidden.device))
51
+ target_id = input_ids[0, t+1].item()
52
+ # print(f"logits[{t},{target_id}] before: {logits[t,target_id].item()}, after: {target_logit.item()}")
53
+ logits[t,target_id] = target_logit
54
+
55
+ return logits
56
+
57
+
58
+ def forward_pass(loss_position='all', hidden_norm_as_loss=False, unnormalized_logits=False, projection_probe=None,tie_input_output_embed = False, return_input_embeds = False, alpha=1, target_id=None):
59
+ embeds = build_inputs()
60
+ input_embeds = embeds
61
+ # input_embeds[0, grad_idx, :] *= presence
62
+ input_embeds[0, :, :] *= presence
63
+ input_embeds[0, :, :] *= alpha
64
+
65
+ # input_normalized = input_embeds[0, grad_idx, :] / input_embeds[0, grad_idx, :].norm(dim=-1, keepdim=True)
66
+ # print("norms: ", input_embeds.norm(dim=-1, keepdim=True))
67
+
68
+ # input_embeds[0, grad_idx, :] += presence * input_normalized
69
+
70
+ out = model.model(inputs_embeds=input_embeds,
71
+ attention_mask=attention_mask,
72
+ use_cache=False)
73
+
74
+ hidden = out.last_hidden_state # [1, L, d]
75
+ # print("hidden", hidden.shape)
76
+
77
+ if tie_input_output_embed:
78
+ readout_embeds = embeds
79
+ logits = compute_logits(hidden, readout_embeds)
80
+ else:
81
+ # lm_head.weight = lm_head.weight.to(hidden.device)
82
+ # lm_head = lm_head.to(hidden.device)
83
+ # logits = hidden[0,] @ lm_head.weight.T
84
+ lm_head_on_device = lm_head.to(hidden.device)
85
+ logits = hidden[0] @ lm_head_on_device.weight.T
86
+
87
+ targets = input_ids[0, 1:].to(logits.device)
88
+ # print("lm_head ", lm_head.weight.shape)
89
+ # print("logits ",logits.shape)
90
+ # print("targets ",targets.shape)
91
+
92
+
93
+ ### Total energy for anomaly detection
94
+ if loss_position == 'all':
95
+ if unnormalized_logits:
96
+ # Extract logits at target positions and sum
97
+ target_logits = logits[torch.arange(len(targets)), targets] # [L-1]
98
+ loss_full = -target_logits
99
+ loss = loss_full.mean() # or .sum()
100
+ else:
101
+ loss = nn.CrossEntropyLoss()(logits[:-1], targets)
102
+ loss_full = nn.CrossEntropyLoss(reduction='none')(logits[:-1], targets).detach() # shape: (seq_len,)
103
+ # loss = nn.CrossEntropyLoss()(logits[5:-1], targets[5:])
104
+
105
+ return loss, logits, loss_full
106
+
107
+
108
+ if not torch.is_tensor(loss_position):
109
+ loss_position = torch.tensor(loss_position)
110
+
111
+
112
+ ### random projection for Hutchinson
113
+ if projection_probe is not None:
114
+ projection_probe = projection_probe / projection_probe.norm(dim=-1, keepdim=True)
115
+ loss_position = loss_position.to(hidden.device)
116
+ # loss = (hidden[0, loss_position, :] * projection_probe.to(hidden.device)).sum()
117
+ loss = (hidden[0, loss_position, :] * projection_probe.to(hidden.device)).sum(dim=-1)
118
+ if return_input_embeds:
119
+ return loss, logits, input_embeds.detach()
120
+ else:
121
+ return loss, logits
122
+
123
+ ### Loss at chosen location
124
+ if hidden_norm_as_loss == True:
125
+ ### Temperature scope
126
+ hidden_act = hidden[:, loss_position, :].detach()
127
+ hidden_act = hidden_act / hidden_act.norm(dim=-1, keepdim=True)
128
+ # print("hidden_act", hidden_act.shape)
129
+ # print("hidden", hidden.shape)
130
+ loss_position = loss_position.to(hidden.device)
131
+ loss = (hidden[0, loss_position, :] * hidden_act).sum(dim=-1)
132
+ if return_input_embeds:
133
+ return loss, logits, input_embeds.detach()
134
+ else:
135
+ return loss, logits
136
+
137
+ else:
138
+ loss_position = loss_position.to(logits.device)
139
+ if target_id is not None:
140
+ target_chosen = torch.tensor([target_id], device=logits.device, dtype=torch.long)
141
+ else:
142
+ target_chosen = targets[loss_position].unsqueeze(0).to(logits.device)
143
+ if unnormalized_logits:
144
+
145
+ loss = -logits[loss_position,target_chosen]
146
+ else:
147
+ assert isinstance(loss_position, int) or (
148
+ torch.is_tensor(loss_position) and loss_position.dim() == 0
149
+ ), "loss_position must be either an integer, a 0D tensor, or str(all)"
150
+
151
+ logits_chosen = logits[loss_position, :].unsqueeze(0) # [1, V]
152
+ loss = nn.CrossEntropyLoss()(logits_chosen, target_chosen)
153
+ if return_input_embeds:
154
+ return loss, logits, input_embeds.detach()
155
+ else:
156
+ return loss, logits
157
+
158
+ return forward_pass
app.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Streamlit app for interactive Jacobian and Temperature Scope visualizations.
3
+ """
4
+
5
+ import gc
6
+ import os
7
+ import sys
8
+
9
+ import numpy as np
10
+ import matplotlib
11
+ matplotlib.use('Agg') # Non-interactive backend for Streamlit
12
+ import matplotlib as mpl
13
+ import matplotlib.pyplot as plt
14
+ import streamlit as st
15
+ import torch
16
+ from matplotlib.colors import LogNorm as Log_Norm
17
+ from matplotlib.colors import Normalize as Norm
18
+ from torch import nn
19
+ from transformers import AutoModelForCausalLM, AutoTokenizer
20
+
21
+ # Add current directory to path for JCBScope_utils
22
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
+ import JCBScope_utils
24
+
25
+ # Device configuration: use CPU to match notebook and avoid device_map complexity
26
+ device = torch.device("cpu")
27
+
28
+
29
+ @st.cache_resource
30
+ def load_model(model_name: str = "meta-llama/Llama-3.2-1B"):
31
+ """Load and cache the tokenizer and model."""
32
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
33
+ model = AutoModelForCausalLM.from_pretrained(model_name)
34
+ model = model.to(device)
35
+ return tokenizer, model
36
+
37
+
38
+ def check_target_single_token(tokenizer, target_str: str) -> tuple[bool, list[int] | None]:
39
+ """
40
+ Check that target is exactly one token. Returns (ok, ids) or (False, None).
41
+ Uses target_str as-is (no strip) so e.g. " truthful" stays one token.
42
+ """
43
+ ids = tokenizer(target_str, add_special_tokens=False)["input_ids"]
44
+ if len(ids) != 1:
45
+ return False, None
46
+ return True, ids
47
+
48
+
49
+ def _is_comma_delimited_numbers(s: str) -> bool:
50
+ """Check if string is comma-delimited integers."""
51
+ try:
52
+ parts = [x.strip() for x in s.split(",") if x.strip()]
53
+ return len(parts) > 0 and all(p.lstrip("-").isdigit() for p in parts)
54
+ except Exception:
55
+ return False
56
+
57
+
58
+ def compute_attribution(
59
+ string: str,
60
+ mode: str,
61
+ tokenizer,
62
+ model,
63
+ target_str: str | None = None,
64
+ front_pad: int = 2,
65
+ input_type: str = "text",
66
+ ):
67
+ """
68
+ Compute attribution using Temperature or Semantic Scope.
69
+
70
+ input_type: "text" or "comma_delimited". For comma_delimited, attribution skips delimiter tokens.
71
+ """
72
+ if mode not in ["Temperature", "Semantic"]:
73
+ raise ValueError(f"Invalid mode '{mode}'. Must be 'Temperature' or 'Semantic'.")
74
+
75
+ if mode == "Semantic" and (not target_str or not target_str.strip()):
76
+ raise ValueError("Semantic Scope requires a target token.")
77
+
78
+ if input_type == "comma_delimited" and not _is_comma_delimited_numbers(string.strip()):
79
+ raise ValueError("Input is not valid comma-delimited numbers.")
80
+
81
+ hidden_norm_as_loss = mode == "Temperature"
82
+ back_pad = 0
83
+
84
+ bos_token_id = tokenizer.bos_token_id if tokenizer.bos_token_id is not None else tokenizer.cls_token_id
85
+ eos_token_id = tokenizer.eos_token_id if tokenizer.eos_token_id is not None else tokenizer.sep_token_id
86
+
87
+ input_ids_list = []
88
+ if bos_token_id is not None:
89
+ input_ids_list += [bos_token_id] * front_pad
90
+ input_ids_list += tokenizer(string.strip(), add_special_tokens=False)["input_ids"]
91
+ if eos_token_id is not None:
92
+ input_ids_list += [eos_token_id] * back_pad
93
+
94
+ embedding_layer = model.get_input_embeddings()
95
+ target_device = embedding_layer.weight.device
96
+
97
+ input_ids = torch.tensor([input_ids_list], dtype=torch.long).to(target_device)
98
+ attention_mask = torch.ones_like(input_ids)
99
+ assert input_ids.max() < model.config.vocab_size, "Token IDs exceed vocab size"
100
+ assert input_ids.min() >= 0, "Token IDs must be non-negative"
101
+
102
+ decoded_tokens = [tokenizer.decode(tok.item(), skip_special_tokens=True) for tok in input_ids[0]]
103
+
104
+ if input_type == "comma_delimited":
105
+ grad_idx = list(range(front_pad, len(decoded_tokens), 2)) # Skip delimiter tokens
106
+ else:
107
+ grad_idx = list(range(front_pad, len(decoded_tokens)))
108
+
109
+ # loss_position = last position; logits[L-1] predicts the next token after input
110
+ loss_position = len(decoded_tokens) - 1
111
+
112
+ target_id = None
113
+ if mode == "Semantic":
114
+ ok, ids = check_target_single_token(tokenizer, target_str)
115
+ if not ok:
116
+ raise ValueError("Target not in token dictionary.")
117
+ target_id = ids[0]
118
+
119
+ d_model = embedding_layer.embedding_dim
120
+ residual = nn.Parameter(torch.zeros(len(grad_idx), d_model, device=target_device))
121
+ presence = torch.ones(len(decoded_tokens), 1, device=target_device)
122
+
123
+ forward_pass = JCBScope_utils.customize_forward_pass(
124
+ model, residual, presence, input_ids, grad_idx, attention_mask
125
+ )
126
+
127
+ unnormalized_logits = True
128
+
129
+ loss, logits = forward_pass(
130
+ loss_position=loss_position,
131
+ hidden_norm_as_loss=hidden_norm_as_loss,
132
+ unnormalized_logits=unnormalized_logits,
133
+ tie_input_output_embed=False,
134
+ target_id=target_id,
135
+ )
136
+
137
+ grads = torch.autograd.grad(loss, residual, retain_graph=True)[0]
138
+
139
+ out = {
140
+ "decoded_tokens": decoded_tokens,
141
+ "grad_idx": grad_idx,
142
+ "grads": grads,
143
+ "loss_position": loss_position,
144
+ "hidden_norm_as_loss": hidden_norm_as_loss,
145
+ "loss": loss.item(),
146
+ "logits": logits,
147
+ "input_type": input_type,
148
+ }
149
+ if mode == "Semantic" and target_str:
150
+ out["target_str"] = target_str # For visualization: append target in red
151
+ if input_type == "comma_delimited":
152
+ raw = [int(x.strip()) for x in string.strip().split(",") if x.strip()]
153
+ out["int_list"] = raw[: len(grad_idx)] # align with grad_idx length
154
+ return out
155
+
156
+
157
+ def rgba_to_css(rgba):
158
+ """Convert matplotlib RGBA to CSS rgba string."""
159
+ return f"rgba({int(rgba[0]*255)}, {int(rgba[1]*255)}, {int(rgba[2]*255)}, {rgba[3]:.2f})"
160
+
161
+
162
+ def get_text_color(bg_rgba):
163
+ """Return white or black text based on background luminance."""
164
+ luminance = 0.299 * bg_rgba[0] + 0.587 * bg_rgba[1] + 0.114 * bg_rgba[2]
165
+ return "white" if luminance < 0.5 else "black"
166
+
167
+
168
+ def render_attribution_html(result, log_color: bool = False, cmap_name: str = "Blues"):
169
+ """
170
+ Render attribution as HTML with colored token boxes (from notebook routine).
171
+ For Semantic Scope, appends the target token in red.
172
+ """
173
+ decoded_tokens = result["decoded_tokens"]
174
+ grad_idx = result["grad_idx"]
175
+ grads = result["grads"]
176
+ loss_position = result["loss_position"]
177
+ target_str = result.get("target_str") # Semantic Scope: append target in red
178
+ hardset_target_grad = True
179
+ exclude_target = False
180
+
181
+ cmap = plt.get_cmap(cmap_name)
182
+
183
+ if exclude_target:
184
+ optimized_tokens = [decoded_tokens[idx] for idx in grad_idx][:-1]
185
+ else:
186
+ optimized_tokens = [decoded_tokens[idx] for idx in grad_idx]
187
+
188
+ tick_label_text = optimized_tokens.copy()
189
+ append_target_in_red = target_str is not None
190
+
191
+ if len(grads.shape) == 2:
192
+ grad_magnitude = grads.norm(dim=-1).squeeze().detach().clone()
193
+ else:
194
+ grad_magnitude = grads.detach().clone()
195
+
196
+ bar_idx = None
197
+ if not exclude_target and hardset_target_grad and (loss_position + 1) in grad_idx:
198
+ target_idx_in_grad = grad_idx.index(loss_position + 1)
199
+ if target_idx_in_grad > 0:
200
+ prev_max = grad_magnitude[:target_idx_in_grad].max().item()
201
+ grad_magnitude[target_idx_in_grad] = max(prev_max, 1e-8)
202
+ else:
203
+ grad_magnitude[target_idx_in_grad] = 1e-8
204
+ bar_idx = target_idx_in_grad
205
+
206
+ grad_np = grad_magnitude.cpu().numpy()
207
+ log_norm = Log_Norm(vmin=grad_np.min(), vmax=grad_np.max())
208
+ norm = Norm(vmin=grad_np.min(), vmax=grad_np.max())
209
+
210
+ if log_color:
211
+ colors = cmap(log_norm(grad_np))
212
+ else:
213
+ colors = cmap(norm(grad_np))
214
+
215
+ html_parts = []
216
+ for i, (token, color) in enumerate(zip(tick_label_text, colors)):
217
+ bg_color = rgba_to_css(color)
218
+ text_color = get_text_color(color)
219
+
220
+ if bar_idx is not None and i == bar_idx and hardset_target_grad:
221
+ bg_color = "red"
222
+ text_color = "white"
223
+
224
+ display_token = token
225
+ html_parts.append(
226
+ f'<span style="'
227
+ f"background-color: {bg_color}; "
228
+ f"color: {text_color}; "
229
+ f"padding: 0px 0px; "
230
+ f"margin: 0px; "
231
+ f"border-radius: 0px; "
232
+ f"font-family: monospace; "
233
+ f"font-size: 16px; "
234
+ f"display: inline-block; "
235
+ f"font-weight: bold; "
236
+ f'white-space: pre;">{display_token}</span>'
237
+ )
238
+
239
+ if append_target_in_red:
240
+ html_parts.append(
241
+ f'<span style="'
242
+ f"background-color: red; "
243
+ f"color: white; "
244
+ f"padding: 0px 0px; "
245
+ f"margin: 0px; "
246
+ f"border-radius: 0px; "
247
+ f"font-family: monospace; "
248
+ f"font-size: 16px; "
249
+ f"display: inline-block; "
250
+ f"font-weight: bold; "
251
+ f'white-space: pre;">{target_str}</span>'
252
+ )
253
+
254
+ html_str = f'''
255
+ <div style="
256
+ background: white;
257
+ padding: 20px;
258
+ border-radius: 8px;
259
+ line-height: 2.2;
260
+ width: 100%;
261
+ max-width: 700px;
262
+ ">
263
+ {"".join(html_parts)}
264
+ </div>
265
+ '''
266
+ # Color bar (from notebook): horizontal, matching the color mapping
267
+ fig_bar, ax_bar = plt.subplots(figsize=(10, 0.3), dpi=100)
268
+ fig_bar.subplots_adjust(left=0.3, right=0.7, bottom=0.1, top=0.9)
269
+ cbar = mpl.colorbar.ColorbarBase(
270
+ ax_bar,
271
+ cmap=cmap,
272
+ norm=log_norm if log_color else norm,
273
+ orientation="horizontal",
274
+ )
275
+ cbar.set_label("Influence")
276
+
277
+ return html_str, fig_bar
278
+
279
+
280
+ def render_attribution_barplot(result, log_color: bool = False, cmap_name: str = "Blues"):
281
+ """
282
+ Bar plot with double axes for comma-delimited input: Influence (left) and Token value (right).
283
+ """
284
+ grad_idx = result["grad_idx"]
285
+ grads = result["grads"]
286
+ loss_position = result["loss_position"]
287
+ int_list = result["int_list"]
288
+ front_pad = 2 # assumed
289
+
290
+ if len(grads.shape) == 2:
291
+ grad_magnitude = grads.norm(dim=-1).squeeze().detach().clone().cpu().numpy()
292
+ else:
293
+ grad_magnitude = grads.detach().clone().cpu().numpy()
294
+
295
+ hardset_target_grad = True
296
+ target_bar_index = None
297
+ if hardset_target_grad and (loss_position + 1) in grad_idx:
298
+ target_bar_index = grad_idx.index(loss_position + 1)
299
+ grad_magnitude[target_bar_index] = max(grad_magnitude)
300
+
301
+ ax1_color = np.array([10, 110, 230]) / 256
302
+ ax2_color = np.array([230, 20, 20]) / 256
303
+
304
+ x_labels = [x - front_pad for x in grad_idx]
305
+
306
+ fig, ax = plt.subplots(figsize=(10, 2.5), dpi=120)
307
+ bars = ax.bar(
308
+ range(grad_magnitude.shape[0]),
309
+ grad_magnitude,
310
+ tick_label=x_labels,
311
+ color=ax1_color,
312
+ linewidth=0.5,
313
+ edgecolor="black",
314
+ width=1.0,
315
+ alpha=0.9,
316
+ )
317
+ if target_bar_index is not None:
318
+ bars[target_bar_index].set_color("red")
319
+ bars[target_bar_index].set_width(1.1)
320
+
321
+ ax2 = ax.twinx()
322
+ ax2.scatter(range(len(int_list)), int_list, color=ax2_color, marker="o", s=13, alpha=0.9)
323
+ ax2.plot(range(len(int_list)), int_list, color=ax2_color, linewidth=1.5, alpha=0.5)
324
+
325
+ ax2.tick_params(axis="y", colors=ax2_color, labelsize=10)
326
+ ax.tick_params(axis="y", colors=ax1_color, labelsize=10)
327
+
328
+ # At most 5 x-axis labels
329
+ n_bars = grad_magnitude.shape[0]
330
+ n_labels = min(5, n_bars)
331
+ if n_labels > 0:
332
+ tick_indices = np.linspace(0, n_bars - 1, n_labels, dtype=int)
333
+ ax.set_xticks(tick_indices)
334
+ ax.set_xticklabels([x_labels[i] for i in tick_indices], fontsize=10)
335
+
336
+ ax.set_xlabel("Token position index", fontsize=10, fontweight="bold")
337
+ ax.set_ylabel("Influence", labelpad=2, color=ax1_color, fontsize=10, fontweight="bold")
338
+ ax2.set_ylabel("Token value", labelpad=2, color=ax2_color, fontsize=10, fontweight="bold")
339
+
340
+ ax.set_axisbelow(True)
341
+ ax.xaxis.grid(True, which="both", linestyle="--", linewidth=0.3, alpha=0.7)
342
+ ax.yaxis.grid(True, which="both", linestyle="--", linewidth=0.3, alpha=0.7)
343
+
344
+ plt.tight_layout()
345
+ return fig
346
+
347
+
348
+ def main():
349
+ st.set_page_config(page_title="Jacobian Scope Demo", page_icon="🔬", layout="centered")
350
+ st.title("🔍 Jacobian & Temperature Scopes Demo")
351
+ st.markdown(
352
+ "**Semantic Scope** explains the predicted logit for a specific target token: enter your input "
353
+ "passage along with a target token.\n\n"
354
+ "**Temperature Scope** explains the overall predictive distribution and does not require a target."
355
+ )
356
+
357
+ model_choice = st.selectbox(
358
+ "Model",
359
+ options=["SmolLM3-3B-Base", "LLaMA 3.2 1B", "LLaMA 3.2 3B"],
360
+ index=0,
361
+ key="model_choice",
362
+ help="Choose model.",
363
+ )
364
+ MODEL_MAP = {
365
+ "LLaMA 3.2 1B": "meta-llama/Llama-3.2-1B",
366
+ "LLaMA 3.2 3B": "meta-llama/Llama-3.2-3B",
367
+ "SmolLM3-3B-Base": "HuggingFaceTB/SmolLM3-3B-Base",
368
+ }
369
+ model_name = MODEL_MAP[model_choice]
370
+
371
+ attribution_type = st.radio(
372
+ "Attribution type",
373
+ options=["Semantic Scope", "Temperature Scope"],
374
+ index=0,
375
+ horizontal=True,
376
+ help="Semantic Scope: attribute toward a target token. Temperature Scope: use hidden-state norm.",
377
+ )
378
+ mode = "Semantic" if attribution_type == "Semantic Scope" else "Temperature"
379
+
380
+ input_type_default = "text" if mode == "Semantic" else "comma_delimited"
381
+ input_type = st.radio(
382
+ "Input type",
383
+ options=["text", "comma-delimited numbers"],
384
+ index=0 if input_type_default == "text" else 1,
385
+ horizontal=True,
386
+ key=f"input_type_{mode}",
387
+ help="Text: natural language. Comma-delimited numbers: time-series style (delimiters skipped when calculating influence scores).",
388
+ )
389
+ is_comma_delimited = input_type == "comma-delimited numbers"
390
+
391
+ if is_comma_delimited:
392
+ default_text = (
393
+ "80,68,57,52,50,49,48,46,42,35,23,14,24,40,49,54,57,60,66,74,79,74,64,58,55,55,57,61,68,77,80,71,60,54,52,51,52,53,55,61,70,83,83,66,53,47,44,41,36,28,22,23,32,40,44,44,43,40,33,24,19,26,37,44,47,47,47,45,40,32,21,16,28,42,49,52,55,58,63,71,80,79,67,58,53,51,51,51,52,55,59,69,82,84,69,54,47,43,40,35,28,22,24,32,39,43,43,41,37,30,22,22,31,39,44,45,44,41,36,27,19,22,34,43,47,49,49,48,47,45,40,31,18,15,31,46,53,57,60,65,72,77,75,67,60,57,57,59,64,71,78,77,68,60,56,55,56,60,66,75,81,75,63,56,53,52,52,54,57,62,73,"
394
+ )
395
+ elif mode == "Semantic":
396
+ default_text = (
397
+ "As a state-of-the-art AI assistant, you never argue or deceive, because you are"
398
+ )
399
+ else:
400
+ default_text = (
401
+ # "Italiano: Ma quando tu sarai nel dolce mondo, priegoti ch'a la mente altrui mi rechi: English: But when you have returned to the sweet world, I pray you"
402
+ "French: Cet article porte sur l'attribution causale, que nous appelons lentille jacobienne. English: This is a paper on causal attribution, and we call it Jacobian"
403
+ )
404
+
405
+ text_input = st.text_area(
406
+ "Input text",
407
+ value=default_text,
408
+ height=120,
409
+ key=f"text_input_{mode}_{input_type}",
410
+ placeholder="Input text or comma-delimited numbers",
411
+ help="Text or comma-separated numbers. Delimiters are skipped for comma-delimited.",
412
+ )
413
+
414
+ target_str = None
415
+ if mode == "Semantic":
416
+ target_str = st.text_input(
417
+ "Target token",
418
+ value=" truthful",
419
+ placeholder='e.g., " truthful" or " nice"',
420
+ help="Must be representable as a single token (e.g. ' truthful' with leading space for Llama).",
421
+ )
422
+
423
+ compute_clicked = st.button("Compute Attribution!", type="primary", use_container_width=True)
424
+
425
+ input_type_param = "comma_delimited" if is_comma_delimited else "text"
426
+
427
+ if compute_clicked:
428
+ if not text_input.strip():
429
+ st.error("Please enter some text.")
430
+ elif mode == "Semantic" and (not target_str or not target_str.strip()):
431
+ st.error("Please enter a target token for Semantic Scope.")
432
+ elif is_comma_delimited and not _is_comma_delimited_numbers(text_input.strip()):
433
+ st.error("Input is not valid comma-delimited numbers.")
434
+ else:
435
+ with st.spinner(f"Loading model and computing {mode} Scope..."):
436
+ try:
437
+ torch.cuda.empty_cache()
438
+ torch.cuda.ipc_collect() if torch.cuda.is_available() else None
439
+ gc.collect()
440
+
441
+ tokenizer, model = load_model(model_name=model_name)
442
+ result = compute_attribution(
443
+ text_input.strip(),
444
+ mode,
445
+ tokenizer,
446
+ model,
447
+ target_str=target_str,
448
+ input_type=input_type_param,
449
+ )
450
+ st.session_state["attribution_result"] = result
451
+ st.session_state["tokenizer"] = tokenizer
452
+
453
+ st.success("Attribution successful!")
454
+ except ValueError as e:
455
+ if "Target not in token dictionary" in str(e):
456
+ st.error("Target not in token dictionary.")
457
+ else:
458
+ st.error(str(e))
459
+ except Exception as e:
460
+ st.error(f"Error: {e}")
461
+ raise
462
+
463
+ # Visualization (uses cached result; log_color and cmap are post-compute only)
464
+ if "attribution_result" in st.session_state:
465
+ result = st.session_state["attribution_result"]
466
+ tokenizer = st.session_state["tokenizer"]
467
+
468
+ st.subheader("Attribution Visualization")
469
+
470
+ # Adjustable after compute — does not trigger recompute
471
+ viz_col1, viz_col2 = st.columns([1, 1])
472
+ with viz_col1:
473
+ log_color = st.checkbox(
474
+ "Log-scale colormap",
475
+ value=False,
476
+ key="log_color",
477
+ help="Use log scale for influence values.",
478
+ )
479
+ with viz_col2:
480
+ cmap_choice = st.selectbox(
481
+ "Color map",
482
+ options=["Blues", "Greens", "viridis"],
483
+ index=0,
484
+ key="cmap_choice",
485
+ help="Colormap for attribution visualization.",
486
+ )
487
+
488
+ if result.get("input_type") == "comma_delimited":
489
+ fig_barplot = render_attribution_barplot(
490
+ result, log_color=log_color, cmap_name=cmap_choice
491
+ )
492
+ st.pyplot(fig_barplot)
493
+ plt.close(fig_barplot)
494
+ else:
495
+ html_output, fig_colorbar = render_attribution_html(
496
+ result, log_color=log_color, cmap_name=cmap_choice
497
+ )
498
+ st.markdown(html_output, unsafe_allow_html=True)
499
+ st.pyplot(fig_colorbar)
500
+ plt.close(fig_colorbar)
501
+
502
+ with st.expander("Top predicted next tokens"):
503
+ k = 7
504
+ logit_vector = result["logits"][result["loss_position"]].detach()
505
+ probs = torch.softmax(logit_vector, dim=-1)
506
+ top_probs, top_indices = torch.topk(probs, k)
507
+ top_tokens = [tokenizer.decode([idx]) for idx in top_indices]
508
+ for i, (tok, prob) in enumerate(zip(top_tokens, top_probs.cpu().numpy()), 1):
509
+ st.write(f"{i}. P(**{repr(tok)}**)={prob:.3f}")
510
+
511
+
512
+ if __name__ == "__main__":
513
+ main()
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
- altair
2
- pandas
3
- streamlit
 
 
1
+ torch>=2.0.0
2
+ transformers>=4.30.0
3
+ matplotlib>=3.5.0
4
+ streamlit>=1.28.0