-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmask_and_fill_by_bert.py
287 lines (241 loc) · 9.23 KB
/
mask_and_fill_by_bert.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
import os
import pickle
import random
from typing import List
import numpy as np
from tqdm import tqdm
import torch
from nltk.corpus import stopwords
from transformers import BertConfig, BertForMaskedLM, BertTokenizer
from utils import set_random_seed
stopwords = stopwords.words("english") + [".", ",", "!", "?", "'", '"']
SCORE_FNAME_TEMPLATE = "./data/scored/{}_sorted_by_condition_mlm_dd.pck"
FINAL_NEGATIVE_FNAME = (
"./data/negative_dd/dialogues_{}_negative_mask-fill-coherence{}_1.txt"
)
softmax = torch.nn.Softmax(dim=0)
def calculate_score(
context: List[str],
response: str,
bert: BertForMaskedLM,
tokenizer: BertTokenizer,
device,
):
print("=== New example ===")
print("Original Context: {}".format(context))
print("Original Response: {}".format(response))
dialog = context + " " + response
assert isinstance(dialog, str) and isinstance(response, str)
encoded_dialog = tokenizer.encode_plus(dialog, return_tensors="pt")
encoded_dialog = {k: v.to(device) for k, v in encoded_dialog.items()}
encoded_response = tokenizer.encode_plus(response, return_tensors="pt")
encoded_response = {k: v.to(device) for k, v in encoded_response.items()}
response_begin_index_in_dialog = (
len(encoded_dialog["input_ids"][0]) - len(encoded_response["input_ids"][0]) + 1
)
word_list = []
dialog_score_list, response_score_list, diff_score_list = [], [], []
for response_token_index in range(len(encoded_response["input_ids"][0]) - 2):
response_index_in_dialog = response_token_index + response_begin_index_in_dialog
response_index_in_response = response_token_index + 1
# Find the original token and check the integrity
original_token_in_dialog = (
encoded_dialog["input_ids"][0][response_index_in_dialog].clone().detach()
)
original_token_in_response = (
encoded_response["input_ids"][0][response_index_in_response]
.clone()
.detach()
)
word_list.append(tokenizer.convert_ids_to_tokens([original_token_in_dialog])[0])
assert original_token_in_dialog == original_token_in_response
# Mask the current token in both dialog and response sentence
encoded_dialog["input_ids"][0][
response_index_in_dialog
] = tokenizer.mask_token_id
encoded_response["input_ids"][0][
response_index_in_response
] = tokenizer.mask_token_id
with torch.no_grad():
dialog_output = bert(**encoded_dialog)[0]
response_output = bert(**encoded_response)[0]
score_in_dialog = float(
softmax(dialog_output[0][response_index_in_dialog])[
original_token_in_dialog
]
.cpu()
.detach()
.numpy()
)
score_in_response = float(
softmax(response_output[0][response_index_in_response])[
original_token_in_response
]
.cpu()
.detach()
.numpy()
)
diff_score_list.append(np.log(score_in_dialog) - np.log(score_in_response))
dialog_score_list.append(np.log(score_in_dialog))
response_score_list.append(np.log(score_in_response))
assert (
len(word_list)
== len(diff_score_list)
== len(encoded_response["input_ids"][0]) - 2
)
return (
word_list,
diff_score_list,
[dialog_score_list, response_score_list],
)
def mask_and_fill_by_threshold(
text: str,
bert: BertForMaskedLM,
tokenizer: BertTokenizer,
threshold: float,
device,
mlm_score,
):
print("=== New example ===")
print("Original Text: {}".format(text))
context, response, word_list, score_list, sorted_index = mlm_score
if score_list is None:
raise ValueError
if len(text.split()) < 3:
return None
assert len(sorted_index[0]) == len(sorted_index[1]) == len(score_list)
response = response.strip()
text = text.strip()
assert response == text
if max(score_list) < threshold or len(score_list) < 3:
return None
encoded = tokenizer.encode_plus(
text,
return_tensors="pt",
max_length=512,
truncation=True,
)
assert len(encoded["input_ids"][0]) == len(word_list) + 2
masked_token_indices = []
masked_token_original_list = []
for idx, score in enumerate(score_list):
if score >= threshold:
masked_token_original_list.append(
encoded["input_ids"][0][idx + 1].clone().detach()
)
encoded["input_ids"][0][idx + 1] = tokenizer.mask_token_id
masked_token_indices.append(idx + 1)
encoded = {k: v.to(device) for k, v in encoded.items()}
with torch.no_grad():
output = bert(**encoded)[0]
changed_indices = []
for mask_order, mask_index in enumerate(masked_token_indices):
while True:
decoded_index = torch.argmax(output[0][mask_index]).item()
if decoded_index not in [masked_token_original_list[mask_order]]:
break
output[0][mask_index, decoded_index] = -100
changed_indices.append(decoded_index)
for idx, mask_position in enumerate(masked_token_indices):
encoded["input_ids"][0][mask_position] = changed_indices[idx]
changed_response = tokenizer.decode(
encoded["input_ids"][0],
skip_special_tokens=True,
clean_up_tokenization_spaces=True,
)
print("Changed: {}".format(changed_response))
return changed_response
def make_context_and_response_file(setname="train"):
if setname == "valid":
setname = "validation"
with open(
"./data/ijcnlp_dailydialog/{}/dialogues_{}.txt".format(setname, setname), "r"
) as f:
ls = [line.strip().split("__eou__") for line in f.readlines()]
ls = [[el.lower() for el in line if len(el.strip()) != 0] for line in ls]
new_dataset = []
for idx, line in enumerate(ls):
context = line[0]
response = line[1]
new_dataset.append([context, response, random.sample(ls, 1)[0][-1]])
return new_dataset
def make_score_file():
for setname in ["valid", "train"]:
final_fname = SCORE_FNAME_TEMPLATE.format(setname)
device = torch.device("cuda")
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
bert = BertForMaskedLM.from_pretrained("bert-base-uncased").to(device)
bert.eval()
ls = make_context_and_response_file(setname)
assert all([len(el) == 3 for el in ls])
output = []
for line_index, line in enumerate(tqdm(ls)):
context, response, _ = [el.strip() for el in line]
try:
words, scores, additional_scores = calculate_score(
context,
response,
bert,
tokenizer,
device,
)
except Exception as err:
print("\n" * 30)
print(err)
words, scores, additional_scores = None, None, None
output.append(
[
context.strip(),
response.strip(),
words,
scores,
additional_scores,
]
)
print("{}/{} is filled".format(len(output), len(ls)))
os.makedirs(os.path.dirname(final_fname),exist_ok=True)
with open(final_fname, "wb") as f:
pickle.dump(output, f)
def make_negative(threshold: float = 0.5):
for setname in ["valid", "train"]:
threshold_fname = SCORE_FNAME_TEMPLATE.format(setname)
with open(threshold_fname, "rb") as f:
score_data = pickle.load(f)
final_fname = FINAL_NEGATIVE_FNAME.format(setname, threshold)
print(final_fname)
# assert not os.path.exists(final_fname)
device = torch.device("cuda")
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
bert = BertForMaskedLM.from_pretrained("bert-base-uncased")
bert.to(device)
bert.eval()
ls = make_context_and_response_file(setname=setname)
assert all([len(el) == 3 for el in ls])
output = []
assert len(ls) == len(score_data)
for line_index, line in enumerate(tqdm(ls)):
score = score_data[line_index]
print(f"{line_index}/{len(ls)}")
context, response, _ = line
response = response.strip()
generated_response = mask_and_fill_by_threshold(
response,
bert,
tokenizer,
threshold,
device,
score,
)
if generated_response is None:
generated_response = "[NONE]"
output.append([context.strip(), response.strip(), generated_response])
os.makedirs(os.path.dirname(final_fname), exist_ok=True)
print("{}/{} is filled".format(len(output), len(ls)))
with open(final_fname, "w") as f:
for line in output:
f.write("|||".join(line))
f.write("\n")
if __name__ == "__main__":
set_random_seed(42)
make_score_file()
make_negative()