-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.py
408 lines (321 loc) · 16.9 KB
/
data.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
from datasets import load_dataset
import random
import torch
import numpy as np
from typing import List
import logging
from transformers import RobertaTokenizer, RobertaModel
from tqdm import tqdm
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import pairwise
from transformers import GPT2Tokenizer, GPT2Model
logging.basicConfig(level = logging.INFO)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class SST2Processor():
def __init__(self, k, seed, dataset, tokenizer, kate_metric,reversedCosi , encoder_kate, use_calibration, ensemble):
self.dataset_name = dataset
self.tokenizer = tokenizer
self.seed = seed
self.k = k
dataset1 = load_dataset(self.dataset_name)
self.train_split = dataset1["train"]
self.test_split = dataset1["test"]
#self.val_split = dataset1["validation"]
self.kate_metric = kate_metric
self.reversed = reversedCosi
self.encoder_kate = encoder_kate
self.use_calibration = use_calibration
self.ensemble = ensemble
self.train_id = random.sample(range(len(self.train_split)), k=self.k)
# self.template = template
# self.tmp_idx = tmp_idx
#self.mode = mode
def generate_setOfDemon(self,template, group_id_kate = []):
label_words = ["terrible", "great"]
demonstrations = []
train_id = self.train_id if len(group_id_kate) == 0 else group_id_kate
#logging.info(f"{train_id}")
few_train = [self.train_split[i] for i in train_id]
#logging.info("few_train = {}".format(len(few_train)))
for key in few_train:
text = key['text'].strip()
label = int(key['label'])
if text[-1] != ".":
text = text + " ."
tokens_input = self.tokenizer(text)["input_ids"]
tokens_label = self.tokenizer(" " + (template % label_words[label]))["input_ids"]
demonstrations = demonstrations + tokens_input + tokens_label
#print("demonstrations = ",self.tokenizer.decode(demonstrations))
#demonstrations_t = demonstrations_t+ text+ " " + (template % label_words[label])
return demonstrations
def generate_setOfDemon_channel(self,template , group_id_kate = []):
label_words = ["terrible", "great"]
demonstrations = []
train_id = self.train_id if len(group_id_kate) == 0 else group_id_kate
#logging.info(f"{train_id}")
few_train = [self.train_split[i] for i in train_id]
logging.info("few_train = {}".format(few_train))
for key in few_train:
text = key['text'].strip()
label = int(key['label'])
if text[-1] != ".":
text = text + " ."
p = (template % label_words[label])
if len(demonstrations)>0:
p = " " + p
tokens_input = self.tokenizer(text)["input_ids"]
tokens_label = self.tokenizer(p)["input_ids"]
demonstrations = demonstrations + tokens_label + tokens_input
#demonstrations_t = demonstrations_t+ text+ " " + (template % label_words[label])
return demonstrations
def get_prompts(self , few_train,test_data):
label_words = ["terrible", "great"]
#print(few_train)
demonstrations = []
demonstrations_t = ""
for key in few_train:
text = key['text'].strip()
label = int(key['label'])
# if len(demonstrations)>0:
# text = " " + text
tokens_input = self.tokenizer(text)["input_ids"]
tokens_label = self.tokenizer(" " + (self.template % label_words[label]))["input_ids"]
demonstrations = demonstrations + tokens_input + tokens_label
demonstrations_t = demonstrations_t+ text+ " " + (self.template % label_words[label])
#test_inputs = [self.tokenizer(sent['text'].strip())["input_ids"] for sent in test_data]
# data = []
# for key in test_data:
# text = key['text'].strip()
# label = int(key['label'])
# data.append((text, label))
# print(demonstrations)
# print(demonstrations_t)
# print(test_inputs[0])
return demonstrations
def generate_datasets2212(self):
assert self.k < 8
logging.info(f"generating datasets using seed = {self.seed}, k = {self.k} , Dataset = {self.dataset_name}")
dataset1 = load_dataset(self.dataset_name)
train_split = dataset1["train"]
test_split = dataset1["test"]
val_split = dataset1["validation"]
logging.info("train_split = {} test_split = {} val_split = {}".format(len(train_split),len(test_split),len(val_split)))
train_id = [10,55,415,45]#random.sample(range(len(train_split)), k=self.k)
logging.info(f"{train_id}")
# test_id = random.sample(range(len(test_split)), k=self.k)
# logging.info(f"{test_id}")
few_train = [train_split[i] for i in train_id]
logging.info("few_train = {}".format(len(few_train)))
# few_test = [test_split[i] for i in test_id]
# logging.info("few_test = {}".format(len(few_test)))
demonstrations = self.get_prompts(few_train,test_split)
return demonstrations
def generate_test_set(self):
#assert self.mode == "Test"
data = []
data_token = []
data_token_with_space = []
#dataset1 = load_dataset(self.dataset_name)
#test_split = dataset1["test"]
#j = 0
#[self.tokenizer(sent['text'].strip())["input_ids"] for sent in test_data]
for key in self.test_split:
text = key['text'].strip()
label = int(key['label'])
data.append((text, label))
data_token.append(self.tokenizer(text)["input_ids"])
data_token_with_space.append(self.tokenizer(" ",text)["input_ids"])
# j = j+1
# if j >6:
# break
return data , data_token , data_token_with_space
# https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks
def chunks(self, lst, n):
"""Yield successive n-sized chunks from lst."""
# for i in range(0, len(lst), n):
# yield lst[i:i + n]
return [lst[i:i + n] for i in range(0, len(lst), n)]
def decode(self, tok, model, corpus ):
embeddings = []
for corpus_tmp in tqdm(self.chunks(corpus, 128)):
encoding = tok.batch_encode_plus(corpus_tmp, padding=True, truncation=True)
sentence_batch, attn_mask = encoding["input_ids"], encoding["attention_mask"]
sentence_batch, attn_mask = torch.LongTensor(sentence_batch).to(device), torch.LongTensor(attn_mask).to(device)
with torch.no_grad():
embedding_output_batch = model(sentence_batch, attn_mask)
sentence_embeddings = embedding_output_batch[0][:, 0, :]
embeddings.append(sentence_embeddings.detach().cpu().numpy())
return np.concatenate(embeddings, axis=0)
def kate_process(self):
#corpus = dev_corpus + train_corpus
tok = RobertaTokenizer.from_pretrained(self.encoder_kate)
model = RobertaModel.from_pretrained(self.encoder_kate)
logging.info("Start Encoder : {}".format(self.encoder_kate))
test_text = []
test_label = []
c = 0
for key in self.test_split:
text = key['text'].strip()
label = int(key['label'])
test_text.append(text)
test_label.append(label)
c =c + 1
# if c > 200:
# break
print("len test_split = " , c)
train_text = []
train_label = []
c = 0
for key in self.train_split:
text = key['text'].strip()
label = int(key['label'])
train_text.append(text)
train_label.append(label)
c =c + 1
# if c > 200:
# break
#print("len train_split = " , c)
train_indices = list(range(len(train_text)))
corpus = test_text + train_text
n_dev = len(test_label)
n_train = len(train_text)
model.to(device)
X = self.decode(tok, model, corpus)
emb_train = X[n_dev:]
emb_dev = X[:n_dev]
logging.info("n_dev = {} n_train = {} all corpus = {}".format(n_dev,n_train,len(corpus)))
#print("emb_train = ", emb_train)
#print("emb_train len= ", len(emb_train))
if self.kate_metric == "euclidean":
logging.info("Start NearestNeighbors...")
nbrs = NearestNeighbors(n_neighbors=self.k, algorithm='ball_tree', n_jobs=-1).fit(emb_train)
distances, indices = nbrs.kneighbors(emb_dev)
elif self.kate_metric == "cosine":
logging.info("Start cosine_similarity...")
dist_matrix = pairwise.cosine_similarity(X=emb_dev, Y=emb_train)
if self.reversed:
values, indices = torch.topk(-torch.from_numpy(dist_matrix), k=self.k, dim=-1)
else:
values, indices = torch.topk(torch.from_numpy(dist_matrix), k=self.k, dim=-1)
indices = indices.numpy()
train_indices_np = np.asarray(train_indices)
#print("train_indices_np = ",train_indices_np)
kNN_dev_train = [train_indices_np[indices[i]].reshape(1, -1) for i in range(len(indices))]
#print("kNN_dev_train = ",kNN_dev_train)
kNN_dev_train = np.concatenate(kNN_dev_train, axis=0).tolist()
#print("kNN_dev_train = ",kNN_dev_train)
#print("kNN_dev_train = ",kNN_dev_train)
#prompt = [demonstrations.copy() + test_input + prefix[:tmp_idx] for test_input in test_inputs_token]
return kNN_dev_train
def kate_generate_promt(self, group_id_kate , test_inputs_token , prefix , template):
prompt = []
prompt_calibration = []
na_token = self.tokenizer("N/A")["input_ids"]
label_words = ["terrible", "great"]
for test_input, group_id in zip(test_inputs_token, group_id_kate):
#print("group_id = ",group_id)
if self.ensemble:
for g_id in group_id:
#prompt1 = demonstrations.copy() + test_input + prefix
few_train = self.train_split[g_id]
text = few_train['text'].strip()
label = int(few_train['label'])
if text[-1] != ".":
text = text + " ."
tokens_input = self.tokenizer(text)["input_ids"]
tokens_label = self.tokenizer(" " + (template % label_words[label]))["input_ids"]
prompt1 = tokens_input + tokens_label + test_input + prefix
prompt2 = tokens_input + tokens_label + na_token + prefix
prompt.append(prompt1)
prompt_calibration.append(prompt2)
else:
demonstrations = self.generate_setOfDemon(template , group_id)
prompt1 = demonstrations.copy() + test_input + prefix
prompt2 = demonstrations.copy() + na_token + prefix
prompt.append(prompt1)
prompt_calibration.append(prompt2)
return prompt , prompt_calibration
def ensemble_generate_promt(self, test_inputs_token , prefix , template, group_id_kate = []):
prompt = []
prompt_calibration = []
na_token = self.tokenizer("N/A")["input_ids"]
label_words = ["terrible", "great"]
#print(group_id_kate)
group_id_kate = group_id_kate if len(group_id_kate) != 0 else [self.train_id]*len(test_inputs_token)
print(len(test_inputs_token))
print(len(group_id_kate))
assert len(test_inputs_token) == len(group_id_kate)
if self.ensemble:
for test_input, group_id in zip(test_inputs_token, group_id_kate):
for g_id in group_id:
few_train = self.train_split[g_id]
text = few_train['text'].strip()
label = int(few_train['label'])
if text[-1] != ".":
text = text + " ."
tokens_input = self.tokenizer(text)["input_ids"]
tokens_label = self.tokenizer(" " + (template % label_words[label]))["input_ids"]
prompt1 = tokens_input + tokens_label + test_input + prefix
prompt2 = tokens_input + tokens_label + na_token + prefix
#print("prompt1 = ",self.tokenizer.decode(prompt1))
#print("prompt2 = ",self.tokenizer.decode(prompt2))
prompt.append(prompt1)
prompt_calibration.append(prompt2)
return prompt , prompt_calibration
def kate_generate_promt_channel(self, data_token_with_space , prefix , template, group_id_kate = []):
#prompt = [demonstrations.copy() + prefix for test_input in data_token_with_space]
prompt = []
label_ensemble = []
label_words = ["terrible", "great"]
group_id_kate = group_id_kate if len(group_id_kate) != 0 else [self.train_id]*len(data_token_with_space)
# print("group_id_kate = ",group_id_kate)
# print("data_token_with_space = ",data_token_with_space)
assert len(group_id_kate) == len(data_token_with_space)
if self.ensemble:
for test_input, group_id in zip(data_token_with_space, group_id_kate):
for g_id in group_id:
#for g_id in group_id:
few_train = self.train_split[g_id]
text = few_train['text'].strip()
label = int(few_train['label'])
if text[-1] != ".":
text = text + " ."
p = (template % label_words[label])
tokens_input = self.tokenizer(text)["input_ids"]
tokens_label = self.tokenizer(p)["input_ids"]
prompt1 = tokens_label + tokens_input + prefix
#print("prompt1 = ",self.tokenizer.decode(prompt1))
#print("label_ensemble = ",self.tokenizer.decode(test_input))
prompt.append(prompt1)
label_ensemble.append(test_input)
assert (len(self.test_split) * self.k ) == len(prompt) and (len(self.test_split) * self.k ) == len(label_ensemble)
else:
for test_input, group_id in zip(data_token_with_space, group_id_kate):
demonstrations = self.generate_setOfDemon_channel(template , group_id)
prompt1 = demonstrations.copy() + prefix
prompt.append(prompt1)
label_ensemble.append(test_input)
# else:
# for test_input, group_id in zip(data_token_with_space, group_id_kate):
# demonstrations = self.generate_setOfDemon_channel(template , group_id)
# prompt1 = demonstrations.copy() + prefix
# for test_input, group_id in zip(data_token_with_space, group_id_kate):
# print("group_id = ",group_id)
# if self.ensemble:
# for g_id in group_id:
# few_train = self.train_split[g_id]
# text = few_train['text'].strip()
# label = int(few_train['label'])
# if text[-1] != ".":
# text = text + " ."
# p = (template % label_words[label])
# tokens_input = self.tokenizer(text)["input_ids"]
# tokens_label = self.tokenizer(p)["input_ids"]
# prompt1 = tokens_label + tokens_input + prefix
# prompt.append(prompt1)
# label_ensemble.append(test_input)
# else:
# demonstrations = self.generate_setOfDemon_channel(template , group_id)
# prompt1 = demonstrations.copy() + prefix
#prompt.append(prompt1)
return prompt , label_ensemble