-
Notifications
You must be signed in to change notification settings - Fork 36
/
data.py
2024 lines (1803 loc) · 95.5 KB
/
data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
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 os
import json
import re
import random
from typing import Tuple, List
import torch
import pandas as pd
from tqdm import tqdm
from torch.utils.data import Dataset
from torch.nn.utils.rnn import pad_sequence
import torch.nn.functional as F
from transformers import PreTrainedTokenizerBase
from src.utils import logger, RESOURCE_PATH
from src.utils.modeling_utils import _prepare_decoder_attention_mask, qwen_make_context
from src.utils.file_utils import print_rank_0
def chatglm3_encode(tokenizer: PreTrainedTokenizerBase,
query: str,
label: str = None,
system: str = "",
max_length: int = 1024,
is_prefix: bool = True
) -> Tuple[List[int], List[int], List[int]]:
'''Use chatglm3 tokenizer to encode prompt + label with "longest_first" truncation strategy
:param tokenizer:
:param prompt:
:param label:
:param system:
:param max_length:
:return:
'''
prefix_tokens = tokenizer.get_prefix_tokens()
role_tokens_1 = [tokenizer.get_command(f"<|user|>")] + tokenizer.encode(f"\n", add_special_tokens=False)
# Process `system` and `query`
if is_prefix:
system_ids = tokenizer.encode(system + "\n\n", add_special_tokens=False) if len(system) > 0 else []
query_ids = tokenizer.encode(" " + query, add_special_tokens=False)[1:]
else:
system_ids = tokenizer.encode(" \n\n" + system, add_special_tokens=False)[1:] if len(system) > 0 else []
query_ids = tokenizer.encode(query, add_special_tokens=False)
# Process `label`
role_tokens_2 = [tokenizer.get_command(f"<|assistant|>")]
if label is not None:
label_ids = tokenizer.encode(label, add_special_tokens=False)
end_tokens = [tokenizer.get_command("<eos>")]
else:
label_ids = []
end_tokens = []
# Remove overflowing tokens
num_tokens_to_remove = len(prefix_tokens) + len(role_tokens_1) + len(query_ids) + len(system_ids) + \
len(role_tokens_2) + len(label_ids) + len(end_tokens) - max_length
if num_tokens_to_remove > 0:
for _ in range(num_tokens_to_remove):
if len(query_ids) + len(system_ids) > len(label_ids) and len(query_ids) > 0:
query_ids.pop()
elif len(label_ids) > 0:
label_ids.pop()
else:
logger.warn("removing system tokens due to tokens overflowing")
system_ids.pop()
if label is not None:
label_ids += end_tokens
else:
if label is not None:
label_ids += end_tokens
label_ids += [tokenizer.pad_token_id] * -num_tokens_to_remove
if is_prefix:
prompt_ids = prefix_tokens + role_tokens_1 + system_ids + query_ids + role_tokens_2
else:
prompt_ids = prefix_tokens + role_tokens_1 + query_ids + system_ids + role_tokens_2
input_ids = prompt_ids + label_ids
labels = [tokenizer.pad_token_id] * len(prompt_ids) + label_ids
assert len(input_ids) == len(labels) == max_length
return input_ids, labels, prompt_ids
def chatglm2_encode(tokenizer: PreTrainedTokenizerBase,
query: str,
label: str = None,
system: str = "",
max_length: int = 1024,
is_prefix: bool = True
) -> Tuple[List[int], List[int], List[int]]:
'''Use chatglm2 tokenizer to encode prompt + label with "longest_first" truncation strategy
:param tokenizer:
:param prompt:
:param label:
:param system:
:param max_length:
:return:
'''
gmask_id = tokenizer.get_command("[gMASK]")
sop_id = tokenizer.get_command("sop")
eop_id = tokenizer.get_command("eop")
# [Round {1}]\n\n问:
ids1 = [790, 30951, 517, 30910, 30939, 30996, 13, 13, 54761, 31211]
# \n\n答:
ids2 = [13, 13, 55437, 31211]
if len(system) > 0:
if is_prefix:
system_ids = tokenizer.encode(" " + system + "\n\n", add_special_tokens=False)[1:]
else:
system_ids = tokenizer.encode(" \n\n" + system, add_special_tokens=False)[1:]
else:
system_ids = []
query_ids = tokenizer.encode(" " + query, add_special_tokens=False)[1:]
if label is not None:
label_ids = tokenizer.encode(label, add_special_tokens=False)
num_special_tokens = 3
else:
label_ids = []
num_special_tokens = 2
num_tokens_to_remove = len(ids1) + len(query_ids) + len(system_ids) + len(ids2) + \
len(label_ids) + num_special_tokens - max_length
if num_tokens_to_remove > 0:
for _ in range(num_tokens_to_remove):
if len(query_ids) + len(system_ids) > len(label_ids) and len(query_ids) > 0:
query_ids.pop()
elif len(label_ids) > 0:
label_ids.pop()
else:
logger.warn("removing system tokens due to tokens overflowing")
system_ids.pop()
if label is not None:
label_ids += [eop_id]
else:
if label is not None:
label_ids += [eop_id]
label_ids += [tokenizer.pad_token_id] * -num_tokens_to_remove
if is_prefix:
prompt_ids = [gmask_id, sop_id] + ids1 + system_ids + query_ids + ids2
else:
prompt_ids = [gmask_id, sop_id] + ids1 + query_ids + system_ids + ids2
input_ids = prompt_ids + label_ids
labels = [tokenizer.pad_token_id] * len(prompt_ids) + label_ids
assert len(input_ids) == len(labels) == max_length
return input_ids, labels, prompt_ids
class DataCollatorReward:
def __call__(self, data):
has_attention_mask = 'attention_mask' in data[0]
batch = {
"chosen_input_ids": torch.stack([f['input_ids'] for f in data]),
"chosen_attention_mask": torch.stack([f['attention_mask'] for f in data]) if has_attention_mask else None,
# "input_ids": torch.cat([f[0] for f in data] + [f[2] for f in data]),
# "attention_mask": torch.cat([f[1] for f in data] + [f[3] for f in data]),
# "labels": torch.tensor([0] * len(data) + [1] * len(data))
}
return batch
class DataCollatorRLHF:
def __init__(self, max_token_len, inference_tp_size):
self.max_token_len = max_token_len
self.inference_tp_size = inference_tp_size
def __call__(self, data):
batch = {}
pad_token_id = data[-1][-1]
prompt = pad_sequence([f[0] for f in data],
padding_value=pad_token_id,
batch_first=True)
prompt_mask = pad_sequence([f[1] for f in data],
padding_value=0,
batch_first=True)
### make sure the final ouput is a seqence of 2**?
length = prompt.size()[-1]
pad_length = self.max_token_len - length
if pad_length > 0:
batch["prompt"] = F.pad(prompt,
pad=(pad_length, 0),
mode='constant',
value=pad_token_id)
batch["prompt_att_mask"] = F.pad(prompt_mask,
pad=(pad_length, 0),
mode='constant',
value=0)
else:
batch["prompt"] = prompt
batch["prompt_att_mask"] = prompt_mask
batch["prompt"] = batch["prompt"].flip(1)
batch["prompt_att_mask"] = batch["prompt_att_mask"].flip(1)
return batch
class PretrainDataset(Dataset):
def __init__(self, args, filename, tokenizer, concat_samples=True):
self.args = args
self.tokenizer = tokenizer
self.concat_samples = concat_samples
self.model_name_or_path = args.model_name_or_path if hasattr(args,
"model_name_or_path") else args.actor_model_path
self.post_list = self.load_dataset(filename)
for k in range(5):
print_rank_0(f"PretrainDataset sample-{k}\n: {self.post_list[k]}")
def __len__(self):
return len(self.post_list)
def __getitem__(self, idx):
data = self.post_list[idx]
if not self.concat_samples:
prompt = data['prompt']
label = data.get('label', None)
if "glm" in self.model_name_or_path.lower() and "chatglm" not in self.model_name_or_path.lower():
encoded_prompt = self.tokenizer(prompt, self.tokenizer.mask_token)
prompt_length = len(encoded_prompt['input_ids'])
label_length = len(self.tokenizer.tokenize(label)) + 1
if prompt_length + label_length > self.args.max_length:
num_tokens_to_remove = prompt_length + label_length - self.args.max_length
for _ in range(num_tokens_to_remove):
if prompt_length > label_length:
prompt_length -= 1
else:
label_length -= 1
else:
label_length = self.args.max_length - prompt_length
assert prompt_length > 0
assert label_length > 0
assert prompt_length + label_length == self.args.max_length
encoded_dict = self.tokenizer(prompt, self.tokenizer.mask_token,
max_length=prompt_length,
truncation="only_first",
return_tensors="pt",
return_attention_mask=True,
return_token_type_ids=False)
encoded_dict = self.tokenizer.build_inputs_for_generation(encoded_dict, targets=label,
max_gen_length=label_length, padding=True)
return {
"input_ids": encoded_dict['input_ids'][0],
"position_ids": encoded_dict['position_ids'][0],
"attention_mask": encoded_dict['attention_mask'][0],
"labels": encoded_dict['labels'][0],
}
else:
if "chatglm2" in self.model_name_or_path.lower():
prompt = f"[Round {1}]\n\n问:{prompt}\n\n答:"
label = label
elif "chatglm" in self.model_name_or_path.lower():
prompt = f"[Round {0}]\n问:{prompt}\n答:"
label = label
elif "vicuna" in self.model_name_or_path.lower():
prompt += "\n\n" + label
label = None
else:
label = None
encoded_dict = self.tokenizer(prompt, label,
max_length=self.args.max_length,
truncation="longest_first",
padding="max_length",
return_token_type_ids=False,
return_tensors="pt", )
if "pangu" in self.model_name_or_path.lower():
return {
"input_ids": encoded_dict['input_ids'],
"attention_mask": encoded_dict['attention_mask'],
"labels": encoded_dict['input_ids'],
}
else:
result = {
"input_ids": encoded_dict['input_ids'][0],
"labels": encoded_dict['input_ids'][0],
}
if 'attention_mask' in encoded_dict:
result["attention_mask"] = encoded_dict['attention_mask'][0]
return result
else:
eos_ids = data['eos_ids']
input_ids = data['input_ids']
combined_attention_mask = torch.full((self.args.max_length, self.args.max_length),
torch.tensor(torch.finfo(torch.float16).min))
for i in range(len(eos_ids) - 1):
attention_mask = torch.ones((1, eos_ids[i + 1] - eos_ids[i]), dtype=torch.long)
attention_mask = _prepare_decoder_attention_mask(attention_mask, attention_mask.shape,
input_embeds=torch.ones(1, dtype=torch.float16,
device="cpu"),
past_key_values_length=0)
logger.debug(f"{i}-th sample, shape: {attention_mask.shape}, attention_mask: {attention_mask}")
combined_attention_mask[eos_ids[i]:eos_ids[i + 1], eos_ids[i]:eos_ids[i + 1]] = attention_mask
logger.debug(f"shape: {combined_attention_mask.shape}, combined_attention_mask: {combined_attention_mask}")
if "chatglm2" in self.model_name_or_path.lower():
return {
"input_ids": input_ids,
"labels": input_ids,
"full_attention_mask": combined_attention_mask,
}
else:
return {
"input_ids": input_ids,
"labels": input_ids,
"attention_mask": combined_attention_mask,
}
def load_dataset(self, filename):
discard = 0
datasets = []
with open(filename, "r", encoding="utf-8") as f:
data = []
eos_ids = [0]
length = 0
for i, line in tqdm(enumerate(f), desc=f"Loading {os.path.basename(filename)}"):
item = json.loads(line)
prompt = str(item['prompt'])
label = item.get('label', None)
if len(prompt) <= 0:
discard += 1
continue
if not self.concat_samples:
datasets.append({"prompt": prompt, "label": label})
else:
if "chatglm2" not in self.model_name_or_path.lower():
assert "glm" not in self.model_name_or_path.lower(), \
"Concatenating samples for GLM or ChatGLM not implemented yet"
if "chatglm2" in self.model_name_or_path.lower():
prompt = f"[Round {1}]\n\n问:{prompt}\n\n答:"
else:
prompt = prompt if label is None else "\n\n".join((prompt, label))
label = None
token_ids = self.tokenizer.encode(prompt, label,
max_length=self.args.max_length - length,
truncation="longest_first")
if length + len(token_ids) < self.args.max_length:
data.extend(token_ids)
length += len(token_ids)
eos_ids.append(length)
else:
data.extend(token_ids[:(self.args.max_length - length)])
eos_ids.append(self.args.max_length)
datasets.append({"input_ids": data, "eos_ids": eos_ids})
data = []
eos_ids = [0]
length = 0
print_rank_0(
f"Finished loading {os.path.basename(filename)}, # samples: {len(datasets)}, # discarded: {discard}")
return datasets
class SFTDataset(Dataset):
def __init__(self, args, filename, tokenizer, concat_samples=True):
self.args = args
self.tokenizer = tokenizer
self.concat_samples = concat_samples
self.model_name_or_path = args.model_name_or_path if hasattr(args,
"model_name_or_path") else args.actor_model_path
self.post_list = self.load_dataset(filename)
for k in range(5):
print_rank_0(f"SFTDataset sample-{k}\n: {self.post_list[k]}")
def __len__(self):
return len(self.post_list)
def __getitem__(self, idx):
data = self.post_list[idx]
if not self.concat_samples:
prompt = data['prompt']
label = data['label']
prefix = data['prefix']
system = data['system']
if "glm" in self.model_name_or_path.lower() and "chatglm" not in self.model_name_or_path.lower():
encoded_prompt = self.tokenizer(prompt, prefix + self.tokenizer.mask_token)
prompt_length = len(encoded_prompt['input_ids'])
label_length = len(self.tokenizer.tokenize(label)) + 1
if prompt_length + label_length > self.args.max_length:
num_tokens_to_remove = prompt_length + label_length - self.args.max_length
for _ in range(num_tokens_to_remove):
if prompt_length > label_length:
prompt_length -= 1
else:
label_length -= 1
else:
label_length = self.args.max_length - prompt_length
assert prompt_length > 0
assert label_length > 0
assert prompt_length + label_length == self.args.max_length
encoded_dict = self.tokenizer(prompt, prefix + self.tokenizer.mask_token,
max_length=prompt_length,
truncation="only_first",
return_tensors="pt",
return_attention_mask=True,
return_token_type_ids=False)
encoded_dict = self.tokenizer.build_inputs_for_generation(encoded_dict, targets=label,
max_gen_length=label_length, padding=True)
return {
"input_ids": encoded_dict['input_ids'][0],
"position_ids": encoded_dict['position_ids'][0],
"attention_mask": encoded_dict['attention_mask'][0],
"labels": encoded_dict['labels'][0],
}
elif "pangu" in self.model_name_or_path.lower():
label = prefix + label
encoded_dict = self.tokenizer(prompt, label,
max_length=self.args.max_length,
truncation="longest_first",
padding="max_length",
return_token_type_ids=False,
return_tensors="pt", )
return {
"input_ids": encoded_dict['input_ids'],
"attention_mask": encoded_dict['attention_mask'],
"labels": encoded_dict['input_ids'],
}
elif "chatglm3" in self.model_name_or_path.lower():
input_ids, labels, _ = chatglm3_encode(self.tokenizer, prompt, label, system, self.args.max_length)
return {
"input_ids": torch.tensor(input_ids, dtype=torch.long),
# "attention_mask": torch.ones(len(input_ids), dtype=torch.long),
"labels": torch.tensor(labels, dtype=torch.long),
}
elif "chatglm2" in self.model_name_or_path.lower():
input_ids, labels, _ = chatglm2_encode(self.tokenizer, prompt, label, system, self.args.max_length)
# gmask_id = self.tokenizer.get_command("[gMASK]")
# sop_id = self.tokenizer.get_command("sop")
# eop_id = self.tokenizer.get_command("eop")
# # [Round {1}]\n\n问:
# ids1 = [790, 30951, 517, 30910, 30939, 30996, 13, 13, 54761, 31211]
# # \n\n答:
# ids2 = [13, 13, 55437, 31211]
# prompt = "\n\n".join((system, prompt))
# prompt_ids = self.tokenizer.encode(" " + prompt, add_special_tokens=False)[1:]
# label_ids = self.tokenizer.encode(label, add_special_tokens=False)
# num_tokens_to_remove = len(ids1) + len(prompt_ids) + len(ids2) + len(label_ids) + 3 - self.args.max_length
# if num_tokens_to_remove > 0:
# for _ in range(num_tokens_to_remove):
# if len(prompt_ids) > len(label_ids):
# prompt_ids.pop()
# else:
# label_ids.pop()
# prompt_ids = [gmask_id, sop_id] + ids1 + prompt_ids + ids2
# label_ids = label_ids + [eop_id]
# else:
# prompt_ids = [gmask_id, sop_id] + ids1 + prompt_ids + ids2
# label_ids = label_ids + [eop_id] + [self.tokenizer.pad_token_id] * -num_tokens_to_remove
# input_ids = prompt_ids + label_ids
# labels = [self.tokenizer.pad_token_id] * len(prompt_ids) + label_ids
# assert len(input_ids) == len(labels) == self.args.max_length
return {
"input_ids": torch.tensor(input_ids, dtype=torch.long),
# "attention_mask": torch.ones(len(input_ids), dtype=torch.long),
"labels": torch.tensor(labels, dtype=torch.long),
}
elif "chatglm" in self.model_name_or_path.lower():
prompt = f"[Round {0}]\n问:{prompt}\n答:"
encoded_dict = self.tokenizer(prompt, label,
max_length=self.args.max_length,
truncation="longest_first",
padding="max_length",
return_token_type_ids=False,
return_tensors="pt", )
return {
"input_ids": encoded_dict['input_ids'][0],
"attention_mask": encoded_dict['attention_mask'][0],
"labels": encoded_dict['input_ids'][0],
}
else:
encoded_dict = self.tokenizer(prompt, label,
max_length=self.args.max_length,
truncation="longest_first",
padding="max_length",
return_token_type_ids=False,
return_tensors="pt", )
result = {
"input_ids": encoded_dict['input_ids'][0],
"labels": encoded_dict['input_ids'][0],
}
if 'attention_mask' in encoded_dict:
result["attention_mask"] = encoded_dict['attention_mask'][0]
return result
else:
eos_ids = data['eos_ids']
input_ids = data['input_ids']
combined_attention_mask = torch.full((self.args.max_length, self.args.max_length),
torch.tensor(torch.finfo(torch.float16).min))
for i in range(len(eos_ids) - 1):
attention_mask = torch.ones((1, eos_ids[i + 1] - eos_ids[i]), dtype=torch.long)
attention_mask = _prepare_decoder_attention_mask(attention_mask, attention_mask.shape,
input_embeds=torch.ones(1, dtype=torch.float16,
device="cpu"),
past_key_values_length=0)
logger.debug(f"{i}-th sample, shape: {attention_mask.shape}, attention_mask: {attention_mask}")
combined_attention_mask[eos_ids[i]:eos_ids[i + 1], eos_ids[i]:eos_ids[i + 1]] = attention_mask
logger.debug(f"shape: {combined_attention_mask.shape}, combined_attention_mask: {combined_attention_mask}")
if "chatglm2" in self.model_name_or_path.lower():
return {
"input_ids": input_ids,
"labels": input_ids,
"full_attention_mask": combined_attention_mask,
}
else:
return {
"input_ids": input_ids,
"labels": input_ids,
"attention_mask": combined_attention_mask,
}
def load_dataset(self, filename):
discard = 0
datasets = []
with open(filename, "r", encoding="utf-8") as f:
data = []
eos_ids = [0]
length = 0
for i, line in tqdm(enumerate(f), desc=f"Loading {os.path.basename(filename)}"):
item = json.loads(line)
data_type = item.get('data_type', "human_generated")
if data_type != "human_generated":
continue
prompt = str(item['prompt'])
label = str(item['answers'][0]['answer'])
score = item['answers'][0]['score']
prefix = item.get('prefix', "")
system = item.get('system', "")
if len(prompt) <= 0 or len(label) <= 0:
discard += 1
continue
if not self.concat_samples:
datasets.append({"prompt": prompt, "label": label, "prefix": prefix, "system": system})
else:
if "chatglm2" not in self.model_name_or_path.lower():
assert "glm" not in self.model_name_or_path.lower(), \
"Concatenating samples for GLM or ChatGLM not implemented yet"
else:
if "chatglm2" in self.model_name_or_path.lower():
prompt = f"[Round {1}]\n\n问:{prompt}\n\n答:"
else:
prompt = prompt if label is None else "\n\n".join((prompt, label))
label = None
token_ids = self.tokenizer.encode(prompt, label,
max_length=self.args.max_length - length,
truncation="longest_first")
if length + len(token_ids) < self.args.max_length:
data.extend(token_ids)
length += len(token_ids)
eos_ids.append(length)
else:
data.extend(token_ids[:(self.args.max_length - length)])
eos_ids.append(self.args.max_length)
datasets.append({"input_ids": data, "eos_ids": eos_ids})
data = []
eos_ids = [0]
length = 0
print_rank_0(
f"Finished loading {os.path.basename(filename)}, # samples: {len(datasets)}, # discarded: {discard}")
return datasets
class PairwiseDataset(Dataset):
def __init__(self, args, filename, tokenizer):
self.pairs = self.load_dataset(filename)
self.args = args
self.tokenizer = tokenizer
for k in range(5):
print_rank_0(f"PairwiseDataset sample-{k}\n: {self.pairs[k]}")
def __len__(self):
return len(self.pairs)
def __getitem__(self, idx):
pair = self.pairs[idx]
prompt = pair["prompt"]
chosen_answer = pair["chosen_answer"]
rejected_answer = pair["rejected_answer"]
prefix = pair['prefix']
system = pair['system']
if "pangu" in self.args.model_name_or_path.lower():
chosen_encodings_dict = self.tokenizer(prompt, prefix + chosen_answer, max_length=self.args.max_length,
truncation="longest_first", padding="max_length",
return_tensors="pt",
return_token_type_ids=False)
rejected_encodings_dict = self.tokenizer(prompt, prefix + rejected_answer, max_length=self.args.max_length,
truncation="longest_first", padding="max_length",
return_tensors="pt",
return_token_type_ids=False)
return {
"chosen_input_ids": chosen_encodings_dict["input_ids"],
"chosen_attention_mask": chosen_encodings_dict["attention_mask"],
"rejected_input_ids": rejected_encodings_dict["input_ids"],
"rejected_attention_mask": rejected_encodings_dict["attention_mask"],
"labels": rejected_encodings_dict["input_ids"],
}
elif "chatglm3" in self.args.model_name_or_path.lower():
chosen_input_ids, labels, _ = chatglm3_encode(self.tokenizer, prompt, chosen_answer, system,
self.args.max_length)
rejected_input_ids, labels, _ = chatglm3_encode(self.tokenizer, prompt, rejected_answer, system,
self.args.max_length)
return {
"chosen_input_ids": torch.tensor(chosen_input_ids, dtype=torch.long),
"rejected_input_ids": torch.tensor(rejected_input_ids, dtype=torch.long),
"labels": torch.tensor(labels, dtype=torch.long)
}
elif "chatglm2" in self.args.model_name_or_path.lower():
chosen_input_ids, labels, _ = chatglm2_encode(self.tokenizer, prompt, chosen_answer, system,
self.args.max_length)
rejected_input_ids, labels, _ = chatglm2_encode(self.tokenizer, prompt, rejected_answer, system,
self.args.max_length)
return {
"chosen_input_ids": torch.tensor(chosen_input_ids, dtype=torch.long),
"rejected_input_ids": torch.tensor(rejected_input_ids, dtype=torch.long),
"labels": torch.tensor(labels, dtype=torch.long)
}
elif "chatglm" in self.args.model_name_or_path.lower():
prompt = f"[Round {0}]\n问:{prompt}\n答:"
chosen_encodings_dict = self.tokenizer(prompt, chosen_answer, max_length=self.args.max_length,
truncation="longest_first", padding="max_length",
return_tensors="pt")
rejected_encodings_dict = self.tokenizer(prompt, rejected_answer, max_length=self.args.max_length,
truncation="longest_first", padding="max_length",
return_tensors="pt")
return {
"chosen_input_ids": chosen_encodings_dict["input_ids"][0],
"rejected_input_ids": rejected_encodings_dict["input_ids"][0],
"labels": rejected_encodings_dict["input_ids"][0],
}
elif "glm" in self.args.model_name_or_path.lower():
chosen_prompt_length = len(self.tokenizer.tokenize(prompt + prefix)) + 4
rejected_prompt_length = chosen_prompt_length
chosen_answer_length = len(self.tokenizer.tokenize(chosen_answer)) + 1
if chosen_prompt_length + chosen_answer_length > self.args.max_length:
if chosen_prompt_length >= chosen_answer_length:
chosen_prompt_length -= chosen_prompt_length + chosen_answer_length - self.args.max_length
else:
chosen_answer_length -= chosen_prompt_length + chosen_answer_length - self.args.max_length
else:
chosen_answer_length = self.args.max_length - chosen_prompt_length
chosen_encoded_dict = self.tokenizer(prompt, prefix + self.tokenizer.mask_token,
max_length=chosen_prompt_length,
truncation="only_first",
return_tensors="pt",
return_token_type_ids=False)
chosen_encodings_dict = self.tokenizer.build_inputs_for_generation(chosen_encoded_dict,
targets=chosen_answer,
max_gen_length=chosen_answer_length,
padding=True)
rejected_answer_length = len(self.tokenizer.tokenize(rejected_answer)) + 1
if rejected_prompt_length + rejected_answer_length > self.args.max_length:
if rejected_prompt_length >= rejected_answer_length:
rejected_prompt_length -= rejected_prompt_length + rejected_answer_length - self.args.max_length
else:
rejected_answer_length -= rejected_prompt_length + rejected_answer_length - self.args.max_length
else:
rejected_answer_length = self.args.max_length - rejected_prompt_length
rejected_encoded_dict = self.tokenizer(prompt, prefix + self.tokenizer.mask_token,
max_length=rejected_prompt_length,
truncation="only_first",
return_tensors="pt",
return_token_type_ids=False)
rejected_encodings_dict = self.tokenizer.build_inputs_for_generation(rejected_encoded_dict,
targets=rejected_answer,
max_gen_length=rejected_answer_length,
padding=True)
return {
"chosen_input_ids": chosen_encodings_dict["input_ids"][0],
"chosen_attention_mask": chosen_encodings_dict["attention_mask"][0],
"chosen_position_ids": chosen_encodings_dict["position_ids"][0],
"rejected_input_ids": rejected_encodings_dict["input_ids"][0],
"rejected_attention_mask": rejected_encodings_dict["attention_mask"][0],
"rejected_position_ids": rejected_encodings_dict["position_ids"][0],
"labels": rejected_encodings_dict["input_ids"][0],
}
else:
raise ValueError(f"Unsupported model name: {self.args.model_name_or_path}")
@staticmethod
def load_dataset(filename):
discard = 0
pairs = []
with open(filename, "r", encoding="utf-8") as f:
for line in tqdm(f, desc=f"Loading {os.path.basename(filename)}"):
item = json.loads(line)
prompt = str(item['prompt'])
answers = item['answers']
prefix = item.get('prefix', "")
system = item.get('system', "")
chosen_answer, rejected_answer = None, None
for i in range(len(answers) - 1):
answer_1 = str(answers[i]["answer"])
answer_1_score = answers[i]["score"]
answer_2 = str(answers[i + 1]["answer"])
answer_2_score = answers[i + 1]["score"]
if answer_1_score > answer_2_score:
chosen_answer = answer_1
rejected_answer = answer_2
if chosen_answer is not None and rejected_answer is not None \
and len(prompt) > 0 and len(chosen_answer) > 0 and len(rejected_answer) > 0 \
and chosen_answer != rejected_answer:
pair = {
"prompt": prompt,
"prefix": prefix,
"system": system,
"chosen_answer": chosen_answer,
"rejected_answer": rejected_answer
}
pairs.append(pair)
else:
discard += 1
print_rank_0(f"Finished loading {os.path.basename(filename)}, # pairs: {len(pairs)}, # discarded: {discard}")
return pairs
class RLHFDataset(Dataset):
def __init__(self, args, filename, tokenizer):
self.args = args
self.tokenizer = tokenizer
assert tokenizer.padding_side == "left", "In RLHF training, need to set padding_side to 'left'"
self.post_list = self.load_dataset(filename)
for k in range(5):
print_rank_0(f"RLHFDataset sample-{k}\n: {self.post_list[k]}")
def __len__(self):
return len(self.post_list)
def __getitem__(self, idx):
data = self.post_list[idx]
prompt = data['prompt']
prefix = data['prefix']
system = data['system']
if "pangu" in self.args.actor_model_path:
encoded_dict = self.tokenizer(prompt, self.tokenizer.sep_token + prefix,
max_length=self.args.max_prompt_length,
# padding="max_length",
truncation="only_first", add_special_tokens=False,
return_tensors="pt", return_token_type_ids=False)
return {
"input_ids": encoded_dict['input_ids'][0],
"attention_mask": encoded_dict['attention_mask'][0],
# "labels": encoded_dict['input_ids'],
}
elif "chatglm" in self.args.actor_model_path:
prompt = "\n\n".join((system, prompt))
prompt = f"[Round {1}]\n\n问:{prompt}\n\n答:" if "chatglm2" in self.args.actor_model_path else f"[Round {0}]\n问:{prompt}\n答:"
encoded_dict = self.tokenizer(prompt, max_length=self.args.max_prompt_length,
return_tensors="pt", truncation="only_first")
return {
"input_ids": encoded_dict['input_ids'][0],
}
elif "glm" in self.args.actor_model_path:
# encoded_prompt = self.tokenizer(prompt, prefix + self.tokenizer.mask_token)
# prompt_length = len(encoded_prompt['input_ids'])
encoded_dict = self.tokenizer(prompt, prefix + self.tokenizer.mask_token,
max_length=self.args.max_prompt_length,
# padding="max_length",
truncation="only_first",
return_tensors="pt",
return_token_type_ids=False)
encoded_dict = self.tokenizer.build_inputs_for_generation(encoded_dict,
max_gen_length=self.args.max_gen_length,
padding=True)
return {
"input_ids": encoded_dict['input_ids'][0],
"position_ids": encoded_dict['position_ids'][0],
"generation_attention_mask": encoded_dict['generation_attention_mask'][0],
# "labels": encoded_dict['labels'][0],
}
else:
raise ValueError(f"Unsupported model name: {self.args.model_name_or_path}")
@staticmethod
def load_dataset(filename):
discard = 0
datasets = []
with open(filename, "r", encoding="utf-8") as f:
for i, line in tqdm(enumerate(f), desc=f"Loading {os.path.basename(filename)}"):
item = json.loads(line)
data_type = item.get('data_type', "human_generated")
if data_type != "human_generated":
continue
prompt = str(item['prompt'])
prefix = item.get('prefix', "")
system = item.get('system', "")
if len(prompt) <= 0:
discard += 1
continue
datasets.append({"prompt": prompt, "system": system, "prefix": prefix})
print_rank_0(
f"Finished loading {os.path.basename(filename)}, # samples: {len(datasets)}, # discarded: {discard}")
return datasets
class PPODataset:
def __init__(self, max_size, small_batch_size):
self.dataset = []
self.max_size = max_size
self.small_batch_size = small_batch_size
def separate(self):
small_dataset = []
for large_batch in self.dataset:
if type(large_batch) == list or type(large_batch) == tuple:
large_size = len(large_batch[0])
elif type(large_batch) == dict:
large_size = len(large_batch[list(large_batch.keys())[0]])
else:
large_size = len(large_batch)
for i in range(0, large_size, self.small_batch_size):
if type(large_batch) == list or type(large_batch) == tuple:
small_dataset.append(
[x[i:i + self.small_batch_size] for x in large_batch])
elif type(large_batch) == dict:
small_dataset.append({
k: v[i:i + self.small_batch_size] if v is not None else None
for k, v in large_batch.items()
})
else:
small_dataset.append(large_batch[i:i + self.small_batch_size])
self.free()
return small_dataset
def add(self, data):
if len(self.dataset) < self.max_size:
self.dataset.append(data)
if len(self.dataset) == self.max_size:
return self.separate()
else:
return None
else:
raise ValueError(
"The dataset is full but we did not stop it. There is a bug in the code."
)
def free(self):
self.dataset = []
class DPODataset(Dataset):
def __init__(self, args, filename, tokenizer):
self.pairs = self.load_dataset(filename)
self.args = args
self.tokenizer = tokenizer
for k in range(5):
print_rank_0(f"DPODataset sample-{k}\n: {self.pairs[k]}")
def __len__(self):
return len(self.pairs)
def __getitem__(self, idx):
pair = self.pairs[idx]
index = pair["index"]
prompt = pair["prompt"]
chosen_answer = pair["chosen_answer"]
rejected_answer = pair["rejected_answer"]
prefix = pair['prefix']
system = pair['system']
if "pangu" in self.args.model_name_or_path.lower():
chosen_encodings_dict = self.tokenizer(prompt, prefix + chosen_answer, max_length=self.args.max_length,
truncation="longest_first", padding="max_length",
return_tensors="pt",
return_token_type_ids=False)
rejected_encodings_dict = self.tokenizer(prompt, prefix + rejected_answer, max_length=self.args.max_length,
truncation="longest_first", padding="max_length",
return_tensors="pt",
return_token_type_ids=False)
return {
"chosen_input_ids": chosen_encodings_dict["input_ids"],
"chosen_attention_mask": chosen_encodings_dict["attention_mask"],
"rejected_input_ids": rejected_encodings_dict["input_ids"],
"rejected_attention_mask": rejected_encodings_dict["attention_mask"],
"labels": rejected_encodings_dict["input_ids"],
}
elif "chatglm3" in self.args.model_name_or_path.lower():
chosen_input_ids, chosen_labels, _ = chatglm3_encode(self.tokenizer, prompt, chosen_answer, system,
self.args.max_length)
rejected_input_ids, rejected_labels, _ = chatglm3_encode(self.tokenizer, prompt, rejected_answer, system,
self.args.max_length)
return {
"index": torch.tensor(index, dtype=torch.long),
"chosen_input_ids": torch.tensor(chosen_input_ids, dtype=torch.long),
"rejected_input_ids": torch.tensor(rejected_input_ids, dtype=torch.long),
"chosen_labels": torch.tensor(chosen_labels, dtype=torch.long),
"rejected_labels": torch.tensor(rejected_labels, dtype=torch.long)
}
elif "chatglm2" in self.args.model_name_or_path.lower():
chosen_input_ids, chosen_labels, _ = chatglm2_encode(self.tokenizer, prompt, chosen_answer, system,
self.args.max_length)
rejected_input_ids, rejected_labels, _ = chatglm2_encode(self.tokenizer, prompt, rejected_answer, system,
self.args.max_length)
return {
"index": torch.tensor(index, dtype=torch.long),
"chosen_input_ids": torch.tensor(chosen_input_ids, dtype=torch.long),
"rejected_input_ids": torch.tensor(rejected_input_ids, dtype=torch.long),
"chosen_labels": torch.tensor(chosen_labels, dtype=torch.long),
"rejected_labels": torch.tensor(rejected_labels, dtype=torch.long)
}
elif "chatglm" in self.args.model_name_or_path.lower():
prompt = f"[Round {0}]\n问:{prompt}\n答:"
chosen_encodings_dict = self.tokenizer(prompt, chosen_answer, max_length=self.args.max_length,
truncation="longest_first", padding="max_length",
return_tensors="pt")
rejected_encodings_dict = self.tokenizer(prompt, rejected_answer, max_length=self.args.max_length,
truncation="longest_first", padding="max_length",
return_tensors="pt")
return {
"chosen_input_ids": chosen_encodings_dict["input_ids"][0],
"rejected_input_ids": rejected_encodings_dict["input_ids"][0],
"labels": rejected_encodings_dict["input_ids"][0],
}
else:
raise ValueError(f"Unsupported model name: {self.args.model_name_or_path}")
@staticmethod
def load_dataset(filename):
discard = 0
index = 1
pairs = []
with open(filename, "r", encoding="utf-8") as f:
for line in tqdm(f, desc=f"Loading {os.path.basename(filename)}"):
item = json.loads(line)
prompt = str(item['prompt'])
answers = item['answers']
prefix = item.get('prefix', "")
system = item.get('system', "")
chosen_answer, rejected_answer = None, None
for i in range(len(answers) - 1):
answer_1 = str(answers[i]["answer"])
answer_1_score = answers[i]["score"]
answer_2 = str(answers[i + 1]["answer"])
answer_2_score = answers[i + 1]["score"]
if answer_1_score > answer_2_score:
chosen_answer = answer_1
rejected_answer = answer_2
if chosen_answer is not None and rejected_answer is not None \
and len(prompt) > 0 and len(chosen_answer) > 0 and len(rejected_answer) > 0 \
and chosen_answer != rejected_answer:
pair = {
"index": index,
"prompt": prompt,
"prefix": prefix,
"system": system,
"chosen_answer": chosen_answer,
"rejected_answer": rejected_answer
}
index += 1
pairs.append(pair)
else:
discard += 1
print_rank_0(f"Finished loading {os.path.basename(filename)}, # pairs: {len(pairs)}, # discarded: {discard}")
return pairs
class OCNLIDataset(Dataset):
def __init__(self, args, eval_filename, tokenizer, train_filename=None):
self.tokenizer = tokenizer
self.args = args
self.label_dict = {'entailment': 'Yes', 'neutral': 'Maybe', 'contradiction': 'No'}
dataset = self.load_dataset(eval_filename)
if train_filename is not None:
self.labelled_list = self.load_dataset(eval_filename)
self.post_list = dataset
for k in range(5):
print_rank_0(f"OCNLIDataset sample-{k}\n: {dataset[k]}")
def __len__(self):
return len(self.post_list)
def __getitem__(self, idx):
data = self.post_list[idx]
prompt = data['prompt']
label = data['label']
# Few-Shot example construction
if hasattr(self, "labelled_list"):
examples = random.sample(self.labelled_list, min(len(self.labelled_list), self.args.max_few_shot))
prompts = []
prompt_tokens = self.tokenizer.tokenize(prompt)
for example in examples:
example_prompt = example['prompt']
exmample_tokens = self.tokenizer.tokenize(example_prompt + "\n")
if len(exmample_tokens) + len(prompt_tokens) + 2 > self.args.max_length:
break