forked from facebookresearch/EGG
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathintervention.py
236 lines (176 loc) · 6.63 KB
/
intervention.py
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
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import json
import torch
from scipy import spatial
from scipy.stats import spearmanr
import egg.core as core
from egg.core.batch import Batch
from egg.zoo.language_bottleneck.intervention import entropy, mutual_info
try:
import editdistance # package to install https://pypi.org/project/editdistance/0.3.1/
except ImportError:
print(
"Please install editdistance package: `pip install editdistance`. "
"It is used for calculating topographic similarity."
)
def ask_sender(n_attributes, n_values, dataset, sender, device):
attributes = []
strings = []
meanings = []
for i in range(len(dataset)):
meaning = dataset[i]
attribute = meaning.view(n_attributes, n_values).argmax(dim=-1)
attributes.append(attribute)
meanings.append(meaning.to(device))
with torch.no_grad():
string, *other = sender(meaning.unsqueeze(0).to(device))
strings.append(string.squeeze(0))
attributes = torch.stack(attributes, dim=0)
strings = torch.stack(strings, dim=0)
meanings = torch.stack(meanings, dim=0)
return attributes, strings, meanings
def information_gap_representation(meanings, representations):
gaps = torch.zeros(representations.size(1))
non_constant_positions = 0.0
for j in range(representations.size(1)):
symbol_mi = []
h_j = None
for i in range(meanings.size(1)):
x, y = meanings[:, i], representations[:, j]
info = mutual_info(x, y)
symbol_mi.append(info)
if h_j is None:
h_j = entropy(y)
symbol_mi.sort(reverse=True)
if h_j > 0.0:
gaps[j] = (symbol_mi[0] - symbol_mi[1]) / h_j
non_constant_positions += 1
score = gaps.sum() / non_constant_positions
return score.item()
def information_gap_position(n_attributes, n_values, dataset, sender, device):
attributes, strings, _meanings = ask_sender(
n_attributes, n_values, dataset, sender, device
)
return information_gap_representation(attributes, strings)
def histogram(strings, vocab_size):
batch_size = strings.size(0)
histogram = torch.zeros(batch_size, vocab_size, device=strings.device)
for v in range(vocab_size):
histogram[:, v] = strings.eq(v).sum(dim=-1)
return histogram
def information_gap_vocab(n_attributes, n_values, dataset, sender, device, vocab_size):
attributes, strings, _meanings = ask_sender(
n_attributes, n_values, dataset, sender, device
)
histograms = histogram(strings, vocab_size)
return information_gap_representation(attributes, histograms[:, 1:])
def edit_dist(_list):
distances = []
count = 0
for i, el1 in enumerate(_list[:-1]):
for j, el2 in enumerate(_list[i + 1 :]):
count += 1
# Normalized edit distance (same in our case as length is fixed)
distances.append(editdistance.eval(el1, el2) / len(el1))
return distances
def cosine_dist(_list):
distances = []
for i, el1 in enumerate(_list[:-1]):
for j, el2 in enumerate(_list[i + 1 :]):
distances.append(spatial.distance.cosine(el1, el2))
return distances
def topographic_similarity(n_attributes, n_values, dataset, sender, device):
_attributes, strings, meanings = ask_sender(
n_attributes, n_values, dataset, sender, device
)
list_string = []
for s in strings:
list_string.append([x.item() for x in s])
distance_messages = edit_dist(list_string)
distance_inputs = cosine_dist(meanings.cpu().numpy())
corr = spearmanr(distance_messages, distance_inputs).correlation
return corr
class Metrics(core.Callback):
def __init__(self, dataset, device, n_attributes, n_values, vocab_size, freq=1):
self.dataset = dataset
self.device = device
self.n_attributes = n_attributes
self.n_values = n_values
self.epoch = 0
self.vocab_size = vocab_size
self.freq = freq
def dump_stats(self):
game = self.trainer.game
game.eval()
positional_disent = information_gap_position(
self.n_attributes, self.n_values, self.dataset, game.sender, self.device
)
bos_disent = information_gap_vocab(
self.n_attributes,
self.n_values,
self.dataset,
game.sender,
self.device,
self.vocab_size,
)
topo_sim = topographic_similarity(
self.n_attributes, self.n_values, self.dataset, game.sender, self.device
)
output = dict(
epoch=self.epoch,
positional_disent=positional_disent,
bag_of_symbol_disent=bos_disent,
topographic_sim=topo_sim,
)
output_json = json.dumps(output)
print(output_json, flush=True)
game.train()
def on_train_end(self):
self.dump_stats()
def on_epoch_end(self, *stuff):
self.epoch += 1
if self.freq <= 0 or self.epoch % self.freq != 0:
return
self.dump_stats()
class Evaluator(core.Callback):
def __init__(self, loaders_metrics, device, freq=1):
self.loaders_metrics = loaders_metrics
self.device = device
self.epoch = 0
self.freq = freq
self.results = {}
def evaluate(self):
game = self.trainer.game
game.eval()
old_loss = game.loss
for loader_name, loader, metric in self.loaders_metrics:
acc_or, acc = 0.0, 0.0
n_batches = 0
game.loss = metric
for batch in loader:
n_batches += 1
if not isinstance(batch, Batch):
batch = Batch(*batch)
batch = batch.to(self.device)
with torch.no_grad():
_, interaction = game(*batch)
acc += interaction.aux["acc"].mean().item()
acc_or += interaction.aux["acc_or"].mean().item()
self.results[loader_name] = {
"acc": acc / n_batches,
"acc_or": acc_or / n_batches,
}
self.results["epoch"] = self.epoch
output_json = json.dumps(self.results)
print(output_json, flush=True)
game.loss = old_loss
game.train()
def on_train_end(self):
self.evaluate()
def on_epoch_end(self, *stuff):
self.epoch += 1
if self.freq <= 0 or self.epoch % self.freq != 0:
return
self.evaluate()