-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathdataloader.py
2417 lines (2163 loc) · 104 KB
/
dataloader.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
from header import *
from utils import *
from data import *
'''
The Dataset Object can handle the single-turn and multi-turn (<eou> seperator) dialog format.
'''
# ========== For LCCC ========== #
SPECIAL_TOKENS = ["[CLS]", "[SEP]", "[speaker1]", "[speaker2]"]
# ========== For LCCC ========== #
class ChineseTokenizer:
'''
Only for Chinese RNN based model, parameters:
:corpus: a list of pair (context string, response string)
'''
def __init__(self, corpus, n_vocab=50000, min_freq=1):
self.allowPOS = ['n', 'nr', 'nz', 'PER', 'LOC', 'ORG', 'ns', 'nt', 'nw', 'vn', 's']
self.topk = 10
special_tokens = ['[PAD]', '[UNK]', '[CLS]', '[SEP]']
self.vocab = vocab.Vocab(
self._build_vocab(corpus),
max_size=n_vocab,
min_freq=min_freq,
specials=special_tokens,
)
assert self.vocab.stoi['[PAD]'] == 0, f'[PAD] id should be 0, but got {self.vocab.stoi["[PAD]"]}'
print(f'[!] init the vocabulary over, vocab size: {len(self.vocab)}')
def __len__(self):
return len(self.vocab)
@property
def size(self):
return len(self.vocab)
def decode(self, idx_seq, spliter=''):
'''chinese spliter: ''; english spliter: ' '
'''
words = self.idx2toks(idx_seq)
return spliter.join(words)
def encode(self, tok_seq, len_size_limit):
'''Careful about the special tokens'''
sentences = re.split('(\[SEP\])', tok_seq)
sep_token = self.vocab.stoi['[SEP]']
cls_token = self.vocab.stoi['[CLS]']
idxs = []
for sentence in sentences:
sentence = sentence.strip()
if sentence == '[SEP]':
continue
sentence = list(jieba.cut(sentence))
sentence = list(map(lambda i: self.vocab.stoi[i] if i in self.vocab.stoi else self.vocab.stoi['[UNK]'], sentence))
idxs.extend(sentence)
idxs.append(sep_token)
idxs = idxs[-(len_size_limit-2):]
idxs = [cls_token] + idxs
return idxs
def idx2toks(self, idx_seq):
return list(map(lambda i: self.vocab.itos[i], idx_seq))
def _build_vocab(self, corpus):
vocab_counter = Counter()
for context, response in tqdm(corpus):
c_words = list(jieba.cut(context))
r_words = list(jieba.cut(response))
vocab_counter.update(c_words + r_words)
print(f'[!] whole vocab size: {len(vocab_counter)}')
return vocab_counter
def _build_keywords(self, corpus):
keywords = Counter()
for dialog in tqdm(corpus):
for utterance in dialog:
words = jieba.analyse.extract_tags(
utterance,
topK=self.topk,
allowPOS=self.allowPOS
)
keywords.update(words)
print(f'[!] collect {len(keywords)} keywords')
return keywords
class When2talkDataset(Dataset):
def __init__(self, path, mode='train', min_length=15, lang='zh', src_len_size=512, tgt_len_size=128):
if lang == 'zh':
vocab_file = 'data/vocab/vocab_small'
else:
vocab_file = 'data/vocab/vocab_english'
self.mode = mode
# tokenizer with addtional tokens
self.vocab = BertTokenizer(vocab_file=vocab_file)
additional_tokens = {'additional_special_tokens': ['[USER1]', '[USER2]', '[STP]']}
self.vocab.add_special_tokens(additional_tokens)
self.src_len_size, self.tgt_len_size = src_len_size, tgt_len_size
#
self.pp_path = f'{os.path.splitext(path)[0]}.pkl'
if os.path.exists(self.pp_path):
with open(self.pp_path, 'rb') as f:
self.data = pickle.load(f)
print(f'[!] load preprocessed file from {self.pp_path}')
return None
#
data = read_text_data(path)
self.data = []
if self.mode in ['train', 'dev']:
contexts = [when2talk_utils(i) for i in data]
for sample in tqdm(contexts):
bundle = dict()
bundle['context_text'] = sample
ids = self.vocab.encode(sample)[1:-1]
if len(ids) < min_length:
continue
ids = ids[-self.src_len_size:]
bundle['context_id'] = torch.LongTensor(ids)
self.data.append(bundle)
self.data = sorted(self.data, key=lambda x: len(x['context_id']))
else:
contexts = [when2talk_utils(i) for i in data]
for sample in tqdm(contexts):
bundle = dict()
bundle['context_text'] = sample
ids = self.vocab.encode(sample)[1:-1]
user2_token = self.vocab.convert_tokens_to_ids('[USER2]')
context, response = ids[:ids.index(user2_token) + 1], ids[ids.index(user2_token) + 1:]
if len(context) < min_length:
continue
context = context[-self.src_len_size:]
bundle['context_id'] = torch.LongTensor(context)
bundle['reply_id'] = torch.LongTensor(response)
self.data.append(bundle)
print(f'[!] read and process raw data from {path} over')
# save the data
with open(self.pp_path, 'wb') as f:
pickle.dump(self.data, f)
print(f'[!] save dataset into {self.pp_path}')
def __len__(self):
return len(self.data)
def __getitem__(self, i):
return self.data[i]
# ========== LCCC-GPT2 ========== #
# For LCCC IR Model, fine tuning the LCCC GPT2 model for retrieval dialog systems
class UNIDataset(Dataset):
def __init__(self, vocab, path, samples=1, max_history=5, batch_first=True, uni=False):
self.tokenizer = BertTokenizer.from_pretrained(vocab)
self.max_history = max_history
self.pad = self.tokenizer.pad_token_id
self.batch_first = batch_first
self.pp_path = f'{os.path.splitext(path)[0]}_uni.pt'
# load the dataset
if os.path.exists(self.pp_path):
self.data = torch.load(self.pp_path)
print(f'[!] load preprocessed file from {self.pp_path}')
else:
with open(path, 'r', encoding='utf-8') as f:
dataset = read_lccc_data(path, debug=True)
# ipdb.set_trace()
responses = [i[-1] for i in dataset]
dataset = [self.tokenize_(item) for item in tqdm(dataset)]
self.data = []
# construct the negative samples and positive samples
for dialog in tqdm(dataset):
bundle = {'context': dialog}
# context, response = dialog[:-1], dialog[-1]
# negatives = generate_negative_samples(
# response,
# responses,
# samples=samples
# )
# tokenize negative samples
# negatives = self.tokenize_(negatives)
# for i, r in enumerate([response] + negatives):
# bundle = {
# 'context': context + [r],
# 'label': 1 if i == 0 else 0,
# }
# bundle = {'context': context + [response]}
self.data.append(bundle)
print(f'[!] collect {len(self.data)} samples for training')
torch.save(self.data, self.pp_path)
print(f'[!] process the dataset and write it into {self.pp_path}')
def tokenize_(self, obj):
if isinstance(obj, str):
return self.tokenizer.convert_tokens_to_ids(self.tokenizer.tokenize(obj))
return list(self.tokenize_(o) for o in obj)
def __len__(self):
return len(self.data)
def __getitem__(self, index):
history = self.data[index]['context'][-2 * self.max_history:-1]
resposne = self.data[index]['context'][-1]
# label = self.data[index]['label']
return self.process(history, resposne)
def process(self, history, resposne, with_eos=True):
bos, eos, speaker1, speaker2 = self.tokenizer.convert_tokens_to_ids(SPECIAL_TOKENS)
sequence = [[bos]] + history + [resposne + ([eos] if with_eos else [])]
sequence = [sequence[0]] + [[speaker2 if i % 2 else speaker1] + s
for i, s in enumerate(sequence[1:])]
instance = {}
instance["input_ids"] = list(chain(*sequence))[-512:]
instance["token_type_ids"] = [bos] + [speaker2 if i % 2 else speaker1 for i, s in
enumerate(sequence[1:])
for _ in s]
instance["token_type_ids"] = instance["token_type_ids"][-512:]
# if label == 0:
# # negative samples donot do the language model training
# instance["lm_labels"] = [-1] * len(instance["input_ids"])
# else:
instance["lm_labels"] = ([-1] * sum(len(s) for s in sequence[:-1])) + [-1] + sequence[-1][1:]
instance["lm_labels"] = instance["lm_labels"][-512:]
# instance["label"] = label
return instance;
def collate(self, batch):
input_ids = pad_sequence(
[torch.tensor(instance["input_ids"], dtype=torch.long) for instance in batch],
batch_first=self.batch_first, padding_value=self.pad
)
token_type_ids = pad_sequence(
[torch.tensor(instance["token_type_ids"], dtype=torch.long) for instance in batch],
batch_first=self.batch_first, padding_value=self.pad
)
# labels = torch.LongTensor([instance['label'] for instance in batch])
lm_labels = pad_sequence(
[torch.tensor(instance["lm_labels"], dtype=torch.long) for instance in batch],
batch_first=self.batch_first, padding_value=-1
)
# if torch.cuda.is_available():
# input_ids, token_type_ids, lm_labels = input_ids.cuda(), token_type_ids.cuda(), lm_labels.cuda()
# [B, S]; [B, S]; [B, S]
return input_ids, token_type_ids, lm_labels
# ========== LCCC-GPT2 ========== #
class GPT2Dataset(Dataset):
'''Training GPT2 model doesn't need the target sentence, just training the Language Model
GPT2 model can leverage the ability for all the pure text information, which is better than Seq2Seq architecture'''
def __init__(self, path, mode='train', lang='zh', min_length=20, src_len_size=512, tgt_len_size=128):
if lang == 'zh':
vocab_file = 'data/vocab/vocab_small'
else:
vocab_file = 'data/vocab/vocab_english'
self.mode = mode
self.pad = '[PAD]'
self.vocab = BertTokenizer(vocab_file=vocab_file)
self.pad_id = self.vocab.convert_tokens_to_ids(self.pad)
self.src_len_size, self.tgt_len_size = src_len_size, tgt_len_size
self.pp_path = f'{os.path.splitext(path)[0]}.pt'
if os.path.exists(self.pp_path):
self.data = torch.load(self.pp_path)
print(f'[!] load preprocessed file from {self.pp_path}')
return None
data = read_text_data(path)
self.data = []
if self.mode in ['train', 'dev']:
contexts = [' [SEP] '.join(sample) for sample in data]
for sample in tqdm(contexts):
bundle = dict()
bundle['context_text'] = sample
ids = self.vocab.encode(sample)
if len(ids) < min_length:
continue
bundle['context_id'] = ids[-self.src_len_size:]
self.data.append(bundle)
self.data = sorted(self.data, key=lambda x: len(x['context_id']))
else:
contexts, responses = [], []
for sample in data:
contexts.append(' [SEP] '.join(sample[:-1]))
responses.append(sample[-1])
for c, r in tqdm(list(zip(contexts, responses))):
bundle = dict()
bundle['context_text'] = c
bundle['reply_text'] = r
ids = self.vocab.encode(c)
bundle['context_id'] = ids[-self.src_len_size:]
ids = self.vocab.encode(r)
bundle['reply_id'] = ids[:self.tgt_len_size]
self.data.append(bundle)
print(f'[!] read and process raw data from {path} over')
def save_pickle(self):
torch.save(self.data, self.pp_path)
print(f'[!] save dataset into {self.pp_path}')
def __len__(self):
return len(self.data)
def __getitem__(self, i):
return self.data[i]
def collate(self, batch):
if self.mode in ['train', 'dev']:
ctx = [torch.LongTensor(i['context_id']) for i in batch]
random.shuffle(ctx)
ctx = pad_sequence(ctx, batch_first=True, padding_value=self.pad_id)
if torch.cuda.is_available():
ctx = ctx.cuda()
return ctx
else:
# assert len(batch) == 1, f'[!] batch must be 1, but got {len(batch)}'
# ctx, res = torch.LongTensor(batch[0]['context_id']), torch.LongTensor(batch[0]['reply_id'])
# if torch.cuda.is_available():
# ctx, res = ctx.cuda(), res.cuda()
# return ctx, res
# NOTE: BATCH VERSION, PAD IN THE LEFT;
max_len = max([len(i['context_id']) for i in batch])
ctx = torch.LongTensor([[self.pad_id] * (max_len - len(i['context_id'])) + i['context_id'] for i in batch])
position_ids = torch.LongTensor([[0] * (max_len - len(i['context_id'])) + list(range(len(i['context_id']))) for i in batch])
attn_mask_index = ctx.nonzero().tolist()
attn_mask_index_x, attn_mask_index_y = [i[0] for i in attn_mask_index], [i[1] for i in attn_mask_index]
attn_mask = ctx.clone()
attn_mask[attn_mask_index_x, attn_mask_index_y] = 1
res = [i['reply_id'] for i in batch]
if torch.cuda.is_available():
ctx = ctx.cuda()
attn_mask = attn_mask.cuda()
position_ids = position_ids.cuda()
return ctx, attn_mask, position_ids, res
class MultiGPT2Dataset(Dataset):
'''
GPT2 Dataset with the multiple retrieval samples
'''
def __init__(self, path, mode='train', vocab_file='data/vocab/vocab_small',
src_len_size=512, tgt_len_size=128, retrieval_size=2):
self.mode = mode
self.pad = '[PAD]'
self.vocab = BertTokenizer(vocab_file=vocab_file)
self.pad_id = self.vocab.convert_tokens_to_ids(self.pad)
self.src_len_size, self.tgt_len_size = src_len_size, tgt_len_size
self.data = []
data = read_csv_data(path)
if self.mode in ['train', 'dev']:
contexts, retrieval_list = [], []
for sample in data:
c = sample[0].split('<eou>')
c = [i.strip() for i in c]
c.append(sample[1])
contexts.append(c)
# retrieval list
retrieval_list.append(sample[2:2+retrieval_size])
for context, retrieval in tqdm(list(zip(contexts, retrieval_list))):
bundle = dict()
bundle['context_text'] = ''.join(context)
ids = [self.vocab.cls_token_id]
for utterance in context:
ids.extend([self.vocab.convert_tokens_to_ids(word) for word in utterance])
ids.append(self.vocab.sep_token_id)
# length size of the context
ids = ids[-self.src_len_size:]
bundle['context_id'] = torch.LongTensor(ids)
# retrieval list
bundle['retrieval_list_text'] = retrieval
retrieval_list_ = []
for i in retrieval:
ids = [self.vocab.cls_token_id]
ids.extend([self.vocab.convert_tokens_to_ids(word) for word in i])
ids.append(self.vocab.sep_token_id)
ids = ids[:self.src_len_size]
retrieval_list_.append(torch.LongTensor(ids))
bundle['retrieval_list'] = retrieval_list_
self.data.append(bundle)
else:
contexts, responses, retrieval_list = [], [], []
for sample in data:
c = sample[0].split('<eou>')
c = [i.strip() for i in c]
contexts.append(c)
responses.append(sample[1])
# retrieval list
retrieval_list.append(sample[2:2+retrieval_size])
for c, r, r_ in tqdm(list(zip(contexts, responses, retrieval_list))):
bundle = dict()
bundle['context_text'] = ''.join(c)
bundle['reply_text'] = r
bundle['retrievl_list_text'] = r_
# ids
ids = [self.vocab.cls_token_id]
for utterance in c:
ids.extend([self.vocab.convert_tokens_to_ids(word) for word in utterance])
ids.append(self.vocab.sep_token_id)
ids = ids[-self.src_len_size:]
bundle['context_id'] = torch.LongTensor(ids)
ids = [self.vocab.cls_token_id]
ids.extend([self.vocab.convert_tokens_to_ids(word) for word in r])
ids.append(self.vocab.sep_token_id)
ids = ids[:self.tgt_len_size]
bundle['reply_id'] = torch.LongTensor(ids)
# retrieval ids
retrieval_list_ = []
for i in r_:
ids = [self.vocab.cls_token_id]
ids.extend([self.vocab.convert_tokens_to_ids(word) for word in i])
ids.append(self.vocab.sep_token_id)
ids = ids[:self.src_len_size]
retrieval_list_.append(torch.LongTensor(ids))
bundle['retrieval_list'] = retrieval_list_
self.data.append(bundle)
print(f'[!] read and process raw dara from {path} over')
def __len__(self):
return len(self.data)
def __getitem__(self, i):
return self.data[i]
class DialogDataset(Dataset):
'''
Construct the dataset, use once for one epoch
Tokenizer is the function, default jieba.cut; You can also set is the list for no tokenization
'''
def __init__(self, path, mode='train', vocab=None, tokenizer=jieba.cut,
n_vocab=50000, src_len_size=100, tgt_len_size=20):
self.mode = mode
self.tokenizer = tokenizer
self.src_len_size = src_len_size
self.tgt_len_size = tgt_len_size
# load data
data = read_csv_data(path)
responses, contexts = [], []
for sample in tqdm(data):
responses.append(list(self.tokenizer(sample[1])))
rc, c = [], sample[0].split('<eou>')
for utterance in c:
rc.extend(list(self.tokenizer(utterance.strip())))
rc.append('<eou>')
rc = rc[:-1]
contexts.append(rc)
print(f'[!] read raw data from {path} over')
# process the dataset
if mode == 'train':
self.vocab = vocabulary(
(contexts, responses),
n_vocab=n_vocab)
else:
assert vocab, 'vocab not the NoneType for test/dev mode'
self.vocab = vocab
self.data = []
# init the data
for c, r in zip(contexts, responses):
bundle = dict()
bundle['context_text'] = ' '.join(c)
bundle['reply_text'] = ' '.join(r)
bundle['context_id'] = torch.LongTensor(self.vocab.toks2idx(c, self.src_len_size))
bundle['reply_id'] = torch.LongTensor(self.vocab.toks2idx(r, self.tgt_len_size))
bundle['context_l'] = bundle['context_id'].shape[0]
bundle['reply_l'] = bundle['reply_id'].shape[0]
self.data.append(bundle)
print(f'[!] {mode} dataset init over, size: {len(self.data)}')
print(f'[!] example:')
example = random.choice(self.data)
print(f'CTX: {example["context_text"]}')
print(f'REF: {example["reply_text"]}')
def __getitem__(self, i):
bundle = self.data[i]
cid, cid_l, rid, rid_l = bundle['context_id'], \
bundle['context_l'], bundle['reply_id'], bundle['reply_l']
return cid, cid_l, rid, rid_l
def __len__(self):
return len(self.data)
class BERTNLIDataset(Dataset):
'''
BERT NLI Datset for Chinese
'''
def __init__(self, path, max_len=300, vocab_file='data/vocab/vocab_small'):
data = read_json_data(path)
self.vocab = BertTokenizer(vocab_file=vocab_file)
self.max_len = max_len
self.pp_path = f'{os.path.splitext(path)[0]}.pkl'
if os.path.exists(self.pp_path):
with open(self.pp_path, 'rb') as f:
self.data = pickle.load(f)
print(f'[!] load preprocessed file from {self.pp_path}')
# Dataset object must return None
return None
self.data = []
d_ = []
label_map = {'contradiction': 0, 'neutral': 1, 'entailment': 2}
for i in data:
s1, s2, label = i['sentence1'], i['sentence2'], i['gold_label']
d_.append((s1, s2, label))
for item in tqdm(d_):
bundle = {}
s1, s2, label = item
s = f'{s1} [SEP] {s2}'
sid = self.vocab.encode(s)
bundle['sid'] = torch.LongTensor(sid)
bundle['label'] = label_map[label]
self.data.append(bundle)
def __len__(self):
return len(self.data)
def __getitem__(self, i):
bundle = self.data[i]
return bundle
def save_pickle(self):
with open(self.pp_path, 'wb') as f:
pickle.dump(self.data, f)
print(f'[!] save dataset into {self.pp_path}')
class BERTLOGICDataset(Dataset):
'''
BERT LOGIC Dataset: similar with the BERTIRDataset
The negative samples are chosen by the IR systems, which have the high semantic coherence but low logic coherence.
The whole `train_retrieval` corpus is huge, only use 500000 samples
'''
def __init__(self, path, mode='train', max_len=300, samples=1, vocab_file='data/vocab/vocab_small'):
self.mode = mode
self.max_len = max_len
# data = read_csv_data(path)
data = read_text_data(path)
data = random.sample(data, 500000)
# context and response are all the negative samples
contexts = [i[0] for i in data]
self.vocab = BertTokenizer(vocab_file=vocab_file)
self.pp_path = f'{os.path.splitext(path)[0]}_logic.pkl'
if os.path.exists(self.pp_path):
with open(self.pp_path, 'rb') as f:
self.data = pickle.load(f)
print(f'[!] load preprocessed file from {self.pp_path}')
return None
self.data = []
self.max_len = max_len
self.es = Elasticsearch()
# collect the data samples
d_ = []
with tqdm(total=len(data)) as pbar:
idx, batch_size = 0, 1000
while idx < len(data):
contexts = [i[0] for i in data[idx:idx+batch_size]]
responses = [i[1] for i in data[idx:idx+batch_size]]
negatives = generate_logic_negative_samples(
contexts, self.es, "retrieval_chatbot",
samples=samples)
for each in zip(contexts, responses, negatives):
d_.append((each[0], [each[1]] + each[2]))
idx += batch_size
pbar.update(batch_size)
if mode in ['train', 'dev']:
# concatenate the context and the response
for item in tqdm(d_):
context, response = item
context_id = self.vocab.encode(context)
for idx, r in enumerate(response):
bundle = dict()
rid = self.vocab.encode(r)
bundle['context_id'] = context_id + rid[1:]
bundle['label'] = 1 if idx == 0 else 0
self.data.append(bundle)
else:
for item in tqdm(d_):
context, response = item
context_id = self.vocab.encode(context)
res_ids = [self.vocab.encode(i) for i in response]
bundle = dict()
bundle['context_id'] = context_id
bundle['reply_id'] = res_ids
bundle['label'] = [1] + [0] * samples
self.data.append(bundle)
def __len__(self):
return len(self.data)
def __getitem__(self, i):
bundle = self.data[i]
if self.mode in ['train', 'dev']:
ids = torch.LongTensor(bundle['context_id'][-self.max_len:])
else:
ids = []
for i in range(len(bundle['reply_id'])):
p = bundle['context_id'] + bundle['reply_id'][i][1:]
ids.append(torch.LongTensor(p[-self.max_len:]))
return ids, bundle['label']
def save_pickle(self):
with open(self.pp_path, 'wb') as f:
pickle.dump(self.data, f)
print(f'[!] save dataset into {self.pp_path}')
class BERTIRMultiDataset(Dataset):
'''
training samples (positive:negative): 1:1
test samples (positive:negative) 1:9
turn_size controls the turn_size of the multi-turn conversations
'''
def __init__(self, path, mode='train', max_len=300, samples=9, turn_size=3, vocab_file='data/vocab/vocab_small'):
self.mode = mode
data = read_text_data(path)
responses = [i[-1] for i in data]
self.vocab = BertTokenizer.from_pretrained('bert-base-chinese')
self.pp_path = f'{os.path.splitext(path)[0]}_multiir.pkl'
if os.path.exists(self.pp_path):
with open(self.pp_path, 'rb') as f:
self.data = pickle.load(f)
print(f'[!] load preprocessed file from {self.pp_path}')
return None
self.data = []
sep_id = self.vocab.convert_tokens_to_ids('[SEP]')
self.max_len = max_len
# collect the samples
d_ = []
for context, response in data:
negative = generate_negative_samples(response, responses, samples=1)
d_.append((context, [response] + negative))
if mode in ['train', 'dev']:
for contexts, responses in tqdm(d_):
# recode the [SEP] index after tokenize
if contexts.count('[SEP]') < turn_size:
continue
contexts_id = self.vocab.encode(contexts)
for idx, r in enumerate(responses):
bundle = dict()
rid = self.vocab.encode(r)[1:] # without [CLS]
ids = contexts_id + rid
if len(ids) > 512:
continue
bundle['ids'] = ids
bundle['label'] = 1 if idx == 0 else 0
bundle['turn_length'] = bundle['ids'].count(sep_id)
sep_index = (np.array(ids) == sep_id).astype(np.int).nonzero()[0]
sep_chunk_size, last_sep = [], 0
for sep_idx in sep_index:
sep_chunk_size.append(sep_idx - last_sep + 1)
last_sep = sep_idx + 1
bundle['sep_index'] = sep_chunk_size
self.data.append(bundle)
else:
for item in tqdm(d_):
contexts, responses = item
contexts_id = [self.vocab.encode(context)[-self.max_len:] for context in contexts]
res_ids = [self.vocab.encode(i)[-self.max_len] for i in responses]
bundle = dict()
bundle['ids'] = contexts_id
bundle['replys_id'] = res_ids
bundle['label'] = [1] + [0] * samples
bundle['turn_length'] = len(bundle['ids']) + 1
self.data.append(bundle)
self.data = sorted(self.data, key=lambda i:i['turn_length'])
print(f'[!] read the processed raw data from {path} over')
def __len__(self):
return len(self.data)
def save_pickle(self):
with open(self.pp_path, 'wb') as f:
pickle.dump(self.data, f)
print(f'[!] save the dataset into {self.pp_path}')
def __getitem__(self, i):
return self.data[i]
class BERTIRMultiDataLoader:
def __init__(self, data, shuffle=True, batch_size=16):
self.data = data
self.data_size = len(data)
self.shuffle = shuffle
self.batch_size = batch_size
self.lengths = [i['turn_length'] for i in self.data.data]
self.index, self.pad = 0, 0
def __iter__(self):
return self
def __len__(self):
return self.data_size
def __next__(self):
if self.index >= self.data_size:
self.index = 0
raise StopIteration
else:
idx, start1 = self.index, self.lengths[self.index]
for l in self.lengths[self.index:self.index+self.batch_size]:
if l != start1:
break
idx += 1
batch = self.data[self.index:idx] # batch*[turn, seq]
if self.shuffle:
random.shuffle(batch)
self.index = idx
if self.data.mode in ['train', 'dev']:
# construct the tensor
# batch: batch*[turn, seq] -> turn*[batch, seq] with the [PAD]
ids = [torch.LongTensor(i['ids']) for i in batch]
ids = pad_sequence(ids, batch_first=True, padding_value=self.pad) # [batch, seq]
sep_index = [i['sep_index'] for i in batch]
labels = torch.LongTensor([i['label'] for i in batch])
# rest: turn_size*[batch, seq]; labels: [batch]
if torch.cuda.is_available():
ids = ids.cuda()
labels = labels.cuda()
return ids, labels, sep_index
else:
rest, turn_size = [], len(batch[0])
contexts, responses, labels = [item['ids'] for item in batch], [item['replys_ids'] for item in batch], [item['label'] for item in batch]
sentences, labels = [], []
for i in range(len(batch)):
for r in range(len(responses)):
item = contexts[i] + [responses[i][j]]
sentences.append(item)
labels.extend(batch[i]['label'])
# sentences: batch*samples; labels: batch*samples
rest = []
for i in range(turn_size):
n_batch = [torch.LongTensor(item[i]) for item in sentences]
n_batch = pad_sequence(n_batch, batch_first=True, padding_value=self.pad)
if torch.cuda.is_available():
n_batch = n_batch.cuda()
rest.append(n_batch)
if torch.cuda.is_available():
labels = torch.LongTensor(labels).cuda()
return rest, labels
class BERTMCDataset(Dataset):
def __init__(self, path, mode='train', src_min_length=20, tgt_min_length=15,
max_len=300, samples=1, vocab_file='data/vocab/vocab_small',
model_type='mc', harder=False):
self.mode = mode
self.max_len = max_len
data = read_text_data(path)
responses = [i[1] for i in data]
self.vocab = BertTokenizer.from_pretrained('bert-base-chinese')
if mode == 'test':
# load the test dataset generated by the BERTIRDataset directly
self.pp_path = f'{os.path.splitext(path)[0]}_hard.pkl'
else:
self.pp_path = f'{os.path.splitext(path)[0]}_{model_type}.pkl'
if os.path.exists(self.pp_path):
with open(self.pp_path, 'rb') as f:
self.data = pickle.load(f)
print(f'[!] load preprocessed file from {self.pp_path}')
return None
self.data, d_ = [], []
for i in tqdm(data):
context, response = i[0], i[1]
negative = generate_negative_samples(response, responses, samples=samples)
d_.append((context, [response] + negative))
if mode in ['train', 'dev']:
for context, responses in tqdm(d_):
response, negative = responses
context_id = self.vocab.encode(context)
response_id = self.vocab.encode(response)
negative_id = self.vocab.encode(negative)
choice1 = context_id + response_id[1:]
choice2 = context_id + negative_id[1:]
bundle = dict()
if random.random() < 0.5:
bundle['ids'] = [choice1[-self.max_len:], choice2[-self.max_len:]]
bundle['label'] = 0
else:
bundle['ids'] = [choice2[-self.max_len:], choice1[-self.max_len:]]
bundle['label'] = 1
self.data.append(bundle)
else:
for context, response in tqdm(d_):
context_id = self.vocab.encode(context)
# delete the [CLS] token of the response sequence for combining
ids = [self.vocab.encode(r) for r in response]
bundle = dict()
bundle['context_id'] = context_id
bundle['reply_id'] = ids
bundle['label'] = [1] + [0] * samples
self.data.append(bundle)
def __len__(self):
return len(self.data)
def __getitem__(self, i):
bundle = self.data[i]
if self.mode in ['train', 'dev']:
return bundle
else:
ids = []
for i in range(len(bundle['reply_id'])):
p = bundle['context_id'] + bundle['reply_id'][i][1:]
ids.append(torch.LongTensor(p[-self.max_len:]))
return ids
def save_pickle(self):
with open(self.pp_path, 'wb') as f:
pickle.dump(self.data, f)
print(f'[!] save dataset into {self.pp_path}')
class RetrievalDataset(Dataset):
'''Only for Douban300w and E-Commerce datasets; test batch size must be 1'''
def __init__(self, path, mode='train', max_len=300, lang='zh'):
self.mode = mode
self.max_len = max_len
if lang == 'zh':
self.vocab = BertTokenizer.from_pretrained('bert-base-chinese')
else:
self.vocab = BertTokenizer.from_pretrained('bert-base-uncased')
self.pad = self.vocab.convert_tokens_to_ids('[PAD]')
self.pp_path = f'{os.path.splitext(path)[0]}_irbi.pt'
if os.path.exists(self.pp_path):
self.data = torch.load(self.pp_path)
print(f'[!] load preprocessed file from {self.pp_path}')
return None
if mode == 'train':
data = read_retrieval_data_train(path, lang=lang)
else:
name = os.path.split(path)[-1]
samples = 10 if name == 'test.txt' else int(name[5:-4])
data = read_retrieval_data_test(path, samples=samples, lang=lang)
self.data = []
if mode in ['train', 'dev']:
contexts = [i[0] for i in data]
responses = [i[1] for i in data]
for context, response in tqdm(list(zip(contexts, responses))):
item = self.vocab.batch_encode_plus([context, response])
cid, rid = item['input_ids']
cid, rid = self._length_limit(cid), self._length_limit(rid)
self.data.append({'cid': cid, 'rid': rid})
else:
for context, session in tqdm(data):
labels, responses = [i[0] for i in session], [i[1] for i in session]
item = self.vocab.batch_encode_plus([context] + responses)['input_ids']
cid, rid = item[0], item[1:]
cid = self._length_limit(cid)
rids = [self._length_limit(i) for i in rid]
self.data.append({'cid': cid, 'rids': rids, 'labels': labels})
def _length_limit(self, ids):
if len(ids) > self.max_len:
ids = [ids[0]] + ids[-(self.max_len-1):]
return ids
def __len__(self):
return len(self.data)
def __getitem__(self, i):
bundle = self.data[i]
if self.mode in ['train', 'dev']:
cid = torch.LongTensor(bundle['cid'])
rid = torch.LongTensor(bundle['rid'])
return cid, rid
else:
cid = torch.LongTensor(bundle['cid'])
rids = [torch.LongTensor(i) for i in bundle['rids']]
return cid, rids
def save_pickle(self):
data = torch.save(self.data, self.pp_path)
print(f'[!] save dataset into {self.pp_path}')
def generate_mask(self, ids):
attn_mask_index = ids.nonzero().tolist()
attn_mask_index_x, attn_mask_index_y = [i[0] for i in attn_mask_index], [i[1] for i in attn_mask_index]
attn_mask = torch.zeros_like(ids)
attn_mask[attn_mask_index_x, attn_mask_index_y] = 1
return attn_mask
def collate(self, batch):
if self.mode in ['train', 'dev']:
cid, rid = [i[0] for i in batch], [i[1] for i in batch]
cid = pad_sequence(cid, batch_first=True, padding_value=self.pad)
rid = pad_sequence(rid, batch_first=True, padding_value=self.pad)
cid_mask = self.generate_mask(cid)
rid_mask = self.generate_mask(rid)
if torch.cuda.is_available():
cid, rid, cid_mask, rid_mask = cid.cuda(), rid.cuda(), cid_mask.cuda(), rid_mask.cuda()
return cid, rid, cid_mask, rid_mask
else:
assert len(batch) == 1, f'[!] test bacth size must be 1'
cid, rids = batch[0]
rids = pad_sequence(rids, batch_first=True, padding_value=self.pad)
rids_mask = self.generate_mask(rids)
if torch.cuda.is_available():
cid, rids, rids_mask = cid.cuda(), rids.cuda(), rids_mask.cuda()
return cid, rids, rids_mask
class RURetrievalDataset(Dataset):
'''Only for Douban300w and E-Commerce datasets; test batch size must be 1'''
def __init__(self, path, mode='train', max_len=300, max_turn_size=10):
self.mode = mode
self.max_len = max_len
if mode == 'train':
data = read_retrieval_data_sep_train(path, max_len=max_len, max_turn_size=max_turn_size)
else:
data = read_retrieval_data_sep_test(path, max_len=max_len, max_turn_size=max_turn_size)
self.vocab = BertTokenizer.from_pretrained('bert-base-chinese')
self.pad = self.vocab.convert_tokens_to_ids('[PAD]')
self.pp_path = f'{os.path.splitext(path)[0]}_ruirbi.pt'
if os.path.exists(self.pp_path):
self.data = torch.load(self.pp_path)
print(f'[!] load preprocessed file from {self.pp_path}')
return None
self.data = []
if mode in ['train', 'dev']:
contexts = [i[0] for i in data]
responses = [i[1] for i in data]
for context, response in tqdm(list(zip(contexts, responses))):
item = self.vocab.batch_encode_plus(context + [response])['input_ids']
cid, rid = item[:-1], item[-1]
cid, rid = [self._length_limit(i) for i in cid], self._length_limit(rid)
self.data.append({'cid': cid, 'cid_length': len(cid), 'rid': rid})
else:
for context, session in tqdm(data):
labels, responses = [i[0] for i in session], [i[1] for i in session]
context_length = len(context)
item = self.vocab.batch_encode_plus(context + responses)['input_ids']
cid, rid = item[:context_length], item[context_length:]
cid = [self._length_limit(i) for i in cid]
rids = [self._length_limit(i) for i in rid]
self.data.append({'cid': cid, 'cid_length': len(cid), 'rids': rids, 'labels': labels})
def _length_limit(self, ids):
if len(ids) > self.max_len:
ids = [ids[0]] + ids[-(self.max_len-1):]
return ids
def __len__(self):
return len(self.data)
def __getitem__(self, i):
bundle = self.data[i]
if self.mode in ['train', 'dev']:
cid = [torch.LongTensor(i) for i in bundle['cid']]
rid = torch.LongTensor(bundle['rid'])
turn_length = bundle['cid_length']
return cid, rid, turn_length
else:
cid = [torch.LongTensor(i) for i in bundle['cid']]
rids = [torch.LongTensor(i) for i in bundle['rids']]
turn_length = bundle['cid_length']
return cid, rids, turn_length
def save_pickle(self):
data = torch.save(self.data, self.pp_path)
print(f'[!] save dataset into {self.pp_path}')
def generate_mask(self, ids):
attn_mask_index = ids.nonzero().tolist()
attn_mask_index_x, attn_mask_index_y = [i[0] for i in attn_mask_index], [i[1] for i in attn_mask_index]
attn_mask = torch.zeros_like(ids)
attn_mask[attn_mask_index_x, attn_mask_index_y] = 1
return attn_mask
def collate(self, batch):
if self.mode in ['train', 'dev']:
cid, rid, turn_length = [i[0] for i in batch], [i[1] for i in batch], [i[2] for i in batch]
cid = list(chain(*cid))
cid = pad_sequence(cid, batch_first=True, padding_value=self.pad)
rid = pad_sequence(rid, batch_first=True, padding_value=self.pad)
cid_mask = self.generate_mask(cid)
rid_mask = self.generate_mask(rid)
if torch.cuda.is_available():
cid, cid_mask, rid, rid_mask = cid.cuda(), cid_mask.cuda(), rid.cuda(), rid_mask.cuda()
return cid, turn_length, rid, cid_mask, rid_mask
else:
assert len(batch) == 1, f'[!] test batch size must be 1'
cid, rids, _ = batch[0]
cid = pad_sequence(cid, batch_first=True, padding_value=self.pad) # [T, S]
cid_mask = self.generate_mask(cid)