File size: 11,245 Bytes
d77f6b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import numpy as np
import plotly.graph_objects as go
import json
import gradio as gr
from nltk.corpus import words
import nltk


# load files w embeddings, attention scores, and tokens
vocab_embeddings = np.load('vocab_embeddings.npy')
with open('vocab_attention_scores.json', 'r') as f:
    vocab_attention_scores = json.load(f)
with open('vocab_tokens.json', 'r') as f:
    vocab_tokens = json.load(f)

# attention scores to numpy arrs
b_gen_attention = np.array([score['B-GEN'] for score in vocab_attention_scores])
i_gen_attention = np.array([score['I-GEN'] for score in vocab_attention_scores])
b_unfair_attention = np.array([score['B-UNFAIR'] for score in vocab_attention_scores])
i_unfair_attention = np.array([score['I-UNFAIR'] for score in vocab_attention_scores])
b_stereo_attention = np.array([score['B-STEREO'] for score in vocab_attention_scores])
i_stereo_attention = np.array([score['I-STEREO'] for score in vocab_attention_scores])
o_attention = np.array([score['O'] for score in vocab_attention_scores])  # Use actual O scores

# remove non-dict english words, but keep subwords ##
nltk.download('words')
english_words = set(words.words())

filtered_indices = [i for i, token in enumerate(vocab_tokens) if token in english_words or token.startswith("##")]
filtered_tokens = [vocab_tokens[i] for i in filtered_indices]

b_gen_attention_filtered = b_gen_attention[filtered_indices]
i_gen_attention_filtered = i_gen_attention[filtered_indices]
b_unfair_attention_filtered = b_unfair_attention[filtered_indices]
i_unfair_attention_filtered = i_unfair_attention[filtered_indices]
b_stereo_attention_filtered = b_stereo_attention[filtered_indices]
i_stereo_attention_filtered = i_stereo_attention[filtered_indices]
o_attention_filtered = o_attention[filtered_indices]

# plot top 500 O tokens for comparison
top_500_o_indices = np.argsort(o_attention_filtered)[-500:]
top_500_o_tokens = [filtered_tokens[i] for i in top_500_o_indices]
o_attention_filtered_top_500 = o_attention_filtered[top_500_o_indices]

# tool tip for tokens
def create_hover_text(tokens, b_gen, i_gen, b_unfair, i_unfair, b_stereo, i_stereo, o_val):
    hover_text = []
    for i in range(len(tokens)):
        hover_text.append(
            f"Token: {tokens[i]}<br>"
            f"B-GEN: {b_gen[i]:.3f}, I-GEN: {i_gen[i]:.3f}<br>"
            f"B-UNFAIR: {b_unfair[i]:.3f}, I-UNFAIR: {i_unfair[i]:.3f}<br>"
            f"B-STEREO: {b_stereo[i]:.3f}, I-STEREO: {i_stereo[i]:.3f}<br>"
            f"O: {o_val[i]:.3f}"
        )
    return hover_text

# ploting top 100 tokens for each entity
def select_top_100(*data_arrays):
    indices_list = []
    for data in data_arrays:
        if data is not None:
            top_indices = np.argsort(data)[-100:] 
            indices_list.append(top_indices)
    
    combined_indices = np.unique(np.concatenate(indices_list))

    # filter based on combined indices
    filtered_data = [data[combined_indices] if data is not None else None for data in data_arrays]
    tokens_filtered = [filtered_tokens[i] for i in combined_indices]

    return (*filtered_data, tokens_filtered)

# plots for 1 2 and 3 D
def create_plot(selected_dimensions):
    # plot data
    attention_map = {
        'Generalization': b_gen_attention_filtered + i_gen_attention_filtered,
        'Unfairness': b_unfair_attention_filtered + i_unfair_attention_filtered,
        'Stereotype': b_stereo_attention_filtered + i_stereo_attention_filtered,
    }

    # init x, y, z so they can be moved around
    x_data, y_data, z_data = None, None, None

    # use selected dimentsions to order dimensions
    if len(selected_dimensions) > 0:
        x_data = attention_map[selected_dimensions[0]]
    if len(selected_dimensions) > 1:
        y_data = attention_map[selected_dimensions[1]] 
    if len(selected_dimensions) > 2:
        z_data = attention_map[selected_dimensions[2]]

    # select top 100 dps for each selected dimension
    x_data, y_data, z_data, tokens_filtered = select_top_100(x_data, y_data, z_data)

    # filter the O tokens using the same dimensions
    o_x = attention_map[selected_dimensions[0]][top_500_o_indices]
    if len(selected_dimensions) > 1:
        o_y = attention_map[selected_dimensions[1]][top_500_o_indices]
    else:
        o_y = np.zeros_like(o_x) 
    if len(selected_dimensions) > 2:
        o_z = attention_map[selected_dimensions[2]][top_500_o_indices]
    else:
        o_z = np.zeros_like(o_x)

    # hover text for GUS tokens
    classified_hover_text = create_hover_text(
        tokens_filtered, 
        b_gen_attention_filtered, i_gen_attention_filtered, 
        b_unfair_attention_filtered, i_unfair_attention_filtered, 
        b_stereo_attention_filtered, i_stereo_attention_filtered, 
        o_attention_filtered
    )

    # hover text for O tokens
    o_hover_text = create_hover_text(
        top_500_o_tokens, 
        b_gen_attention_filtered[top_500_o_indices], i_gen_attention_filtered[top_500_o_indices], 
        b_unfair_attention_filtered[top_500_o_indices], i_unfair_attention_filtered[top_500_o_indices], 
        b_stereo_attention_filtered[top_500_o_indices], i_stereo_attention_filtered[top_500_o_indices], 
        o_attention_filtered_top_500
    )


    # plot
    fig = go.Figure()

    if x_data is not None and y_data is not None and z_data is not None:
        # 3d scatter plot
        fig.add_trace(go.Scatter3d(
            x=x_data,
            y=y_data,
            z=z_data,
            mode='markers',
            marker=dict(
                size=6,
                color=x_data,  # color based on the x-axis data
                colorscale='Viridis',
                opacity=0.85,
            ),
            text=classified_hover_text, 
            hoverinfo='text',
            name='Classified Tokens'
        ))
        # add top 500 O tags to the plot too
        fig.add_trace(go.Scatter3d(
            x=o_x,
            y=o_y,
            z=o_z,
            mode='markers',
            marker=dict(
                size=6,
                color='grey',
                opacity=0.5,
            ),
            text=o_hover_text,
            hoverinfo='text',
            name='O Tokens'
        ))
    elif x_data is not None and y_data is not None:
        # 2d scatter plot
        fig.add_trace(go.Scatter(
            x=x_data,
            y=y_data,
            mode='markers',
            marker=dict(
                size=6,
                color=x_data, # color based on the x-axis data
                colorscale='Viridis',
                opacity=0.85,
            ),
            text=classified_hover_text,
            hoverinfo='text',
            name='Classified Tokens'
        ))
        # add top 500 O tags to the plot too
        fig.add_trace(go.Scatter(
            x=o_x,
            y=o_y,
            mode='markers',
            marker=dict(
                size=6,
                color='grey',
                opacity=0.5,
            ),
            text=o_hover_text, 
            hoverinfo='text',
            name='O Tokens'
        ))
    elif x_data is not None:
        # 1D scatter plot
        fig.add_trace(go.Scatter(
            x=x_data,
            y=np.zeros_like(x_data),
            mode='markers',
            marker=dict(
                size=6,
                color=x_data, 
                colorscale='Viridis',
                opacity=0.85,
            ),
            text=classified_hover_text,
            hoverinfo='text',
            name='GUS Tokens'
        ))
        fig.add_trace(go.Scatter(
            x=o_x,
            y=np.zeros_like(o_x), 
            mode='markers',
            marker=dict(
                size=6,
                color='grey',
                opacity=0.5,
            ),
            text=o_hover_text,
            hoverinfo='text',
            name='O Tokens'
        ))

    # update layout dynamically
    if x_data is not None and y_data is not None and z_data is not None:
        # 3D
        fig.update_layout(
            title="GUS-Net Entity Attentions Visualization",
            scene=dict(
                xaxis=dict(title=f"{selected_dimensions[0]} Attention"),
                yaxis=dict(title=f"{selected_dimensions[1]} Attention"),
                zaxis=dict(title=f"{selected_dimensions[2]} Attention"),
            ),
            margin=dict(l=0, r=0, b=0, t=40),
        )
    elif x_data is not None and y_data is not None:
        # 2D
        fig.update_layout(
            title="GUS-Net Entity Attentions Visualization",
            xaxis_title=f"{selected_dimensions[0]} Attention",
            yaxis_title=f"{selected_dimensions[1]} Attention",
            margin=dict(l=0, r=0, b=0, t=40),
        )
    elif x_data is not None:
        # 1D
        fig.update_layout(
            title="GUS-Net Entity Attentions Visualization",
            xaxis_title=f"{selected_dimensions[0]} Attention",
            margin=dict(l=0, r=0, b=0, t=40),
        )

    return fig

def get_top_tokens_for_entities(selected_dimensions):
    entity_map = {
        'Generalization': b_gen_attention_filtered + i_gen_attention_filtered,
        'Unfairness': b_unfair_attention_filtered + i_unfair_attention_filtered,
        'Stereotype': b_stereo_attention_filtered + i_stereo_attention_filtered,
    }

    top_tokens_info = {}
    for dimension in selected_dimensions:
        if dimension in entity_map:
            attention_scores = entity_map[dimension]
            top_indices = np.argsort(attention_scores)[-10:]  # top 10 tokens
            top_tokens = [filtered_tokens[i] for i in top_indices]
            top_scores = attention_scores[top_indices]
            top_tokens_info[dimension] = list(zip(top_tokens, top_scores))

    return top_tokens_info

def update_gradio(selected_dimensions):
    fig = create_plot(selected_dimensions)

    top_tokens_info = get_top_tokens_for_entities(selected_dimensions)
    
    formatted_top_tokens = ""
    for entity, tokens_info in top_tokens_info.items():
        formatted_top_tokens += f"\nTop tokens for {entity}:\n"
        for token, score in tokens_info:
            formatted_top_tokens += f"Token: {token}, Attention Score: {score:.3f}\n"

    return fig, formatted_top_tokens


def render_gradio_interface():
    with gr.Blocks() as interface:
        with gr.Column():
            dimensions_input = gr.CheckboxGroup(
                choices=["Generalization", "Unfairness", "Stereotype"],
                label="Select Dimensions to Plot",
                value=["Generalization", "Unfairness", "Stereotype"]  # defaults to 3D
            )

            plot_output = gr.Plot(label="Token Attention Visualization")
            top_tokens_output = gr.Textbox(label="Top Tokens for Each Entity Class", lines=10)

            dimensions_input.change(
                fn=update_gradio,
                inputs=[dimensions_input],
                outputs=[plot_output, top_tokens_output]
            )

            interface.load(
                fn=lambda: update_gradio(["Generalization", "Unfairness", "Stereotype"]),
                inputs=None, 
                outputs=[plot_output, top_tokens_output]
            )

    return interface

interface = render_gradio_interface()
interface.launch()