AryaWu commited on
Commit
2481f0d
·
verified ·
1 Parent(s): 09daab8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +331 -0
app.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ import io
5
+ from PIL import Image
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from nnsight import LanguageModel
9
+ from typing import List
10
+ import pandas as pd
11
+
12
+ # Set up the API key for nnsight
13
+ from nnsight import CONFIG
14
+ import os
15
+ api_key = os.getenv('NNSIGHT_API_KEY')
16
+ CONFIG.set_default_api_key(api_key)
17
+
18
+ # Load the Language Model
19
+ llama = LanguageModel("meta-llama/Meta-Llama-3.1-8B", device="cuda")
20
+
21
+ #placeholder for reset
22
+ prompts_with_probs = pd.DataFrame(
23
+ {
24
+ "prompt": ['waiting for data'],
25
+ "layer": [0],
26
+ "results": ['hi'],
27
+ "probs": [0],
28
+ "expected": ['hi'],
29
+ })
30
+ prompts_with_ranks = pd.DataFrame(
31
+ {
32
+ "prompt": ['waiting for data'],
33
+ "layer": [0],
34
+ "results": ['hi'],
35
+ "ranks": [0],
36
+ "expected": ['hi'],
37
+ })
38
+
39
+ def run_lens(model,PROMPT):
40
+ logits_lens_token_result_by_layer = []
41
+ logits_lens_probs_by_layer = []
42
+ logits_lens_ranks_by_layer = []
43
+ input_ids = model.tokenizer.encode(PROMPT)
44
+ with model.trace(input_ids, remote=True) as runner:
45
+ for layer_ix,layer in enumerate(model.model.layers):
46
+ hidden_state = layer.output[0][0]
47
+ logits_lens_normed_last_token = model.model.norm(hidden_state)
48
+ logits_lens_token_distribution = model.lm_head(logits_lens_normed_last_token)
49
+ logits_lens_last_token_logits = logits_lens_token_distribution[-1:]
50
+ logits_lens_probs = F.softmax(logits_lens_last_token_logits, dim=1).save()
51
+ logits_lens_probs_by_layer.append(logits_lens_probs)
52
+ logits_lens_next_token = torch.argmax(logits_lens_probs, dim=1).save()
53
+ logits_lens_token_result_by_layer.append(logits_lens_next_token)
54
+ tokens_out = llama.lm_head.output.argmax(dim=-1).save()
55
+ expected_token = tokens_out[0][-1].save()
56
+ logits_lens_all_probs = np.concatenate([probs[:, expected_token].cpu().detach().numpy() for probs in logits_lens_probs_by_layer])
57
+ #get the rank of the expected token from each layer's distribution
58
+ for layer_probs in logits_lens_probs_by_layer:
59
+ # Sort the probabilities in descending order and find the rank of the expected token
60
+ sorted_probs, sorted_indices = torch.sort(layer_probs, descending=True)
61
+ # Find the rank of the expected token (1-based rank)
62
+ expected_token_rank = (sorted_indices == expected_token).nonzero(as_tuple=True)[1].item() + 1
63
+ logits_lens_ranks_by_layer.append(expected_token_rank)
64
+ actual_output = llama.tokenizer.decode(expected_token.item())
65
+ logits_lens_results = [model.tokenizer.decode(next_token.item()) for next_token in logits_lens_token_result_by_layer]
66
+ return logits_lens_results, logits_lens_all_probs, actual_output,logits_lens_ranks_by_layer
67
+
68
+
69
+ def process_file(prompts_data,file_path):
70
+ """Read uploaded file and return list of prompts."""
71
+ prompts = []
72
+
73
+ if file_path is None:
74
+ return prompts
75
+
76
+ if file_path.endswith('.csv'):
77
+ # Process CSV file
78
+ df = pd.read_csv(file_path)
79
+ if 'Prompt' in df.columns:
80
+ prompts = df[['Prompt']].dropna().values.tolist()
81
+
82
+ # Read the file as text and split into lines (one prompt per line)
83
+ else:
84
+ with open(file_path, 'r') as file:
85
+ prompts = [[line] for line in file.read().splitlines()]
86
+
87
+ for prompt in prompts_data:
88
+ if prompt==['']:
89
+ continue
90
+ else:
91
+ prompts.append(prompt)
92
+
93
+ return prompts
94
+
95
+
96
+
97
+ #problem with using gr.LinePlot instead of a plt.figure is that text labels cannot be added for each individual point
98
+ # def plot_prob(prompts_with_probs):
99
+ # return gr.LinePlot(prompts_with_probs, x="layer", y="probs",color="prompt", title="Probability of Expected Token",label="results",show_label=True,key="results")
100
+ import matplotlib.pyplot as plt
101
+ import pandas as pd
102
+ import io
103
+ from PIL import Image
104
+ def plot_prob(prompts_with_probs):
105
+ plt.figure(figsize=(10, 6))
106
+
107
+ # Iterate over each prompt and plot its probabilities
108
+ for prompt in prompts_with_probs['prompt'].unique():
109
+ # Filter the DataFrame for the current prompt
110
+ prompt_data = prompts_with_probs[prompts_with_probs['prompt'] == prompt]
111
+
112
+ # Plot probabilities for this prompt
113
+ plt.plot(prompt_data['layer'], prompt_data['probs'], marker='x', label=prompt)
114
+
115
+ # Annotate each point with the corresponding result
116
+ for layer, prob, result in zip(prompt_data['layer'], prompt_data['probs'], prompt_data['results']):
117
+ plt.text(layer, prob, result, ha='right', va='bottom', fontsize=8)
118
+
119
+
120
+ # Add labels and title
121
+ plt.xlabel('Layer Number')
122
+ plt.ylabel('Probability of Expected Token')
123
+ plt.title('Logits Lens for All Prompts')
124
+ plt.grid(True)
125
+ plt.ylim(0.0, 1.0)
126
+ plt.legend(title='Prompts', bbox_to_anchor=(0.5, -0.15), loc='upper center', ncol=1)
127
+
128
+ # Save the plot to a buffer
129
+ buf = io.BytesIO()
130
+ plt.savefig(buf, format='png', bbox_inches='tight') # Use bbox_inches to avoid cutting off labels
131
+ buf.seek(0)
132
+ img = Image.open(buf)
133
+ plt.close() # Close the figure to free memory
134
+ return img
135
+ # Example usage
136
+ # prompts_with_probs should be a DataFrame with 'prompt', 'layer', and 'probs' columns
137
+
138
+ import matplotlib.pyplot as plt
139
+ import pandas as pd
140
+ import io
141
+ from PIL import Image
142
+
143
+ def plot_rank(prompts_with_ranks):
144
+ plt.figure(figsize=(10, 6))
145
+
146
+ # Iterate over each prompt and plot its ranks
147
+ for prompt in prompts_with_ranks['prompt'].unique():
148
+ # Filter the DataFrame for the current prompt
149
+ prompt_data = prompts_with_ranks[prompts_with_ranks['prompt'] == prompt]
150
+
151
+ # Plot ranks for this prompt
152
+ plt.plot(prompt_data['layer'], prompt_data['ranks'], marker='x', label=prompt)
153
+
154
+ # Annotate each point with the corresponding result
155
+ for layer, rank, result in zip(prompt_data['layer'], prompt_data['ranks'], prompt_data['results']):
156
+ plt.text(layer, rank,result, ha='right', va='bottom', fontsize=8)
157
+
158
+ # Add labels and title
159
+ plt.xlabel('Layer Number')
160
+ plt.ylabel('Rank of Expected Token')
161
+ plt.title('Logits Lens Rank for All Prompts')
162
+ plt.grid(True)
163
+ plt.ylim(bottom=0) # Adjust if needed, depending on your rank values
164
+ plt.legend(title='Prompts', bbox_to_anchor=(0.5, -0.15), loc='upper center', ncol=1)
165
+
166
+
167
+ # Save the plot to a buffer
168
+ buf = io.BytesIO()
169
+ plt.savefig(buf, format='png', bbox_inches='tight') # Use bbox_inches to avoid cutting off labels
170
+ buf.seek(0)
171
+ img = Image.open(buf)
172
+ plt.close() # Close the figure to free memory
173
+ return img
174
+
175
+ import matplotlib.pyplot as plt
176
+ import pandas as pd
177
+ import io
178
+ from PIL import Image
179
+
180
+ def plot_prob_mean(prompts_with_probs):
181
+ # Calculate mean probabilities and variance
182
+ summary_stats = prompts_with_probs.groupby("prompt")["probs"].agg(
183
+ mean_prob="mean",
184
+ variance="var"
185
+ ).reset_index()
186
+
187
+ # Set up the bar plot
188
+ plt.figure(figsize=(10, 6))
189
+ bars = plt.bar(summary_stats['prompt'], summary_stats['mean_prob'],
190
+ yerr=summary_stats['variance']**0.5, # Error bars are the standard deviation
191
+ capsize=5, color='skyblue')
192
+
193
+ # Add labels and title
194
+ plt.xlabel('Prompt')
195
+ plt.ylabel('Mean Probability')
196
+ plt.title('Mean Probability of Expected Token with Error Bars')
197
+ plt.xticks(rotation=45, ha='right')
198
+ plt.grid(axis='y')
199
+
200
+ # Annotate the mean and variance on the bars
201
+ for bar, mean, var in zip(bars, summary_stats['mean_prob'], summary_stats['variance']):
202
+ yval = bar.get_height()
203
+ plt.text(bar.get_x() + bar.get_width() / 2, yval, f'Mean: {mean:.2f}\nVar: {var:.2f}',
204
+ ha='center', va='bottom', fontsize=8, color='black')
205
+
206
+ # Save the plot to a buffer
207
+ buf = io.BytesIO()
208
+ plt.savefig(buf, format='png', bbox_inches='tight') # Use bbox_inches to avoid cutting off labels
209
+ buf.seek(0)
210
+ img = Image.open(buf)
211
+ plt.close() # Close the figure to free memory
212
+ return img
213
+
214
+ # Example usage
215
+ # prompts_with_probs should be a DataFrame with 'prompt' and 'probs' columns
216
+
217
+ def plot_rank_mean(prompts_with_ranks):
218
+ # Calculate mean ranks and variance
219
+ summary_stats = prompts_with_ranks.groupby("prompt")["ranks"].agg(
220
+ mean_rank="mean",
221
+ variance="var"
222
+ ).reset_index()
223
+
224
+ # Set up the bar plot
225
+ plt.figure(figsize=(10, 6))
226
+ bars = plt.bar(summary_stats['prompt'], summary_stats['mean_rank'],
227
+ yerr=summary_stats['variance']**0.5, # Error bars are the standard deviation
228
+ capsize=5, color='salmon')
229
+
230
+ # Add labels and title
231
+ plt.xlabel('Prompt')
232
+ plt.ylabel('Mean Rank')
233
+ plt.title('Mean Rank of Expected Token with Error Bars')
234
+ plt.xticks(rotation=45, ha='right')
235
+ plt.grid(axis='y')
236
+
237
+ # Annotate the mean and variance on the bars
238
+ for bar, mean, var in zip(bars, summary_stats['mean_rank'], summary_stats['variance']):
239
+ yval = bar.get_height()
240
+ plt.text(bar.get_x() + bar.get_width() / 2, yval, f'Mean: {mean:.2f}\nVar: {var:.2f}',
241
+ ha='center', va='bottom', fontsize=8, color='black')
242
+
243
+ # Save the plot to a buffer
244
+ buf = io.BytesIO()
245
+ plt.savefig(buf, format='png', bbox_inches='tight') # Use bbox_inches to avoid cutting off labels
246
+ buf.seek(0)
247
+ img = Image.open(buf)
248
+ plt.close() # Close the figure to free memory
249
+ return img
250
+
251
+ def submit_prompts(prompts_data):
252
+ # Initialize lists to accumulate results
253
+ all_prompts = []
254
+ all_results = []
255
+ all_probs = []
256
+ all_expected = []
257
+ all_layers = []
258
+ all_ranks = []
259
+
260
+ # Iterate over each prompt
261
+ for prompt in prompts_data:
262
+ # If a prompt is an empty string, skip it
263
+ prompt = prompt[0]
264
+ if not prompt:
265
+ continue
266
+
267
+ # Run the lens model on the prompt
268
+ lens_output = run_lens(llama, prompt)
269
+
270
+ # Accumulate results for each layer
271
+ for layer_idx in range(len(lens_output[1])):
272
+ all_prompts.append(prompt)
273
+ all_results.append(lens_output[0][layer_idx])
274
+ all_probs.append(float(lens_output[1][layer_idx]))
275
+ all_expected.append(lens_output[2])
276
+ all_layers.append(int(layer_idx))
277
+ all_ranks.append(int(lens_output[3][layer_idx]))
278
+
279
+ # Create DataFrame from accumulated results
280
+ prompts_with_probs = pd.DataFrame(
281
+ {
282
+ "prompt": all_prompts,
283
+ "layer": all_layers,
284
+ "results": all_results,
285
+ "probs": all_probs,
286
+ "expected": all_expected,
287
+ })
288
+
289
+ prompts_with_ranks = pd.DataFrame(
290
+ {
291
+ "prompt": all_prompts,
292
+ "layer": all_layers,
293
+ "results": all_results,
294
+ "ranks": all_ranks,
295
+ "expected": all_expected,
296
+ })
297
+ return plot_prob(prompts_with_probs), plot_rank(prompts_with_ranks),plot_prob_mean(prompts_with_probs),plot_rank_mean(prompts_with_ranks)
298
+
299
+
300
+ def clear_all(prompts):
301
+ prompts=[['']]
302
+ prompts_data = gr.Dataframe(headers=["Prompt"], row_count=5, col_count=1, value= prompts, type="array", interactive=True)
303
+ return prompts_data,plot_prob(prompts_with_probs),plot_rank(prompts_with_ranks),plot_prob_mean(prompts_with_probs),plot_rank_mean(prompts_with_ranks)
304
+
305
+
306
+ def gradio_interface():
307
+ with gr.Blocks(theme="gradio/monochrome") as demo:
308
+ prompts=[['']]
309
+ prompts_data = gr.Dataframe(headers=["Prompt"], row_count=5, col_count=1, value= prompts, type="array", interactive=True)
310
+ prompt_file=gr.File(type="filepath", label="Upload a File with Prompts")
311
+ prompt_file.upload(process_file, inputs=[prompts_data,prompt_file], outputs=[prompts_data])
312
+
313
+ # Define the outputs
314
+ with gr.Row():
315
+ prob_visualization = gr.Image(value=plot_prob(prompts_with_probs), type="pil", label="Probability of Expected Token")
316
+ rank_visualization = gr.Image(value=plot_rank(prompts_with_ranks), type="pil", label="Rank of Expected Token")
317
+ with gr.Row():
318
+ prob_mean_visualization = gr.Image(value=plot_prob_mean(prompts_with_probs), type="pil", label="Mean Probability of Expected Token")
319
+ rank_mean_visualization = gr.Image(value=plot_rank_mean(prompts_with_ranks), type="pil", label="Mean Rank of Expected Token")
320
+
321
+ with gr.Row():
322
+ clear_btn = gr.Button("Clear")
323
+ clear_btn.click(clear_all, inputs=[prompts_data], outputs=[prompts_data,prob_visualization,rank_visualization,prob_mean_visualization,rank_mean_visualization])
324
+ submit_btn = gr.Button("Submit")
325
+ submit_btn.click(submit_prompts, inputs=[prompts_data], outputs=[prob_visualization,rank_visualization,prob_mean_visualization,rank_mean_visualization])#
326
+
327
+
328
+ demo.launch()
329
+
330
+
331
+ gradio_interface()