-
Notifications
You must be signed in to change notification settings - Fork 0
/
build_data_PersonaChat.py
255 lines (216 loc) · 11.2 KB
/
build_data_PersonaChat.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
import random
from tqdm import tqdm
import torch
from collections import defaultdict
from torch.nn.utils.rnn import pad_sequence
import numpy as np
import json
def get_token_id(tokenizer):
bos_id = tokenizer.bos_token_id
eos_id = tokenizer.eos_token_id
pad_id = tokenizer.pad_token_id
sep_id = tokenizer.sep_token_id
query_id, res_id, latent_id, persona_id = tokenizer.convert_tokens_to_ids(
['<query>', '<response>', '<latent>', '<persona>'])
return bos_id, eos_id, pad_id, sep_id, query_id, res_id, latent_id, persona_id
def create_data(data_file, smalldataset):
with open(data_file, "r", encoding="utf8") as f:
persona =[]
query = []
response = []
cand = []
is_persona = False
tmp_persona = []
tmp_query = []
tmp_response = []
tmp_cand = []
first = True
cnt = 0
sum_u = 0
for line in f:
cnt += 1
line = line.strip()
if "your persona: " in line:
if not is_persona and not first:
query.append(tmp_query)
response.append(tmp_response)
cand.append(tmp_cand)
sum_u += len(tmp_query)
tmp_query = []
tmp_response = []
tmp_cand = []
first = False
is_persona = True
line = line.split(": ", maxsplit=1)[1]
tmp_persona.append(line)
else:
if is_persona:
persona.append(tmp_persona)
is_persona = False
tmp_persona = []
line = line[line.find(" ")+1:]
tmp_query.append(line.split("\t")[0])
tmp_response.append(line.split("\t")[1])
tmp_cand.append(line.split("\t")[3].split("|"))
query.append(tmp_query)
response.append(tmp_response)
cand.append(tmp_cand)
sum_u += len(tmp_query)
assert len(query) == len(response) == len(persona) == len(cand)
if smalldataset:
query = query[:32]
response = response[:32]
persona = persona[:32]
cand = cand[:32]
print("used 32 pairs of datasets personal chat\n")
print("{} has {} dialog and {} query".format(data_file, len(query), sum_u))
return persona, query, response, cand
def create_encoder_input(per, history, query_id, res_id, latent_id, persona_id, sep_id, eos_id):
encoder_input_ids = []
#per_input_ids = [latent_id] + [persona_id]
per_input_ids = [persona_id]
for x in per:
per_input_ids += x + [sep_id]
encoder_input_ids += per_input_ids
for i in range(len(history)):
if i % 2 == 0:
encoder_input_ids += [query_id] + history[i] + [eos_id]
else:
encoder_input_ids += [res_id] + history[i] + [eos_id]
attention_mask = [1] * len(encoder_input_ids)
per_attention_mask = [1] * len(per_input_ids)
return encoder_input_ids, attention_mask, per_input_ids, per_attention_mask
def create_decoder_input(response_ids, res_id, eos_id, golden=None):
assert golden != None
decoder_lmlabel= response_ids + [eos_id]
decoder_input_ids = [res_id] + response_ids
decoder_cls_index = [-100] * (len(decoder_lmlabel) - 1) + [eos_id]
decoder_attention_mask = [1] * len(decoder_input_ids)
if golden == False:
decoder_lmlabel = [-100] * len(decoder_lmlabel)
assert len(decoder_lmlabel) == len(decoder_input_ids)
return decoder_lmlabel, decoder_input_ids, decoder_cls_index, decoder_attention_mask
def build_dataloader(persona, query, response, cand, tokenizer, max_history=7, n_cand=5, use_all=False):
bos_id, eos_id, pad_id, sep_id, query_id, res_id, latent_id, persona_id = get_token_id(tokenizer)
dataset = defaultdict(list)
for i in range(len(persona)):
persona_ = persona[i]
per_list = []
for per in persona_:
persona_ids = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(per, add_prefix_space=True))
per_list.append(persona_ids)
query_ = query[i]
response_ = response[i]
cand_ = cand[i]
history = []
assert len(query_) == len(response_)
for j in range(len(query_)):
if use_all:
noise_candidate = cand_[j][:-1]
else:
noise_candidate = random.sample(cand_[j][:-1], n_cand-1)
query_ids = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(query_[j], add_prefix_space=True))
response_ids = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(response_[j], add_prefix_space=True))
noise_cand_ids_list = [tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text, add_prefix_space=True))
for text in noise_candidate]
history.append(query_ids)
history.append(response_ids)
tmp_history = history[-2 * max_history: -1]
encoder_input_ids, attention_mask, \
per_input_ids, per_attention_mask = create_encoder_input(per_list, tmp_history, query_id, res_id,
latent_id, persona_id, sep_id, eos_id)
decoder_lmlabel, decoder_input_ids, decoder_cls_idx,\
decoder_attention_mask = create_decoder_input(response_ids, res_id, eos_id, golden=True)
dataset["input_ids"].append(encoder_input_ids)
dataset["attention_mask"].append(attention_mask)
dataset["per_input_ids"].append(per_input_ids)
dataset["per_attention_mask"].append(per_attention_mask)
dataset["lmlabels"].append(decoder_lmlabel)
dataset["decoder_input_ids"].append(decoder_input_ids)
dataset["decoder_attention_mask"].append(decoder_attention_mask)
dataset["cls_index"].append(decoder_cls_idx)
dataset["clslabel"].append([0])
for k in range(len(noise_cand_ids_list)):
decoder_lmlabel, decoder_input_ids, decoder_cls_idx,\
decoder_attention_mask = create_decoder_input(noise_cand_ids_list[k], res_id, eos_id, golden=False)
dataset["input_ids"].append(encoder_input_ids)
dataset["attention_mask"].append(attention_mask)
dataset["per_input_ids"].append(per_input_ids)
dataset["per_attention_mask"].append(per_attention_mask)
dataset["lmlabels"].append(decoder_lmlabel)
dataset["decoder_input_ids"].append(decoder_input_ids)
dataset["decoder_attention_mask"].append(decoder_attention_mask)
dataset["cls_index"].append(decoder_cls_idx)
for item_name, item in dataset.items():
if item_name == "input_ids" or item_name == "per_input_ids":
item = pad_sequence([torch.from_numpy(np.array(x)) for x in item],
batch_first=True, padding_value=pad_id)
dataset[item_name] = item
elif item_name == "lmlabels":
item = pad_sequence([torch.from_numpy(np.array(x)) for x in item],
batch_first=True, padding_value=-100)
dataset[item_name] = item
elif item_name == "attention_mask" or item_name == "decoder_attention_mask" or item_name == "per_attention_mask":
item = pad_sequence([torch.from_numpy(np.array(x)) for x in item],
batch_first=True, padding_value=0)
dataset[item_name] = item
elif item_name == "decoder_input_ids":
item = pad_sequence([torch.from_numpy(np.array(x)) for x in item],
batch_first=True, padding_value=pad_id)
dataset[item_name] = item
elif item_name == "clslabel":
dataset[item_name] = torch.tensor(item).view(-1,1)
elif item_name == "cls_index":
item = pad_sequence([torch.from_numpy(np.array(x)) for x in item],
batch_first=True, padding_value=-100)
dataset[item_name] = item
return dataset
def build_infer_dataset(tokenizer, file_path, smalldataset):
bos_id, eos_id, pad_id, sep_id, query_id, res_id, latent_id, persona_id = get_token_id(tokenizer)
positive_set = defaultdict(list)
with open(file_path, "r") as f:
row_data = json.load(f)
for obj in tqdm(row_data, desc='Generate infer data'):
if obj['label'] == "neutral" or obj['label'] == "negative":
continue
pre = obj["sentence1"].lower()
hyp = obj["sentence2"].lower()
pre_ids = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(pre, add_prefix_space=True))
hyp_ids = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(hyp, add_prefix_space=True))
encoder_input_ids = [persona_id] + pre_ids + [eos_id]
#encoder_input_ids = [latent_id] + [persona_id] + pre_ids + [eos_id]
attention_mask = [1] * len(encoder_input_ids)
decoder_input_ids = [res_id] + hyp_ids
decoder_attention_mask = [1] * len(decoder_input_ids)
if obj['label'] == 'positive':
positive_set["encoder_input_ids"].append(encoder_input_ids)
positive_set["decoder_input_ids"].append(decoder_input_ids)
positive_set["attention_mask"].append(attention_mask)
positive_set["decoder_attention_mask"].append(decoder_attention_mask)
decoder_lmlabel = hyp_ids + [eos_id]
positive_set["lmlabels"].append(decoder_lmlabel)
if smalldataset:
positive_set["encoder_input_ids"] = positive_set["encoder_input_ids"][:32]
positive_set["lmlabels"] = positive_set["lmlabels"][:32]
positive_set["attention_mask"] = positive_set["attention_mask"][:32]
positive_set["decoder_attention_mask"] = positive_set["decoder_attention_mask"][:32]
positive_set["decoder_input_ids"] = positive_set["decoder_input_ids"][:32]
print("used 32 pairs of datasets infer\n")
for item_name, item in positive_set.items():
if item_name == "encoder_input_ids":
item = pad_sequence([torch.from_numpy(np.array(x)) for x in item],
batch_first=True, padding_value=pad_id)
positive_set[item_name] = item
elif item_name == "lmlabels":
item = pad_sequence([torch.from_numpy(np.array(x)) for x in item],
batch_first=True, padding_value=-100)
positive_set[item_name] = item
elif item_name == "attention_mask" or item_name == "decoder_attention_mask":
item = pad_sequence([torch.from_numpy(np.array(x)) for x in item],
batch_first=True, padding_value=0)
positive_set[item_name] = item
elif item_name == "decoder_input_ids":
item = pad_sequence([torch.from_numpy(np.array(x)) for x in item],
batch_first=True, padding_value=pad_id)
positive_set[item_name] = item
return positive_set