forked from ZonglinY/ECBRF_Case_Based_Reasoning_with_PLM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
comet-atomic-index-builder-v6-twoEmbedder-DPR-faster-May-TST.py
2426 lines (2283 loc) · 145 KB
/
comet-atomic-index-builder-v6-twoEmbedder-DPR-faster-May-TST.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse, logging, os, sys, random, datetime, math
os.environ["CUDA_VISIBLE_DEVICES"]="3"
import numpy as np
import torch
import math
import time
import random
import copy
import pickle
sys.path.insert(0, "..")
# from transformers import (CONFIG_NAME, WEIGHTS_NAME, AdamW,
# get_linear_schedule_with_warmup, cached_path)
# from transformers import (BertModel, BertTokenizer, BertConfig)
from transformers import (DPRQuestionEncoder, DPRContextEncoder,
DPRQuestionEncoderTokenizer, DPRContextEncoderTokenizer)
from torch.utils.data import (DataLoader, SequentialSampler,
TensorDataset)
# from tqdm import tqdm
# import torch.nn.functional as F
from utils_TST import (save_model, tokenize_and_encode,
set_seed, load_data_atomic, find_path_tensor_dataset,
find_path_sample_ckb_dict, get_k_for_topk_subRel,
get_selected_idxs_and_prob_from_double_topk_result,
get_id_for_id_with_different_source_during_larger_range,
add_special_tokens)
logging.basicConfig(format = "%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt = "%m/%d/%Y %H:%M:%S",
level = logging.INFO)
logger = logging.getLogger(__name__)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# retr_input_ids, retr_attention_mask, retr_segment_ids = batch
def batch_get_embed(model, model_type, batch):
batch = tuple(t.to(device) for t in batch)
retr_input_ids, retr_attention_mask, retr_segment_ids = batch
if model_type =='dpr':
outputs = model(retr_input_ids, attention_mask=retr_attention_mask, token_type_ids=retr_segment_ids)
# # final_hid_embed: [batch_size, (max)512, 768]
# final_hid_embed = outputs[0]
# # pooled_embedding: [batch_size, 768]
# pooled_embedding = final_hid_embed[:, 0, :]
# # pooled_embedding: [batch_size, 768]
# pooled_embedding = outputs[1]
# pooled_embedding: [32, 768], verified
pooled_embedding = outputs[0]
# print('pooled_embedding.size(): ', pooled_embedding.size())
else:
raise Exception
return pooled_embedding
# input:
# sample_size_each_rel: minimum size of sampled case for each rel
# sample_size_total: size of sampled case knowledge base
# num_cases: number of cases for each obj_emb to retrieve
# simi_batch_size: batch size used for calculate similarity during finding cases
# num_steps: number of steps during training to build cases in advance
class embedding_builder:
def __init__(self, args, model_type, num_cases=15, n_doc=3, simi_batch_size=64, sample_size_each_rel=100, sample_size_total=20000, num_steps=500, data_type='train'):
self.args = args
self.num_cases = num_cases
self.n_doc = n_doc
self.simi_batch_size = simi_batch_size
self.sample_size_each_rel = sample_size_each_rel
self.sample_size_total = sample_size_total
self.num_steps = num_steps
self.data_type = data_type
# self.path_sample_ckb_dict = path_sample_ckb_dict
self.initialize_paths_variables(args.output_dir)
self.check_input_variables()
# train_lines should be sorted with rel
if args.dataset_selection == 0:
self.get_ori_text_conceptnet()
elif args.dataset_selection == 1:
self.get_ori_text_atomic()
elif args.dataset_selection == 2:
self.get_ori_text_shakespeare()
elif args.dataset_selection == 3:
self.get_ori_text_e2e()
elif args.dataset_selection == 4 or args.dataset_selection == 5 or args.dataset_selection == 6 or args.dataset_selection == 7:
self.get_ori_text_sentiment()
self.tensor_datasets = self.wait_and_get_tensor_datasets()
# self.get_data_loader()
# self.train_tensor_dataset, self.eval_tensor_dataset, self.test_tensor_dataset = self.tensor_datasets[0], self.tensor_datasets[1], self.tensor_datasets[2]
self.train_tensor_dataset = self.tensor_datasets[0]
if self.args.if_double_retrieval:
self.model, self.model_doc, self.tokenizer_retriever_doc = self.initialize_model(model_type)
print("self.tokenizer_retriever_doc has been initialized")
else:
self.model, self.model_doc = self.initialize_model(model_type)
def check_input_variables(self):
assert self.num_cases % self.n_doc == 0
# Eval need to use this path to load sample_ckb_dict
assert self.path_sample_ckb_dict != None
def initialize_paths_variables(self, output_dir):
# will get it during the inference
self.n_shot = None
# data dir
self.train_data_dir = self.args.train_dataset[0]
self.val1_data_dir = self.args.eval_dataset[0]
self.test_data_dir = self.args.test_dataset[0]
# full embedding; used for evaluation
self.full_train_emb_dir = os.path.join(output_dir, 'full_train_embedding.pt')
self.full_val_emb_dir = os.path.join(output_dir, 'full_val_embedding.pt')
self.full_test_emb_dir = os.path.join(output_dir, 'full_test_embedding.pt')
# full cases; used for evaluation
self.full_train_cases_dir = os.path.join(output_dir, 'full_train_cases.txt')
self.full_val_cases_dir = os.path.join(output_dir, 'full_val_cases.txt')
self.full_test_cases_dir = os.path.join(output_dir, 'full_test_cases.txt')
# sample embedding
self.sample_CKB_train_embed_dir = os.path.join(output_dir, 'sample_CKB_train_embedding.pt')
self.batch_train_embed_dir = os.path.join(output_dir, 'batch_train_embed.pt')
# Q: not used yet
self.batch_eval_embed_dir = os.path.join(output_dir, 'batch_eval_embed.pt')
# Q: not used yet
self.batch_test_embed_dir = os.path.join(output_dir, 'batch_test_embed.pt')
self.bundle_train_cases_dir = os.path.join(output_dir, 'bundle_train_cases.pt')
self.bundle_eval_cases_dir = os.path.join(output_dir, 'bundle_eval_cases.pt')
self.bundle_test_cases_dir = os.path.join(output_dir, 'bundle_test_cases.pt')
# for debug
self.batch_rel_dir = os.path.join(output_dir, 'batch_rel.pt')
# to interact with generator
self.path_tensor_datasets = find_path_tensor_dataset(self.args)
print("INFO: path_tensor_datasets: ", self.path_tensor_datasets)
# 'next_bundle_train' is used in self.wait_get_remove_bundle
self.path_next_bundle = os.path.join(self.args.output_dir, 'next_bundle_train.pt')
# 'next_bundle_eval' and 'next_bundle_test' are used in self.wait_get_remove_bundle_eval
self.path_next_bundle_eval = os.path.join(self.args.output_dir, 'next_bundle_eval.pt')
self.path_next_bundle_test = os.path.join(self.args.output_dir, 'next_bundle_test.pt')
self.path_model_retriever = os.path.join(self.args.output_dir, 'retriever.pt')
self.path_model_retriever_eval = os.path.join(self.args.output_dir, 'retriever_eval.pt')
self.path_model_retriever_test = os.path.join(self.args.output_dir, 'retriever_test.pt')
self.path_retriever_doc = os.path.join(self.args.output_dir, 'retriever_doc.pt')
self.path_retriever_doc_eval = os.path.join(self.args.output_dir, 'retriever_doc_eval.pt')
self.path_retriever_doc_test = os.path.join(self.args.output_dir, 'retriever_doc_test.pt')
self.path_retrieved_encoded_cases = os.path.join(self.args.output_dir, 'encoded_cases_train.pt')
self.path_retrieved_encoded_cases_eval = os.path.join(self.args.output_dir, 'encoded_cases_eval.pt')
self.path_retrieved_encoded_cases_test = os.path.join(self.args.output_dir, 'encoded_cases_test.pt')
# signal from generator that indicates whether it's eval or test mode
self.path_signal_file_if_eval = os.path.join(self.args.output_dir, 'under_evaluation.pt')
self.path_signal_file_if_test = os.path.join(self.args.output_dir, 'under_evaluation_test.pt')
# path to save ttl_similar_cases during eval or test time
self.path_ttl_similar_cases_eval = os.path.join(self.args.output_dir, 'ttl_similar_cases_eval.txt')
# change the name for a different sample (to differentiate different ttl_similar_cases for different sample)
if self.args.num_sample != 1:
self.path_ttl_similar_cases_eval = self.path_ttl_similar_cases_eval.split('.')
assert len(self.path_ttl_similar_cases_eval) == 2
self.path_ttl_similar_cases_eval[0] += '_sample' + str(self.args.num_sample)
self.path_ttl_similar_cases_eval = '.'.join(self.path_ttl_similar_cases_eval)
# Should be different
if self.args.if_use_full_memory_store_while_subset:
self.path_ttl_similar_cases_test = os.path.join(self.args.output_dir, 'ttl_similar_cases_test_fullMS.txt')
else:
self.path_ttl_similar_cases_test = os.path.join(self.args.output_dir, 'ttl_similar_cases_test.txt')
# change the name for a different sample (to differentiate different ttl_similar_cases for different sample)
if self.args.num_sample != 1:
self.path_ttl_similar_cases_test = self.path_ttl_similar_cases_test.split('.')
assert len(self.path_ttl_similar_cases_test) == 2
self.path_ttl_similar_cases_test[0] += '_sample' + str(self.args.num_sample)
self.path_ttl_similar_cases_test = '.'.join(self.path_ttl_similar_cases_test)
self.path_if_no_need_for_retrieval = os.path.join(self.args.output_dir, 'finished-no_need_for_retrieval.pt')
# to store ttl_similar_cases
self.ttl_similar_cases_eval, self.ttl_similar_cases_test = [], []
# when using frozen retriever or comet baseline, sample_ckb_dict is fixed
self.sample_ckb_dict = None
# num_cases_tmp = np.minimum(num_cases*self.times_more_num_cases_to_retrieve+1, similarity.size()[1])
# rlt_topk = torch.topk(similarity, num_cases_tmp)
if self.args.rerank_selection == 0:
self.times_more_num_cases_to_retrieve = 1
elif self.args.rerank_selection == 1 or self.args.rerank_selection == 2:
if self.n_doc >= 3:
self.times_more_num_cases_to_retrieve = 3
else:
self.times_more_num_cases_to_retrieve = 10
# Conceptnet needs more times_more_num_cases_to_retrieve, since the number of cases
# that with the same sub and rel can be large
if self.args.dataset_selection == 0:
self.times_more_num_cases_to_retrieve *= 24
elif self.args.dataset_selection == 3:
self.times_more_num_cases_to_retrieve *= 2
elif self.args.dataset_selection == 5:
self.times_more_num_cases_to_retrieve *= 36
elif self.args.dataset_selection == 6:
self.times_more_num_cases_to_retrieve *= 10
if self.args.use_only_sub_rel_for_retrieval:
self.times_more_num_cases_to_retrieve *= 3
# newly added 2023/03/14; since with less num_cases, times_more_num_cases_to_retrieve might not be enough
if self.args.num_cases < 3:
self.times_more_num_cases_to_retrieve = int(self.times_more_num_cases_to_retrieve * 3 / self.args.num_cases)
else:
raise Exception('Invalid rerank_selection')
# cnt_next_bundle: the number of current next_bundle to retrieve
# (this number is used by both train/eval/test mode)
self.cnt_next_bundle = None
# path_sample_ckb_dict is not influenced by args.use_obj_for_retrieval
self.path_sample_ckb_dict = find_path_sample_ckb_dict(self.args)
if self.args.if_double_retrieval:
self.path_sample_ckb_dict_subRel = find_path_sample_ckb_dict(self.args, use_only_sub_rel_for_retrieval=True)
# Add tokenizer_gene
def initialize_model(self, model_type='dpr'):
# currently only support bert
assert model_type == 'dpr'
# print("INFO: tokenizer_gene uses GPT2Tokenizer to initialize")
# tokenizer_gene = GPT2Tokenizer.from_pretrained('gpt2')
if self.args.if_double_retrieval:
# tokenizer_retriever = DPRQuestionEncoderTokenizer.from_pretrained('facebook/dpr-question_encoder-single-nq-base')
tokenizer_retriever_doc = DPRContextEncoderTokenizer.from_pretrained('facebook/dpr-ctx_encoder-single-nq-base')
# tokenizer_retriever = add_special_tokens(self.args, tokenizer_retriever)
tokenizer_retriever_doc = add_special_tokens(self.args, tokenizer_retriever_doc)
model = DPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base')
model_doc = DPRContextEncoder.from_pretrained('facebook/dpr-ctx_encoder-single-nq-base')
# model.resize_token_embeddings(len(tokenizer_retriever))
model.to(device)
# model_doc.resize_token_embeddings(len(tokenizer_retriever_doc))
model_doc.to(device)
if self.args.if_double_retrieval:
return model, model_doc, tokenizer_retriever_doc
else:
return model, model_doc
def wait_and_get_tensor_datasets(self):
# if_longer_wait_time: if self.path_tensor_datasets is just created; give it more time to create a complete file
if_longer_wait_time = False
while not os.path.exists(self.path_tensor_datasets):
time.sleep(5)
if_longer_wait_time = True
# do not need to remove since it won't be changed during experiment
if if_longer_wait_time:
time.sleep(10)
while True:
try:
tensor_datasets = torch.load(self.path_tensor_datasets)
break
except:
time.sleep(5)
print('Loaded tensor_datasets Successfully.')
return tensor_datasets
# get self.next_bundle
def wait_get_remove_bundle(self):
print('Waiting for next_bundle...')
start_waiting_time = time.time()
# while(not os.path.exists(RFself.path_next_bundle)):
while True:
if os.path.exists(self.path_signal_file_if_eval):
print("Begin evaluating in validation set...")
self.evaluation_mode('eval')
assert not os.path.exists(self.path_signal_file_if_eval)
elif os.path.exists(self.path_signal_file_if_test):
print("Begin evaluating in test set...")
self.evaluation_mode('test')
assert not os.path.exists(self.path_signal_file_if_test)
elif os.path.exists(self.path_if_no_need_for_retrieval):
# if continue
return False
else:
possible_other_next_bundle_files = \
[i for i in os.listdir(self.args.output_dir) if i.startswith('next_bundle_train')]
if len(possible_other_next_bundle_files) > 0:
assert len(possible_other_next_bundle_files) == 1
# to get self.cnt_next_bundle
self.cnt_next_bundle = int(possible_other_next_bundle_files[0].split('.')[0].replace('next_bundle_train_', ''))
# to get the exact path_next_bundle
path_next_bundle = os.path.join(self.args.output_dir, possible_other_next_bundle_files[0])
break
else:
time.sleep(5)
print('--- Waiting for next_bundle: %s ---' % (time.time() - start_waiting_time))
time.sleep(5)
while True:
try:
self.next_bundle = torch.load(path_next_bundle)
break
except:
time.sleep(5)
os.remove(path_next_bundle)
assert not os.path.exists(path_next_bundle)
# print('Loaded and deleted next_bundle successfully!')
# if continue
return True
# both model_retriever and model_retriever_doc
def load_remove_retriever(self, data_type='train'):
if data_type == 'train':
path_retriever = self.path_model_retriever
path_retriever_doc = self.path_retriever_doc
elif data_type == 'eval':
path_retriever = self.path_model_retriever_eval
path_retriever_doc = self.path_retriever_doc_eval
elif data_type == 'test':
path_retriever = self.path_model_retriever_test
path_retriever_doc = self.path_retriever_doc_test
else:
raise Exception("Wrong data_type: ", data_type)
# should be saved within 15 sec
starting_wait_time = time.time()
while not os.path.exists(path_retriever) or not os.path.exists(path_retriever_doc):
print('Warning: waiting for model_retriever or path_retriever_doc')
time.sleep(5)
waiting_time_for_retriever = time.time() - starting_wait_time
if waiting_time_for_retriever > 20:
print('Warning: waiting_time_for_retriever > 20s')
# Q: should we check whether loaded retriever has added special tokens?
# model_retriever
time.sleep(5)
self.model.load_state_dict(torch.load(path_retriever, map_location='cuda:0'))
# model_retriever_doc
self.model_doc.load_state_dict(torch.load(path_retriever_doc, map_location='cuda:0'))
self.model.eval()
self.model_doc.eval()
os.remove(path_retriever)
os.remove(path_retriever_doc)
assert not os.path.exists(path_retriever)
assert not os.path.exists(path_retriever_doc)
# print('Loaded and deleted path_retriever successfully!')
# get_sampled_ckb_data_loader accoring to sample_ids
# sample_ids: a tensor contains sampled ids
def get_sampled_ckb_data_loader(self, sample_ids):
# Q: need to extend for eval and test
# SQ: seems do not need extension
assert self.data_type == 'train'
sampled_train_tensor_dataset = [d[sample_ids] for d in self.train_tensor_dataset]
train_data = TensorDataset(*sampled_train_tensor_dataset)
assert len(train_data) == len(sample_ids)
train_sampler = SequentialSampler(train_data)
sample_train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=self.args.train_batch_size)
return sample_train_dataloader
def get_ori_text_atomic(self):
# eval_size: 1000 means using "None" tuple data; 900 means not using
# test_size: 87481 means using "None" tuple data; 72872 means not using
if self.args.if_without_none:
eval_size = 900
test_size = 72872
else:
eval_size = 1000
test_size = 87481
if self.args.subset_selection == -1:
# if self.args.if_without_none == True, the returned lines should not contain "None"
# [('PersonX plays a ___ in the war', '<oReact>', 'none'), (), ...]
self.train_lines, self.cat_len_noter_train = load_data_atomic(self.train_data_dir, self.args.if_without_none)
self.val_lines, self.cat_len_noter_val = load_data_atomic(self.val1_data_dir, self.args.if_without_none)
self.test_lines, self.cat_len_noter_test = load_data_atomic(self.test_data_dir, self.args.if_without_none)
else:
# Q:
data_dir = "./Data/atomic/"
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection)+'_lines' + self.args.additional_sampling_method_name + self.args.additional_sample_name), 'rb') as f:
self.train_lines = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(eval_size)+'_lines'), 'rb') as f:
self.val_lines = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(test_size)+'_lines'), 'rb') as f:
self.test_lines = pickle.load(f)
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection)+'_cat_len_noter' + self.args.additional_sampling_method_name + self.args.additional_sample_name), 'rb') as f:
self.cat_len_noter_train = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(eval_size)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_val = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(test_size)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_test = pickle.load(f)
if self.args.if_use_full_memory_store_while_subset:
data_dir = "./Data/atomic/"
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection_while_use_full_memory_store)+'_lines' + self.args.additional_sampling_method_name + self.args.additional_sample_name), 'rb') as f:
self.train_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(eval_size)+'_lines'), 'rb') as f:
self.val_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(test_size)+'_lines'), 'rb') as f:
self.test_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection_while_use_full_memory_store)+'_cat_len_noter' + self.args.additional_sampling_method_name + self.args.additional_sample_name), 'rb') as f:
self.cat_len_noter_subset_train = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(eval_size)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_subset_val = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(test_size)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_subset_test = pickle.load(f)
def get_cat_len_noter_conceptnet(self, lines):
cat_len_noter = []
prev_rel, cur_rel = None, None
for id, line in enumerate(lines):
cur_rel = line.split('\t')[0]
if cur_rel != prev_rel and prev_rel != None:
cat_len_noter.append(id-1)
prev_rel = cur_rel
cat_len_noter.append(id)
return cat_len_noter
# train_lines/val_lines/test_lines must be sorted
def get_ori_text_conceptnet(self):
if self.args.subset_selection == -1:
with open(self.train_data_dir, 'r') as f:
self.train_lines = f.readlines()
self.cat_len_noter_train = self.get_cat_len_noter_conceptnet(self.train_lines)
print('cat_len_noter_train: ', self.cat_len_noter_train)
print('len(cat_len_noter_train): ', len(self.cat_len_noter_train))
with open(self.val1_data_dir, 'r') as f:
self.val_lines = f.readlines()
self.cat_len_noter_val = self.get_cat_len_noter_conceptnet(self.val_lines)
print('cat_len_noter_val: ', self.cat_len_noter_val)
print('len(cat_len_noter_val): ', len(self.cat_len_noter_val))
with open(self.test_data_dir, 'r') as f:
self.test_lines = f.readlines()
self.cat_len_noter_test = self.get_cat_len_noter_conceptnet(self.test_lines)
print('cat_len_noter_test: ', self.cat_len_noter_test)
print('len(cat_len_noter_test): ', len(self.cat_len_noter_test))
else:
data_dir = "./Data/conceptnet/"
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection)+'_lines' + self.args.additional_sampling_method_name + self.args.additional_sample_name), 'rb') as f:
self.train_lines = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(600)+'_lines'), 'rb') as f:
self.val_lines = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(1200)+'_lines'), 'rb') as f:
self.test_lines = pickle.load(f)
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection)+'_cat_len_noter' + self.args.additional_sampling_method_name + self.args.additional_sample_name), 'rb') as f:
self.cat_len_noter_train = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(600)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_val = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(1200)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_test = pickle.load(f)
if self.args.if_use_full_memory_store_while_subset:
data_dir = "./Data/conceptnet/"
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection_while_use_full_memory_store)+'_lines' + self.args.additional_sampling_method_name + self.args.additional_sample_name), 'rb') as f:
self.train_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(600)+'_lines'), 'rb') as f:
self.val_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(1200)+'_lines'), 'rb') as f:
self.test_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection_while_use_full_memory_store)+'_cat_len_noter' + self.args.additional_sampling_method_name + self.args.additional_sample_name), 'rb') as f:
self.cat_len_noter_subset_train = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(600)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_subset_val = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(1200)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_subset_test = pickle.load(f)
def get_ori_text_shakespeare(self):
if self.args.subset_selection == -1:
while not os.path.exists(self.train_data_dir):
time.sleep(5)
with open(self.train_data_dir, 'r') as f:
self.train_lines = f.readlines()
self.cat_len_noter_train = self.get_cat_len_noter_conceptnet(self.train_lines)
print('cat_len_noter_train: ', self.cat_len_noter_train)
print('len(cat_len_noter_train): ', len(self.cat_len_noter_train))
with open(self.val1_data_dir, 'r') as f:
self.val_lines = f.readlines()
self.cat_len_noter_val = self.get_cat_len_noter_conceptnet(self.val_lines)
print('cat_len_noter_val: ', self.cat_len_noter_val)
print('len(cat_len_noter_val): ', len(self.cat_len_noter_val))
with open(self.test_data_dir, 'r') as f:
self.test_lines = f.readlines()
self.cat_len_noter_test = self.get_cat_len_noter_conceptnet(self.test_lines)
print('cat_len_noter_test: ', self.cat_len_noter_test)
print('len(cat_len_noter_test): ', len(self.cat_len_noter_test))
else:
data_dir = "./Data/shakes/"
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection)+'_lines' + self.args.additional_sample_name), 'rb') as f:
self.train_lines = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(1179)+'_lines'), 'rb') as f:
self.val_lines = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(1411)+'_lines'), 'rb') as f:
self.test_lines = pickle.load(f)
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection)+'_cat_len_noter' + self.args.additional_sample_name), 'rb') as f:
self.cat_len_noter_train = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(1179)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_val = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(1411)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_test = pickle.load(f)
if self.args.if_use_full_memory_store_while_subset:
data_dir = "./Data/shakes/"
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection_while_use_full_memory_store)+'_lines' + self.args.additional_sample_name), 'rb') as f:
self.train_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(1179)+'_lines'), 'rb') as f:
self.val_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(1411)+'_lines'), 'rb') as f:
self.test_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection_while_use_full_memory_store)+'_cat_len_noter' + self.args.additional_sample_name), 'rb') as f:
self.cat_len_noter_subset_train = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(1179)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_subset_val = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(1411)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_subset_test = pickle.load(f)
def get_ori_text_e2e(self):
if self.args.subset_selection == -1:
while not os.path.exists(self.train_data_dir):
time.sleep(5)
with open(self.train_data_dir, 'r') as f:
self.train_lines = f.readlines()
self.cat_len_noter_train = self.get_cat_len_noter_conceptnet(self.train_lines)
print('cat_len_noter_train: ', self.cat_len_noter_train)
print('len(cat_len_noter_train): ', len(self.cat_len_noter_train))
with open(self.val1_data_dir, 'r') as f:
self.val_lines = f.readlines()
self.cat_len_noter_val = self.get_cat_len_noter_conceptnet(self.val_lines)
print('cat_len_noter_val: ', self.cat_len_noter_val)
print('len(cat_len_noter_val): ', len(self.cat_len_noter_val))
with open(self.test_data_dir, 'r') as f:
self.test_lines = f.readlines()
self.cat_len_noter_test = self.get_cat_len_noter_conceptnet(self.test_lines)
print('cat_len_noter_test: ', self.cat_len_noter_test)
print('len(cat_len_noter_test): ', len(self.cat_len_noter_test))
else:
data_dir = "./Data/e2e/"
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection)+'_lines' + self.args.additional_sample_name), 'rb') as f:
self.train_lines = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(1000)+'_lines'), 'rb') as f:
self.val_lines = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(4693)+'_lines'), 'rb') as f:
self.test_lines = pickle.load(f)
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection)+'_cat_len_noter' + self.args.additional_sample_name), 'rb') as f:
self.cat_len_noter_train = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(1000)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_val = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(4693)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_test = pickle.load(f)
if self.args.if_use_full_memory_store_while_subset:
data_dir = "./Data/e2e/"
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection_while_use_full_memory_store)+'_lines' + self.args.additional_sample_name), 'rb') as f:
self.train_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(1000)+'_lines'), 'rb') as f:
self.val_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(4693)+'_lines'), 'rb') as f:
self.test_subset_lines = pickle.load(f)
with open(os.path.join(data_dir, 'train'+'_subset_'+str(self.args.subset_selection_while_use_full_memory_store)+'_cat_len_noter' + self.args.additional_sample_name), 'rb') as f:
self.cat_len_noter_subset_train = pickle.load(f)
with open(os.path.join(data_dir, 'eval'+'_subset_'+str(1000)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_subset_val = pickle.load(f)
with open(os.path.join(data_dir, 'test'+'_subset_'+str(4693)+'_cat_len_noter'), 'rb') as f:
self.cat_len_noter_subset_test = pickle.load(f)
def get_ori_text_sentiment(self):
while not os.path.exists(self.train_data_dir):
time.sleep(5)
if self.args.dataset_selection == 4:
data_dir = "./Data/sentiment/splitted/"
elif self.args.dataset_selection == 5:
data_dir = "./Data/financial_phasebank/splitted/"
elif self.args.dataset_selection == 6:
data_dir = "./Data/yelp/splitted/"
elif self.args.dataset_selection == 7:
data_dir = "./Data/twitter/splitted/"
else:
raise NotImplementError
with open(self.train_data_dir, 'r') as f:
if self.args.subset_selection == -1:
self.train_lines = f.readlines()
else:
all_lines = f.readlines()
with open(os.path.join(data_dir, "{}_subset_{}_index.npy".format("train", self.args.subset_selection)), "rb") as f:
subset_indexes = np.load(f)
subset_indexes = sorted(subset_indexes)
self.train_lines = [all_lines[index] for index in subset_indexes]
self.cat_len_noter_train = self.get_cat_len_noter_conceptnet(self.train_lines)
print('cat_len_noter_train: ', self.cat_len_noter_train)
print('len(cat_len_noter_train): ', len(self.cat_len_noter_train))
with open(self.val1_data_dir, 'r') as f:
self.val_lines = f.readlines()
self.cat_len_noter_val = self.get_cat_len_noter_conceptnet(self.val_lines)
print('cat_len_noter_val: ', self.cat_len_noter_val)
print('len(cat_len_noter_val): ', len(self.cat_len_noter_val))
with open(self.test_data_dir, 'r') as f:
self.test_lines = f.readlines()
self.cat_len_noter_test = self.get_cat_len_noter_conceptnet(self.test_lines)
print('cat_len_noter_test: ', self.cat_len_noter_test)
print('len(cat_len_noter_test): ', len(self.cat_len_noter_test))
if self.args.if_use_full_memory_store_while_subset:
raise NotImplementedError
# get embed for train batches
# input:
# self.next_bundle: #train(gene_doc_input_ids, gene_doc_attention_mask, gene_doc_lm_labels, \
# gene_cur_input_ids, gene_cur_attention_mask, gene_cur_lm_labels, \
# data_idx_ids, rel_collection, \
# retr_doc_input_ids, retr_doc_attention_mask, retr_doc_segment_ids, \
# retr_input_ids, retr_attention_mask, retr_segment_ids)
# output: embedding, rel_list(should be sorted), line_id, ori_id_in_next_bundle(to recover order)
def get_embed_for_train_batches(self, model_type=None, save_dir=None, next_bundle=None):
self.model.eval()
len_next_bundle = next_bundle[0].size()[0]
id_next_bundle = torch.tensor(list(range(len_next_bundle)))
reorder_to_sort_rel = torch.argsort(next_bundle[-7])
# now next_bundle has ordered rel_list
next_bundle = [d[reorder_to_sort_rel] for d in next_bundle]
# to recover the ori batch id
ori_id_in_next_bundle = id_next_bundle[reorder_to_sort_rel]
builded_embedding = None
num_steps = math.ceil(len_next_bundle / self.args.train_batch_size)
for step in range(num_steps):
batch = [d[step*self.args.train_batch_size: np.minimum((step+1)*self.args.train_batch_size, len_next_bundle)] for d in next_bundle]
# batch: (retr_input_ids, retr_attention_mask, retr_segment_ids)
batch = tuple(t.to(device) for t in batch[-3:])
batch_size = batch[0].size()[0]
# DEBUG
# if step == 0 and self.data_type == 'train':
# print('batch_size: ', batch_size)
# print(torch.cuda.memory_summary(device))
with torch.no_grad():
# embedding: [batch_size, 768]
embedding = batch_get_embed(self.model, model_type, batch)
if step == 0:
builded_embedding = embedding
else:
builded_embedding = torch.cat((builded_embedding, embedding), 0)
# rel_for_embedding: torch.Size([709996])
rel_for_embedding = next_bundle[-7]
line_id_for_embedding = next_bundle[-8]
assert rel_for_embedding.size()[0] == builded_embedding.size()[0]
# save
if save_dir:
torch.save([builded_embedding.cpu(), rel_for_embedding, ori_id_in_next_bundle], save_dir)
return builded_embedding, rel_for_embedding, line_id_for_embedding, ori_id_in_next_bundle
## Get a sample id and use it to get embed for sample CKB, then build a dict for the embed
# INPUT:
# use_only_sub_rel_for_retrieval: for if_double_retrieval, different from args.use_only_sub_rel_for_retrieval
# OUTPUT:
# sample_ckb_dict: dict for builded_embedding of sample CKB
def get_sample_caseKB_embed_dict(self, data_type='train', use_only_sub_rel_for_retrieval=False):
if data_type == 'train':
## get sample_ids; each rel has sample_size_each_rel samples
if self.args.if_only_embed_ckb_once:
sample_ids = torch.tensor(list(range(len(self.train_lines))))
print('INFO: Using full train instances as memory store during training...{}'.format(len(self.train_lines)))
else:
sample_ids = self.get_sample_ids(data_type=data_type)
print('len(sample_ids): ', len(sample_ids))
elif data_type == 'eval' or data_type == 'test':
# Q: just for debug
# sample_ids = self.get_sample_ids()
# print('Using sampled train instances as memory store during evaling or testing, len(sample_ids):', len(sample_ids))
sample_ids = torch.tensor(list(range(len(self.train_lines))))
print('INFO: Using full train instances as memory store during evaling or testing...')
else:
raise Exception("Wrong data_type: ", data_type)
# print('sample_ids.size()', sample_ids.size())
## get sampled train embeddings
# sample_ckb_rel_for_embed: sorted if data in train_dir is sorted
# sample_ckb_rel_for_embed: id for rel
# sample_ckb_line_id_for_embed: line id
sample_ckb_train_embed, sample_ckb_rel_for_embed, sample_ckb_line_id_for_embed = self.get_embed_for_sample_CKB(sample_ids=sample_ids, use_only_sub_rel_for_retrieval=use_only_sub_rel_for_retrieval)
# print('sample_ckb_train_embed:', sample_ckb_train_embed.size())
print('sample_ckb_rel_for_embed:', sample_ckb_rel_for_embed)
# print('sample_ckb_line_id_for_embed:', sample_ckb_line_id_for_embed.size())
## get sample_ckb_dict
sample_ckb_dict = self.get_sample_ckb_dict(sample_ckb_train_embed=sample_ckb_train_embed, sample_ckb_rel_for_embed=sample_ckb_rel_for_embed, sample_ckb_line_id_for_embed=sample_ckb_line_id_for_embed)
return sample_ckb_dict
# OUTPUT:
# sample_ckb_dict: dict of embed for sample ckb
# bundle_embed_rlts: embed& for bundle
# rel_ttl_batch: used for check correctness of result
def get_embed_for_sample_ckb_and_bundle(self):
## get dict of embedding of sample_ckb
sample_ckb_dict = self.get_sample_caseKB_embed_dict()
# print('CaseKB embedded!')
## get embedding of bundle
# rel_ttl_batch: used for check correctness of result
bundle_embed_rlts, rel_ttl_batch = self.get_bundle_embed_list(model_type=self.args.retriever_model_type)
# print('Bundle embedded!')
return sample_ckb_dict, bundle_embed_rlts, rel_ttl_batch
## INPUT:
# idx_for_ttl_similar_cases_for_bundle: [len_bundle, num_cases*self.times_more_num_cases_to_retrieve]
# prob_for_ttl_similar_cases_for_bundle: [len_bundle, num_cases*self.times_more_num_cases_to_retrieve]
# ttl_similar_cases_with_bundle_order: [len_bundle] (num_cases*self.times_more_num_cases_to_retrieve)
# ttl_cur_tuple_with_bundle_order: [len_bundle] (num_cases*self.times_more_num_cases_to_retrieve)
## OUTPUT:
# idx_for_ttl_similar_cases_for_bundle: [len_bundle, num_cases]
# prob_for_ttl_similar_cases_for_bundle: [len_bundle, num_cases]
# ttl_similar_cases_with_bundle_order: [len_bundle] (num_cases)
# ttl_cur_tuple_with_bundle_order: [len_bundle]
# obj_line_id_bundleOrder: [len_bundle]
def rerank(self, idx_for_ttl_similar_cases_for_bundle, prob_for_ttl_similar_cases_for_bundle, ttl_similar_cases_with_bundle_order, ttl_cur_tuple_with_bundle_order, obj_line_id_bundleOrder, data_type):
# make sure the four input has the same len_bundle
debug_normal_retrieval, debug_abnormal_retrieval = 0, 0
assert idx_for_ttl_similar_cases_for_bundle.size()[0] == prob_for_ttl_similar_cases_for_bundle.size()[0]
assert idx_for_ttl_similar_cases_for_bundle.size()[0] == len(ttl_similar_cases_with_bundle_order)
assert idx_for_ttl_similar_cases_for_bundle.size()[0] == len(ttl_cur_tuple_with_bundle_order)
assert idx_for_ttl_similar_cases_for_bundle.size()[0] == obj_line_id_bundleOrder.size()[0]
if self.args.rerank_selection == 0:
# reverse order of demonstrations
if self.args.if_reverse_order_demonstrations:
raise NotImplementedError
assert self.times_more_num_cases_to_retrieve == 1
# save cases to further test BLEU
if data_type == 'eval':
self.ttl_similar_cases_eval += ttl_similar_cases_with_bundle_order
elif data_type == 'test':
self.ttl_similar_cases_test += ttl_similar_cases_with_bundle_order
return idx_for_ttl_similar_cases_for_bundle, prob_for_ttl_similar_cases_for_bundle, \
ttl_similar_cases_with_bundle_order, ttl_cur_tuple_with_bundle_order
elif self.args.rerank_selection == 1 or self.args.rerank_selection == 2:
## get len_bundle and num_cases
len_bundle = idx_for_ttl_similar_cases_for_bundle.size()[0]
assert idx_for_ttl_similar_cases_for_bundle.size()[1] % self.times_more_num_cases_to_retrieve == 0
num_cases = int(idx_for_ttl_similar_cases_for_bundle.size()[1] / self.times_more_num_cases_to_retrieve)
# number of items in id_with_different_source to collect
if self.args.larger_range_to_select_retrieval_randomly_from != -1 and data_type == 'train':
print("num_cases: ", num_cases)
num_maybe_expanded_cases = np.maximum(self.args.larger_range_to_select_retrieval_randomly_from, num_cases)
# num_maybe_expanded_cases shouldn't exceed self.n_shot-2;
# idx_for_ttl_similar_cases_for_bundle.size()[1] >= self.n_shot-2 and can be filled with irrelavant ids
# num_maybe_expanded_cases = np.minimum(idx_for_ttl_similar_cases_for_bundle.size()[1], num_maybe_expanded_cases)
# *0.25 means we only want to use top retrievals for in-context demonstration combinations
num_maybe_expanded_cases = np.minimum(int((self.n_shot-2)*0.25), num_maybe_expanded_cases)
num_maybe_expanded_cases = np.maximum(num_maybe_expanded_cases, num_cases)
# count the distribution of number of items in id_with_different_source
cnt_id_with_different_source = {}
else:
num_maybe_expanded_cases = num_cases
## begin selection (retrieved cases' source can't be the same with current query)
for id_bundle in range(len_bundle):
# If rerank == 2 and data_type == 'eval' or 'test', then the model can at most get one case that is with same source
if self.args.rerank_selection == 2 and data_type != 'train':
num_allowed_case_with_same_source = 1
else:
num_allowed_case_with_same_source = 0
id_with_different_source = []
dict_retrieved_cases_source = {}
# id_with_different_relation is used when train set do not contain any case with same relation
id_with_different_relation = []
# when use classification dataset, we might want the label of retrieved cases to be evenly distributed (without it, sentiment dataset also works well, so not include dataset_selection == 4)
if self.args.dataset_selection == 5 or self.args.dataset_selection == 6:
label_of_collected_cases = []
cur_query = ttl_cur_tuple_with_bundle_order[id_bundle].strip('\n').split('\t')[1]
cur_rel = ttl_cur_tuple_with_bundle_order[id_bundle].strip('\n').split('\t')[0]
tmp_ttl_cases = ttl_similar_cases_with_bundle_order[id_bundle].strip('\n').split('\t\t')
# when using subset, it's very possible that we do not have tmp_ttl_cases as full size as idx_for_ttl_similar_cases_for_bundle.size()[1]
# many in idx_for_ttl_similar_cases_for_bundle.size()[1] would be -1
if self.args.subset_selection == -1 and self.args.dataset_selection != 0:
try:
assert len(tmp_ttl_cases) == idx_for_ttl_similar_cases_for_bundle.size()[1]
except:
print("len(tmp_ttl_cases): ", len(tmp_ttl_cases))
print("idx_for_ttl_similar_cases_for_bundle.size()[1]: ", idx_for_ttl_similar_cases_for_bundle.size()[1])
raise Exception("Not enough tmp_ttl_cases is retrieved")
# get rid of retrieved cases that share the same source
try:
assert len(tmp_ttl_cases) >= num_cases
except:
print("len(tmp_ttl_cases): ", len(tmp_ttl_cases))
print("num_cases: ", num_cases)
assert len(tmp_ttl_cases) >= num_cases
for id_case in range(len(tmp_ttl_cases)):
tmp_ttl_cases[id_case] = tmp_ttl_cases[id_case].strip('\n')
tmp_source = tmp_ttl_cases[id_case].split('\t')[1]
tmp_rel = tmp_ttl_cases[id_case].split('\t')[0]
tmp_obj = tmp_ttl_cases[id_case].split('\t')[2]
# Only when dataset is conceptnet, tmp_rel != cur_rel is allowed;
# But we do not use case whose rel != cur_rel in rerank1 and rerank2
if tmp_rel != cur_rel:
if self.args.dataset_selection == 0:
# print("Warning: tmp_rel != cur_rel")
id_with_different_relation.append(id_case)
continue
else:
print('tmp_rel: ', tmp_ttl_cases[id_case].split('\t'))
print('cur_rel: ', ttl_cur_tuple_with_bundle_order[id_bundle].strip('\n').split('\t'))
raise Exception("tmp_rel != cur_rel")
if tmp_source.strip() != cur_query.strip():
if self.args.dataset_selection == 5 or self.args.dataset_selection == 6:
# print("tmp_obj: ", tmp_obj)
if tmp_obj not in label_of_collected_cases:
label_of_collected_cases.append(tmp_obj)
else:
continue
if not self.args.use_only_sub_rel_for_retrieval:
# old method 8/17/2021: 11.54 p.m.
id_with_different_source.append(id_case)
elif tmp_source not in dict_retrieved_cases_source:
dict_retrieved_cases_source[tmp_source] = [id_case]
id_with_different_source.append(id_case)
else:
print("{} founded again".format(tmp_source))
continue
elif num_allowed_case_with_same_source > 0:
id_with_different_source.append(id_case)
num_allowed_case_with_same_source -= 1
# if len(id_with_different_source) >= num_cases:
if len(id_with_different_source) >= num_maybe_expanded_cases:
break
# print("1. len(id_with_different_source): ", len(id_with_different_source))
if self.args.dataset_selection != 0:
try:
assert len(id_with_different_source) >= num_cases
except:
print("label_of_collected_cases: ", label_of_collected_cases)
raise Exception("Retrieved cases have a less number than requirement. Requirememt: {}; Retrieved: {}".format(num_cases, len(id_with_different_source)))
else:
# if len(id_with_different_source) == self.args.num_cases and len(id_with_different_relation) == 0:
if len(id_with_different_source) >= self.args.num_cases and len(id_with_different_relation) == 0:
debug_normal_retrieval += 1
else:
# print("len(id_with_different_source): {}, len(id_with_different_relation): {}".format(len(id_with_different_source), len(id_with_different_relation)))
debug_abnormal_retrieval += 1
# when the dataset is conceptnet, for some relation the available retrieval cases is less than num_cases
# In this circumstance, we choose to replicate the existing available retrieval cases
while len(id_with_different_source) < num_cases:
# if len(id_with_different_source) == 0, this while loop will stuck
if len(id_with_different_source) > 0:
id_with_different_source = id_with_different_source + id_with_different_source
else:
try:
assert len(id_with_different_relation) > 0
except:
print("len(id_with_different_relation): ", len(id_with_different_relation))
print("tmp_ttl_cases: ", tmp_ttl_cases)
print('cur_rel: ', ttl_cur_tuple_with_bundle_order[id_bundle].strip('\n').split('\t'))
print("times_more_num_cases_to_retrieve: ", self.times_more_num_cases_to_retrieve)
raise Exception("Can't load id_with_different_relation OR times_more_num_cases_to_retrieve is not enough.")
id_with_different_source = id_with_different_relation
# restrict the length of id_with_different_source when self.args.larger_range_to_select_retrieval_randomly_from != -1
if self.args.larger_range_to_select_retrieval_randomly_from != -1 and len(id_with_different_source) >= self.args.larger_range_to_select_retrieval_randomly_from:
id_with_different_source = id_with_different_source[:self.args.larger_range_to_select_retrieval_randomly_from]
# Modify this "if" code largely in 8/22/2021: 11:53 p.m.;
# Check github if you are interested in the previous version of this "if" code
# According to "Recency Bias", I think we should keep the
# demonstrations (to put in input_ids) in order of similarity
if self.args.larger_range_to_select_retrieval_randomly_from != -1 and data_type == 'train':
# print("2. len(id_with_different_source): ", len(id_with_different_source))
# count the number of items in id_with_different_source
if len(id_with_different_source) not in cnt_id_with_different_source:
cnt_id_with_different_source[len(id_with_different_source)] = 1
else:
cnt_id_with_different_source[len(id_with_different_source)] += 1
# id in tmp_id_for_id_with_different_source should be sorted \
# (to keep the order of id_with_different_source)
tmp_id_for_id_with_different_source = get_id_for_id_with_different_source_during_larger_range(id_with_different_source, self.args.larger_range_to_select_retrieval_randomly_from, num_cases)
assert len(tmp_id_for_id_with_different_source) == num_cases
id_with_different_source = np.array(id_with_different_source)
id_with_different_source = id_with_different_source[tmp_id_for_id_with_different_source]
id_with_different_source = id_with_different_source.tolist()
# only select num_cases cases
id_with_different_source = id_with_different_source[:num_cases]
else:
id_with_different_source = id_with_different_source[:num_cases]
# reverse order of demonstrations
if self.args.if_reverse_order_demonstrations:
id_with_different_source.reverse()
if id_bundle == 0:
print("INFO: Demonstrations reversed")
# get selected_idx_for_ttl_similar_cases_for_bundle / selected_prob_for_ttl_similar_cases_for_bundle
if id_bundle == 0:
selected_idx_for_ttl_similar_cases_for_bundle = idx_for_ttl_similar_cases_for_bundle[id_bundle, id_with_different_source].unsqueeze(0)
selected_prob_for_ttl_similar_cases_for_bundle = prob_for_ttl_similar_cases_for_bundle[id_bundle, id_with_different_source].unsqueeze(0)
selected_ttl_similar_cases_with_bundle_order = ['\t\t'.join([tmp_ttl_cases[i] for i in id_with_different_source]) + '\n']
else:
# cur_selected_idx
cur_selected_idx = idx_for_ttl_similar_cases_for_bundle[id_bundle, id_with_different_source].unsqueeze(0)
selected_idx_for_ttl_similar_cases_for_bundle = torch.cat((selected_idx_for_ttl_similar_cases_for_bundle, cur_selected_idx), dim=0)
# cur_selected_idx_prob
cur_selected_idx_prob = prob_for_ttl_similar_cases_for_bundle[id_bundle, id_with_different_source].unsqueeze(0)
selected_prob_for_ttl_similar_cases_for_bundle = torch.cat((selected_prob_for_ttl_similar_cases_for_bundle, cur_selected_idx_prob), dim=0)
# tmp_ttl_cases
cur_tmp_ttl_cases = '\t\t'.join([tmp_ttl_cases[i] for i in id_with_different_source]) + '\n'
selected_ttl_similar_cases_with_bundle_order.append(cur_tmp_ttl_cases)
# save cases to further test BLEU
if data_type == 'eval':
self.ttl_similar_cases_eval += selected_ttl_similar_cases_with_bundle_order
elif data_type == 'test':
self.ttl_similar_cases_test += selected_ttl_similar_cases_with_bundle_order
# Add current (sub, rel, obj) tuple to retrieved case
if self.args.rerank_selection == 2 and data_type == 'train':
for id_bundle in range(len_bundle):
tmp_rand = np.random.rand(1)[0]
if tmp_rand > self.args.possibility_add_cur_tuple_to_its_retrieved_cases:
# if tmp_rand > 0.0:
tmp_id = int(tmp_rand * 101) % num_cases
# if if_use_full_memory_store_while_subset == True, obj_line_id_bundleOrder is line_id in few shot set, while \
# selected_idx_for_ttl_similar_cases_for_bundle is line_id in full train set; they are not aligned
assert not self.args.if_use_full_memory_store_while_subset
# tmp_id = 0
selected_idx_for_ttl_similar_cases_for_bundle[id_bundle, tmp_id] = obj_line_id_bundleOrder[id_bundle]
selected_prob_for_ttl_similar_cases_for_bundle[id_bundle, tmp_id] = 1.0
tmp_ttl_similar_cases = selected_ttl_similar_cases_with_bundle_order[id_bundle].strip().split('\t\t')
tmp_ttl_similar_cases[tmp_id] = ttl_cur_tuple_with_bundle_order[id_bundle].strip()
selected_ttl_similar_cases_with_bundle_order[id_bundle] = '\t\t'.join(tmp_ttl_similar_cases) + '\n'
print("debug_normal_retrieval: {}, debug_abnormal_retrieval: {}".format(debug_normal_retrieval, debug_abnormal_retrieval))
if self.args.larger_range_to_select_retrieval_randomly_from != -1 and data_type == 'train':
print("cnt_id_with_different_source: ", cnt_id_with_different_source)
return selected_idx_for_ttl_similar_cases_for_bundle, selected_prob_for_ttl_similar_cases_for_bundle, selected_ttl_similar_cases_with_bundle_order, ttl_cur_tuple_with_bundle_order
# get cases for train data
# INPUT:
# bundle_embed_rlts: [obj_emb, obj_rel_list, obj_line_id, obj_ori_id_in_bundle]
# counter_while_loop: when is 0, print time.time()
# sample_ckb_dict_subRel: is not None only when args.if_double_retrieval == True; same usage as sample_ckb_dict
# output:
# sample_ckb_train_embed: [sample_size, 968]
# ttl_similar_cases_with_bundle_order: [num_steps*train_batch_size] (after '\t\t'.join())
# ttl_cur_tuple_with_bundle_order: [num_steps*train_batch_size] (['rel\tsub\tobj\n', ...])
# idx_for_ttl_similar_cases_for_bundle: [num_steps*train_batch_size, num_cases]
# prob_for_ttl_similar_cases_for_bundle: [num_steps*train_batch_size, num_cases]
# encoded_cases: [encoded_cases_gene, encoded_cases_retr]
# encoded_cases_gene: [doc_gene_input_ids, doc_gene_attention_mask, doc_gene_lm_labels]
# encoded_cases_retr: [doc_retr_cases_input_ids, doc_retr_cases_attention_mask, doc_retr_cases_segment_ids]
# doc_gene_input_ids: [len_bundle, n_doc, cases_per_doc * input_len_gene]
# doc_retr_cases_input_ids: [len_bundle, n_doc, cases_per_doc, input_len_retr]
def get_and_save_encoded_cases_and_check_result(self, sample_ckb_dict, bundle_embed_rlts, \
rel_ttl_batch, counter_while_loop, num_cases=None, n_doc=None, data_type='train', sample_ckb_dict_subRel=None):
assert data_type == "train" or data_type == "eval" or data_type == "test"
## get train cases
start_time = time.time()
if self.args.if_double_retrieval:
# double retrieval for better retrieval quality
idx_for_ttl_similar_cases_for_bundle, prob_for_ttl_similar_cases_for_bundle, ttl_similar_cases_with_bundle_order, ttl_cur_tuple_with_bundle_order, obj_line_id_bundleOrder = self.get_selected_idx_and_probs_double_retrieval(
sample_ckb_dict=sample_ckb_dict, sample_ckb_dict_subRel=sample_ckb_dict_subRel, bundle_embed_rlts=bundle_embed_rlts, num_cases=num_cases, data_type=data_type)
else:
# classical once retrieval
idx_for_ttl_similar_cases_for_bundle, prob_for_ttl_similar_cases_for_bundle, ttl_similar_cases_with_bundle_order, ttl_cur_tuple_with_bundle_order, obj_line_id_bundleOrder = self.get_selected_idx_and_probs(
sample_ckb_dict=sample_ckb_dict, bundle_embed_rlts=bundle_embed_rlts, num_cases=num_cases, data_type=data_type)
if counter_while_loop == 0:
start_time_step1 = time.time()
print("--- Finish MIPS step 1: %s seconds ---" % (start_time_step1 - start_time))
# only to get the retrieval_index_id for sentiment sentence dataset (so to get the case difference feature)
# if self.args.dataset_selection == 4 and data_type != "train":
if self.args.dataset_selection == 4 or self.args.dataset_selection == 5 or self.args.dataset_selection == 6 or self.args.dataset_selection == 7:
torch.save(idx_for_ttl_similar_cases_for_bundle, os.path.join(self.args.output_dir, "retrieved_ids_sentiment_sentence_classification_{}_{}.pt".format(data_type, counter_while_loop)))
idx_for_ttl_similar_cases_for_bundle, prob_for_ttl_similar_cases_for_bundle, ttl_similar_cases_with_bundle_order, ttl_cur_tuple_with_bundle_order = self.rerank(idx_for_ttl_similar_cases_for_bundle, prob_for_ttl_similar_cases_for_bundle, ttl_similar_cases_with_bundle_order, ttl_cur_tuple_with_bundle_order, obj_line_id_bundleOrder, data_type)
if counter_while_loop == 0:
# print('MIPS finished! Successfully got selected_idx')
print("--- Finish MIPS step 2: %s seconds ---" % (time.time() - start_time_step1))
# for DEBUG:
torch.save(prob_for_ttl_similar_cases_for_bundle, os.path.join(self.args.output_dir, 'prob_for_ttl_similar_cases_for_bundle.pt'))
start_time = time.time()
encoded_cases = self.get_and_save_encoded_cases(idx_for_ttl_similar_cases_for_bundle, num_cases=num_cases, n_doc=n_doc, data_type=data_type)
if counter_while_loop == 0:
# print('God encoded_cases successfully!')
print("--- Get encoded cases: %s seconds ---" % (time.time() - start_time))
# print(len(ttl_similar_cases_for_batch), prob_for_ttl_similar_cases_for_batch.size())
# print('ttl_similar_cases_for_batch[0:20]:', ttl_similar_cases_for_batch[0:20])
start_time = time.time()
self.check_result(rel_ttl_batch, ttl_similar_cases_with_bundle_order, prob_for_ttl_similar_cases_for_bundle, num_cases=num_cases)
torch.save(rel_ttl_batch, self.batch_rel_dir)
if counter_while_loop == 0:
print("--- Result checked: %s seconds ---" % (time.time() - start_time))
# return ttl_similar_cases_for_batch, prob_for_ttl_similar_cases_for_batch
# check results
# check ttl_similar_cases_for_batch match with prob_for_ttl_similar_cases_for_batch
# check rel in ttl_similar_cases_for_batch match with batch
def check_result(self, rel_ttl_batch, ttl_similar_cases_for_batch, prob_for_ttl_similar_cases_for_batch, num_cases):
if num_cases == None:
num_cases = self.num_cases
# check rel
assert rel_ttl_batch.size()[0] == len(ttl_similar_cases_for_batch)
assert prob_for_ttl_similar_cases_for_batch.size()[0] == len(ttl_similar_cases_for_batch)
# if self.args.dataset_selection == 0, then we have to keep some ttl_similar_cases_for_batch even the relation doesn't match
# when rerank_selection == 1 or 2, which will violate the assertion in check_result function, but that's ok