-
Notifications
You must be signed in to change notification settings - Fork 0
/
compute_perplexity.py
327 lines (281 loc) · 13 KB
/
compute_perplexity.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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# Based on http://nlp.cs.washington.edu/zeroshot/evaluate.py
import pandas as pd
import os
import codecs
import re
import string
import sys
import numpy as np
PUNCTUATION = set(string.punctuation)
import re
def remove_latin(text):
return re.sub(r'[^\x00-\x7f]',r'', text)
def unk_zero_re_eval(test_file, answer_file):
q_aprf = unk_read_results(test_file, answer_file)
return pretify(q_aprf)
def unk_read_results(test_set, answer_file):
with codecs.open(test_set, "r", "utf-8") as fin:
data = [line.strip().split("\t") for line in fin]
metadata = [x[:4] for x in data]
gold = [set(x[4:]) for x in data]
with codecs.open(answer_file, "r", "utf-8") as fin:
answers = [line.strip() for line in fin]
new_answers = []
for answer in answers[1:]:
if answer != "no_answer":
new_answers.append(answer)
else:
new_answers.append("")
telemetry = []
for m, g, a in zip(metadata, gold, new_answers):
stats = score(g, a)
telemetry.append([m[0], m[1], str(len(g) > 0), stats])
return aprf(telemetry)
def parse_no_answers(results):
p_answer = [
a for i, a in sorted([(int(i), a) for i, a in results[0]["scores"].items()])
]
p_no_answer = [
a for i, a in sorted([(int(i), a) for i, a in results[0]["na"].items()])
]
import numpy as np
return [answer > no_answer for answer, no_answer in zip(p_answer, p_no_answer)]
def gb(collection, keyfunc):
return [(k, list(g)) for k, g in groupby(sorted(collection, key=keyfunc), keyfunc)]
def aprf(g):
tp, tn, sys_pos, real_pos = sum(map(lambda x: x[-1], g))
total = len(g)
# a = float(tp + tn) / total
# nr = tn / float(total - real_pos)
# npr = tn / float(total - sys_pos)
if tp == 0:
p = r = f = 0.0
else:
p = tp / float(sys_pos)
r = tp / float(real_pos)
f = 2 * p * r / (p + r)
# return np.array((a, p, r, f, npr, nr))
return np.array((p, r, f))
def score(gold, answer):
if len(gold) > 0:
gold = set.union(*[simplify(g) for g in gold])
answer = simplify(answer)
result = np.zeros(4)
if answer == gold:
if len(gold) > 0:
result[0] += 1
else:
result[1] += 1
if len(answer) > 0:
result[2] += 1
if len(gold) > 0:
result[3] += 1
return result
def simplify(answer):
return set(
"".join(c for c in t if c not in PUNCTUATION)
for t in answer.strip().lower().split()
) - {"the", "a", "an", "and", ""}
def pretify(results):
return " \t ".join(
[
": ".join((k, v))
for k, v in zip(
["Precision", "Recall", "F1"],
map(lambda r: "{0:.2f}%".format(r * 100), results),
)
]
)
from transformers import GPT2LMHeadModel, GPT2TokenizerFast
device = "cuda"
model_id = "gpt2-large"
model = GPT2LMHeadModel.from_pretrained(model_id).to(device)
tokenizer = GPT2TokenizerFast.from_pretrained(model_id)
import torch
def compute_perplexity_for_questions(main_path, file):
ppls = []
df = pd.read_csv(os.path.join(main_path, file), sep=',')
questions = df["question_predictions"].tolist()
for question in questions:
encodings = tokenizer(question, return_tensors="pt")
input_ids = encodings.input_ids.to(device)
b_sz, length = input_ids.size()
target_ids = input_ids.clone()
with torch.no_grad():
outputs = model(input_ids, labels=target_ids)
neg_log_likelihood = outputs[0]
ppl = torch.exp(neg_log_likelihood)
ppls.append(ppl)
ppl = torch.stack(ppls).mean()
return ppl
def gold_compute_perplexity_for_questions(main_path, file):
ppls = []
df = pd.read_csv(os.path.join(main_path, file), sep=',')
inputs = df["input_str"].tolist()
for inp in inputs:
question = inp.split("context:")[0].replace("question:", "").strip()
encodings = tokenizer(question, return_tensors="pt")
input_ids = encodings.input_ids.to(device)
b_sz, length = input_ids.size()
target_ids = input_ids.clone()
with torch.no_grad():
outputs = model(input_ids, labels=target_ids)
neg_log_likelihood = outputs[0]
ppl = torch.exp(neg_log_likelihood)
ppls.append(ppl)
ppl = torch.stack(ppls).mean()
return ppl
def preprocess_the_prediction_files(main_path, list_of_files):
for file in list_of_files:
df = pd.read_csv(os.path.join(main_path, file), sep=',')
df["predictions_str"].to_csv(os.path.join("/tmp/", file), sep='\t', header=True, index=False)
def unk_eval_the_prediction_files(list_of_files, gold_file):
scores = {}
scores_list = []
precision_list = []
recall_list = []
for file in list_of_files:
score = unk_zero_re_eval(gold_file, os.path.join("/tmp/", file))
arr = score.split()
f1_score = float(arr[-1][0:-1])
precision = float(arr[1][0:-1])
recall = float(arr[3][0:-1])
scores[f1_score] = file
scores_list.append(f1_score)
precision_list.append(precision)
recall_list.append(recall)
f1s = np.array(scores_list)
precisions = np.array(precision_list)
recalls = np.array(recall_list)
max_f1 = max(scores.keys())
return scores[max_f1], max_f1, f1s, scores, precisions, recalls
results = {}
for fold_i in range(1, 11, 1):
results[fold_i] = {'mml-pgg-off-sim': {},
'mml-pgg-on-sim': {},
'mml-mml-off-sim': {},
'mml-mml-on-sim': {}}
print("# Evaluating the dev predictions on the RE-QA dataset on all folds for the tail entity generation task.")
# Evaluating the dev predictions on the RE-QA dataset on all folds for the tail entity generation task.
folders = ["mml-pgg-off-sim", "mml-pgg-on-sim", "mml-mml-off-sim", "mml-mml-on-sim"]
for fold_i in range(1, 11, 1):
for folder in folders:
fold_gold_file = "./zero-shot-extraction/relation_splits/dev.{}".format(fold_i-1)
fold_path = "~/reqa-predictions/fold_{}/{}/".format(fold_i, folder)
if fold_i == 1:
fold_files = ["{}.fold.{}.dev.predictions.step.{}.csv".format(folder, fold_i, 100 * i) for i in range(1, 101, 1)]
elif 2 <= fold_i <= 4:
if folder == "mml-pgg-off-sim":
fold_files = ["{}.fold.{}.dev.predictions.step.{}.csv".format(folder, fold_i, 100 * i) for i in range(1, 101, 1)]
else:
fold_files = ["{}.dev.predictions.fold.{}.step.{}.csv".format(folder, fold_i, 100 * i) for i in range(1, 101, 1)]
else:
if folder == "mml-pgg-off-sim":
fold_files = ["{}.fold.{}.dev.predictions.step.{}.csv".format(folder, fold_i, 100 * i) for i in range(1, 201, 1)]
else:
fold_files = ["{}.dev.predictions.fold.{}.step.{}.csv".format(folder, fold_i, 100 * i) for i in range(1, 201, 1)]
preprocess_the_prediction_files(fold_path, fold_files)
max_file, max_f1, f1s, scores, precisions, recalls = unk_eval_the_prediction_files(fold_files, fold_gold_file)
print(folder, fold_i, max_file, max_f1)
print("\n")
results[fold_i][folder] = max_file
print("NEXT")
print("# Evaluating the test predictions on the RE-QA dataset on all folds for the tail entity generation task.")
# Evaluating the test predictions on the RE-QA dataset on all folds for the tail entity generation task.
folders = ["mml-pgg-on-sim", "mml-mml-off-sim", "mml-mml-on-sim", "mml-pgg-off-sim"]
for folder in folders:
avg_f1 = {"mml-mml-off-sim": 0, "mml-mml-on-sim": 0, "mml-pgg-on-sim": 0, "mml-pgg-off-sim": 0}
avg_p = {"mml-mml-off-sim": 0, "mml-mml-on-sim": 0, "mml-pgg-on-sim": 0, "mml-pgg-off-sim": 0}
avg_r = {"mml-mml-off-sim": 0, "mml-mml-on-sim": 0, "mml-pgg-on-sim": 0, "mml-pgg-off-sim": 0}
for fold_i in range(1, 11, 1):
fold_gold_file = "./zero-shot-extraction/relation_splits/test.{}".format(fold_i-1)
fold_path = "~/reqa-predictions/fold_{}/{}".format(fold_i, folder)
old_dev_file = results[fold_i][folder]
new_test_file = old_dev_file.replace(".fold.{}.dev.predictions.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
new_test_file = new_test_file.replace(".dev.predictions.fold.{}.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
fold_files = [new_test_file]
preprocess_the_prediction_files(fold_path, fold_files)
max_file, max_f1, f1s, scores, precisions, recalls = unk_eval_the_prediction_files(fold_files, fold_gold_file)
print(folder, fold_i, max_file, max_f1)
avg_f1[folder] += max_f1
avg_p[folder] += precisions[0]
avg_r[folder] += recalls[0]
print("\n")
print(folder, "f1", avg_f1[folder] / 10.0)
print(folder, "p", avg_p[folder] / 10.0)
print(folder, "r", avg_r[folder] / 10.0)
print("NEXT")
print("# Compute perplexity over the test generated questions for the following method on the RE-QA dataset.")
# Compute perplexity over the test generated questions for the following method on the RE-QA dataset.
folders = ["mml-mml-off-sim"]
for folder in folders:
avg_pp = {"mml-mml-off-sim": 0}
for fold_i in range(9, 11, 1):
fold_path = "~/reqa-predictions/fold_{}/{}".format(fold_i, folder)
old_dev_file = results[fold_i][folder]
new_test_file = old_dev_file.replace(".fold.{}.dev.predictions.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
new_test_file = new_test_file.replace(".dev.predictions.fold.{}.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
fold_file = new_test_file
pp = compute_perplexity_for_questions(fold_path, fold_file)
avg_pp[folder] += pp
print(fold_file, pp)
print("\n")
print(folder, "pp", avg_pp[folder] / 10.0)
print("# Compute perplexity over the test generated questions for the following method on the RE-QA dataset.")
# Compute perplexity over the test generated questions for the following method on the RE-QA dataset.
folders = ["mml-pgg-off-sim"]
for folder in folders:
avg_pp = {"mml-pgg-off-sim": 0}
for fold_i in range(1, 11, 1):
fold_path = "~/reqa-predictions/fold_{}/{}".format(fold_i, folder)
old_dev_file = results[fold_i][folder]
new_test_file = old_dev_file.replace(".fold.{}.dev.predictions.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
new_test_file = new_test_file.replace(".dev.predictions.fold.{}.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
fold_file = new_test_file
pp = compute_perplexity_for_questions(fold_path, fold_file)
avg_pp[folder] += pp
print(fold_file, pp)
print("\n")
print(folder, "pp", avg_pp[folder] / 10.0)
print("# Compute perplexity over the test generated questions for the following method on the RE-QA dataset.")
# Compute perplexity over the test generated questions for the following method on the RE-QA dataset.
folders = ["mml-pgg-on-sim"]
for folder in folders:
avg_pp = {"mml-pgg-on-sim": 0}
for fold_i in range(1, 11, 1):
fold_path = "~/reqa-predictions/fold_{}/{}".format(fold_i, folder)
old_dev_file = results[fold_i][folder]
new_test_file = old_dev_file.replace(".fold.{}.dev.predictions.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
new_test_file = new_test_file.replace(".dev.predictions.fold.{}.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
fold_file = new_test_file
pp = compute_perplexity_for_questions(fold_path, fold_file)
avg_pp[folder] += pp
print(fold_file, pp)
print("\n")
print(folder, "pp", avg_pp[folder] / 10.0)
print("# Compute perplexity over the test generated questions for the following method on the RE-QA dataset.")
# Compute perplexity over the test generated questions for the following method on the RE-QA dataset.
folders = ["mml-mml-on-sim"]
for folder in folders:
avg_pp = {"mml-mml-on-sim": 0}
for fold_i in range(1, 11, 1):
fold_path = "~/reqa-predictions/fold_{}/{}".format(fold_i, folder)
old_dev_file = results[fold_i][folder]
new_test_file = old_dev_file.replace(".fold.{}.dev.predictions.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
new_test_file = new_test_file.replace(".dev.predictions.fold.{}.".format(fold_i), ".test.predictions.fold.{}.".format(fold_i))
fold_file = new_test_file
pp = compute_perplexity_for_questions(fold_path, fold_file)
avg_pp[folder] += pp
print(fold_file, pp)
print("\n")
print(folder, "pp", avg_pp[folder] / 10.0)
print("# PP for the base-base predictions on the RE-QA dataset.")
avg_pp = 0.0
for fold_i in range(1, 11, 1):
fold_path = "~/reqa-predictions/fold_{}/".format(fold_i)
fold_file = "base-base.test.predictions.fold.{}.csv".format(fold_i)
pp = compute_perplexity_for_questions(fold_path, fold_file)
avg_pp += pp
print(fold_file, pp)
print("\n")
print("pp", avg_pp / 10.0)