File size: 9,268 Bytes
4ae80b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcbb55b
4ae80b2
 
 
 
c56dde4
4ae80b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c56dde4
 
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
#############################
#   Imports
#############################

# Python modules

# Remote modules
import matplotlib.pyplot as plt
import numpy as np
import torch

# Local modules

#############################
#   Constants
#############################

class AttentionVisualizer:
    def __init__(self, device):
        self.device = device

    def visualize_token2token_scores(self, all_tokens,
                                     scores_mat,
                                     useful_indeces,
                                     x_label_name='Head',
                                     apply_normalization=True):
        fig = plt.figure(figsize=(20, 20))

        all_tokens = np.array(all_tokens)[useful_indeces]
        for idx, scores in enumerate(scores_mat):
            if apply_normalization:
                scores = torch.from_numpy(scores)
                shape = scores.shape
                scores = scores.reshape((shape[0],shape[1], 1))
                scores = torch.linalg.norm(scores, dim=2)
            scores_np = np.array(scores)
            scores_np = scores_np[useful_indeces, :]
            scores_np = scores_np[:, useful_indeces]
            ax = fig.add_subplot(4, 4, idx + 1)
            # append the attention weights
            im = ax.imshow(scores_np, cmap='viridis')

            fontdict = {'fontsize': 10}

            ax.set_xticks(range(len(all_tokens)))
            ax.set_yticks(range(len(all_tokens)))

            ax.set_xticklabels(all_tokens, fontdict=fontdict, rotation=90)
            ax.set_yticklabels(all_tokens, fontdict=fontdict)
            ax.set_xlabel('{} {}'.format(x_label_name, idx + 1))

            fig.colorbar(im, fraction=0.046, pad=0.04)
        plt.tight_layout()
        plt.show()

    def visualize_matrix(self,
                         scores_mat,
                         label_name='heads_layers'):
        _fig = plt.figure(figsize=(20, 20))
        scores_np = np.array(scores_mat)
        fig, ax = plt.subplots()
        im = ax.imshow(scores_np, cmap='viridis')

        fontdict = {'fontsize': 10}

        ax.set_xticks(range(len(scores_mat[0])))
        ax.set_yticks(range(len(scores_mat)))

        x_labels = [f'head-{i}' for i in range(1, len(scores_mat[0])+1)]
        y_labels = [f'layer-{i}' for i in range(1, len(scores_mat) + 1)]

        ax.set_xticklabels(x_labels, fontdict=fontdict, rotation=90)
        ax.set_yticklabels(y_labels, fontdict=fontdict)
        ax.set_xlabel('{}'.format(label_name))

        fig.colorbar(im, fraction=0.046, pad=0.04)
        plt.tight_layout()
        #plt.show()
        plt.savefig(f'figs/{label_name}.png', dpi=fig.dpi)

    def visualize_token2head_scores(self, all_tokens, scores_mat):
        fig = plt.figure(figsize=(30, 50))
        for idx, scores in enumerate(scores_mat):
            scores_np = np.array(scores)
            ax = fig.add_subplot(6, 3, idx + 1)
            # append the attention weights
            im = ax.matshow(scores_np, cmap='viridis')

            fontdict = {'fontsize': 20}

            ax.set_xticks(range(len(all_tokens)))
            ax.set_yticks(range(len(scores)))

            ax.set_xticklabels(all_tokens, fontdict=fontdict, rotation=90)
            ax.set_yticklabels(range(len(scores[0])), fontdict=fontdict)
            ax.set_xlabel('Layer {}'.format(idx + 1))

            fig.colorbar(im, fraction=0.046, pad=0.04)
        plt.tight_layout()
        plt.show()

    def plot_attn_lines(self, data, heads):
        """Plots attention maps for the given example and attention heads."""
        width = 3
        example_sep = 3
        word_height = 1
        pad = 0.1

        for ei, (layer, head) in enumerate(heads):
            yoffset = 1
            xoffset = ei * width * example_sep

            attn = data["attns"][layer][head]
            attn = np.array(attn)
            attn /= attn.sum(axis=-1, keepdims=True)
            words = data["tokens"]
            words[0] = "..."
            n_words = len(words)

            for position, word in enumerate(words):
                plt.text(xoffset + 0, yoffset - position * word_height, word,
                         ha="right", va="center")
                plt.text(xoffset + width, yoffset - position * word_height, word,
                         ha="left", va="center")
            for i in range(1, n_words):
                for j in range(1, n_words):
                    plt.plot([xoffset + pad, xoffset + width - pad],
                             [yoffset - word_height * i, yoffset - word_height * j],
                             color="blue", linewidth=1, alpha=attn[i, j])

    def plot_attn_lines_concepts(self, title, examples, layer, head, color_words,
                  color_from=True, width=3, example_sep=3,
                  word_height=1, pad=0.1, hide_sep=False):
        # examples -> {'words': tokens, 'attentions': [layer][head]}
        plt.figure(figsize=(4, 4))
        for i, example in enumerate(examples):
            yoffset = 0
            if i == 0:
                yoffset += (len(examples[0]["words"]) -
                            len(examples[1]["words"])) * word_height / 2
            xoffset = i * width * example_sep
            attn = example["attentions"][layer][head]
            if hide_sep:
                attn = np.array(attn)
                attn[:, 0] = 0
                attn[:, -1] = 0
                attn /= attn.sum(axis=-1, keepdims=True)

            words = example["words"]
            n_words = len(words)
            for position, word in enumerate(words):
                for x, from_word in [(xoffset, True), (xoffset + width, False)]:
                    color = "k"
                    if from_word == color_from and word in color_words:
                        color = "#cc0000"
                    plt.text(x, yoffset - (position * word_height), word,
                             ha="right" if from_word else "left", va="center",
                             color=color)

            for i in range(n_words):
                for j in range(n_words):
                    color = "b"
                    if words[i if color_from else j] in color_words:
                        color = "r"
                    print(attn[i, j])
                    plt.plot([xoffset + pad, xoffset + width - pad],
                             [yoffset - word_height * i, yoffset - word_height * j],
                             color=color, linewidth=1, alpha=attn[i, j])
        plt.axis("off")
        plt.title(title)
        plt.show()

    def plot_attn_lines_concepts_ids(self, title, examples, layer, head,
                                     relations_total, width=3, example_sep=3,
                                     word_height=1, pad=0.1, hide_sep=False):
        # examples -> {'words': tokens, 'attentions': [layer][head]}
        plt.clf()
        fig = plt.figure(figsize=(10, 5))
        # print('relations_total:', relations_total)
        # print(examples[0])
        for idx, example in enumerate(examples):
            yoffset = 0
            if idx == 0:
                yoffset += (len(examples[0]["words"]) -
                            len(examples[0]["words"])) * word_height / 2
            xoffset = idx * width * example_sep
            attn = example["attentions"][layer][head]
            if hide_sep:
                attn = np.array(attn)
                attn[:, 0] = 0
                attn[:, -1] = 0
                attn /= attn.sum(axis=-1, keepdims=True)

            words = example["words"]
            n_words = len(words)
            example_rel = relations_total[idx]
            for position, word in enumerate(words):
                for x, from_word in [(xoffset, True), (xoffset + width, False)]:
                    color = "k"
                    for y_idx, y in enumerate(words):
                        if from_word and example_rel[position, y_idx] > 0:
                            # print('outgoing', position, y_idx)
                            color = "r"
                        if not from_word and example_rel[y_idx, position] > 0:
                            # print('coming', position, y_idx)
                            color = "g"
                    # if from_word == color_from and word in color_words:
                    #    color = "#cc0000"
                    plt.text(x, yoffset - (position * word_height), word,
                             ha="right" if from_word else "left", va="center",
                             color=color)

            for i in range(n_words):
                for j in range(n_words):
                    color = "k"
                    # print(i,j, example_rel[i,j])
                    if example_rel[i, j].item() > 0 and i <= j:
                        color = "r"
                    if example_rel[i, j].item() > 0 and i >= j:
                        color = "g"
                    plt.plot([xoffset + pad, xoffset + width - pad],
                             [yoffset - word_height * i, yoffset - word_height * j],
                             color=color, linewidth=1, alpha=attn[i, j])
                    # color=color, linewidth=1, alpha=min(attn[i, j]*10,1))
        plt.axis("off")
        plt.title(title)
        #plt.show()
        return fig