-
Notifications
You must be signed in to change notification settings - Fork 4
/
data_utils.py
212 lines (187 loc) · 8.79 KB
/
data_utils.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
# @Time : 2023/1/22 16:22
# @Author : tk
# @FileName: data_utils.py
import glob
import sys
import os
from functools import cache
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
import copy
import json
import typing
import numpy as np
import torch
from deep_training.data_helper import DataHelper, ModelArguments, TrainingArguments, DataArguments, TrainingArgumentsHF, \
TrainingArgumentsCL, TrainingArgumentsAC
from fastdatasets.record import load_dataset as Loader, RECORD, WriterObject, gfile
from tqdm import tqdm
from transformers import HfArgumentParser,PreTrainedTokenizer
from deep_training.zoo.model_zoo.moss.llm_model import MyTransformer,MossConfig,MossTokenizer,PetlArguments,PromptArguments
from data_processer import DataStrategy, TokenSupervision, TokenUnSupervision, TokenSupervisionRounds, \
TokenRoundsForMoss
from config import *
data_conf = {
'strategy': DataStrategy.mos_rounds, # 数据策略选项
DataStrategy.sup: {
'stride': int(config_args['max_seq_length'] / 3 * 2),
},
DataStrategy.unsup: {
'stride': int(config_args['max_seq_length'] / 3 * 2),
},
DataStrategy.sub_rounds: {
'stride': int(config_args['max_seq_length'] / 3 * 2),
},
DataStrategy.mos_rounds: {
}
}
class NN_DataHelper(DataHelper):
index = 1
def on_data_ready(self):
self.index = -1
# 切分词
def on_data_process(self, data: typing.Any, mode: str):
self.index += 1
tokenizer: MossTokenizer
config: MossConfig
max_seq_length = self.max_seq_length_dict[mode]
tokenizer = self.tokenizer # noqa
config = self.config # noqa
examples = data
strategy = data_conf['strategy']
if strategy == DataStrategy.sup:
ds = TokenSupervision.process(tokenizer, config=config, max_seq_length=max_seq_length, examples=examples,
**data_conf[strategy])
elif strategy == DataStrategy.unsup:
ds = TokenUnSupervision.process(tokenizer, config=config, max_seq_length=max_seq_length, examples=examples,
**data_conf[strategy])
elif strategy == DataStrategy.sub_rounds:
ds = TokenSupervisionRounds.process(tokenizer, config=config, max_seq_length=max_seq_length,
examples=examples,
**data_conf[strategy])
elif strategy == DataStrategy.mos_rounds:
ds = TokenRoundsForMoss.process(tokenizer, config=config, max_seq_length=max_seq_length,
examples=examples,
**data_conf[strategy])
else:
raise ValueError('Invalid strategy', strategy)
if not ds:
return None
if self.index < 3:
print(ds[0])
return ds
# 读取文件
def on_get_corpus(self, files: typing.List, mode: str):
D = []
strategy = data_conf['strategy']
files = sum([glob.glob(file) for file in files], [])
for file in files:
with open(file, mode='r', encoding='utf-8', newline='\n') as f:
lines = f.readlines()
for i, line in enumerate(lines):
jd = json.loads(line)
if not jd:
continue
paragraph = jd['paragraph']
if i < 10:
print(paragraph)
sub = []
# 自行做模板
for session in paragraph:
a = session['a']
assert len(a), ValueError('answer cannot empty')
sub.append(session)
if strategy == DataStrategy.mos_rounds:
D.append((jd['meta_instruction'],copy.deepcopy(sub)))
else:
D.append(copy.deepcopy(sub))
sub.clear()
return D
def collate_fn(self, batch):
o = {}
for i, b in enumerate(batch):
if i == 0:
for k in b:
o[k] = [torch.tensor(b[k])]
else:
for k in b:
o[k].append(torch.tensor(b[k]))
for k in o:
o[k] = torch.stack(o[k])
maxlen = torch.max(o.pop('seqlen'))
o['input_ids'] = o['input_ids'][:, :maxlen]
o['attention_mask'] = o['attention_mask'][:, :maxlen]
o['labels'] = o['labels'][:, :maxlen].long()
return o
def make_dataset_all(self):
data_args = self.data_args
# schema for arrow parquet
schema = {
"input_ids": "int32_list",
"attention_mask": "int32_list",
"labels": "int32_list",
"seqlen": "int32_list",
}
# 缓存数据集
if data_args.do_train:
self.make_dataset_with_args(data_args.train_file, mixed_data=False, shuffle=True, mode='train',
schema=schema)
if data_args.do_eval:
self.make_dataset_with_args(data_args.eval_file, mode='eval', schema=schema)
if data_args.do_test:
self.make_dataset_with_args(data_args.test_file, mode='test', schema=schema)
# 记录缓存文件
with open(os.path.join(data_args.output_dir, 'intermediate_file_index.json'), mode='w',
encoding='utf-8') as f:
f.write(json.dumps({
"train_files": self.train_files,
"eval_files": self.eval_files,
"test_files": self.test_files,
}, ensure_ascii=False))
@cache
def load_dataset_files(self):
data_args = self.data_args
if not data_args.convert_file:
return {
"train_files": self.train_files,
"eval_files": self.eval_files,
"test_files": self.test_files,
}
filename = os.path.join(data_args.output_dir, 'intermediate_file_index.json')
assert os.path.exists(filename), 'make you dataset firstly'
with open(filename, mode='r', encoding='utf-8') as f:
return json.loads(f.read())
if __name__ == '__main__':
if global_args[ "trainer_backend" ] == "hf":
parser = HfArgumentParser((ModelArguments, TrainingArgumentsHF, DataArguments, PetlArguments, PromptArguments),
conflict_handler='resolve')
model_args, training_args, data_args, lora_args, prompt_args = parser.parse_dict(config_args,
allow_extra_keys=True, )
elif global_args[ "trainer_backend" ] == "pl":
parser = HfArgumentParser((ModelArguments, TrainingArguments, DataArguments, PetlArguments, PromptArguments))
model_args, training_args, data_args, _, _ = parser.parse_dict(config_args)
elif global_args["trainer_backend"] == "cl":
parser = HfArgumentParser((ModelArguments, TrainingArgumentsCL, DataArguments, PetlArguments, PromptArguments),
conflict_handler='resolve')
model_args, training_args, data_args, lora_args, prompt_args = parser.parse_dict(config_args,
allow_extra_keys=True, )
else:
parser = HfArgumentParser((ModelArguments, TrainingArgumentsAC, DataArguments, PetlArguments, PromptArguments),
conflict_handler='resolve')
model_args, training_args, data_args, lora_args, prompt_args = parser.parse_dict(config_args,
allow_extra_keys=True, )
dataHelper = NN_DataHelper(model_args, training_args, data_args)
tokenizer, config, _,_ = dataHelper.load_tokenizer_and_config(tokenizer_class_name=MossTokenizer,config_class_name=MossConfig,config_kwargs={"torch_dtype": "float16"})
# 缓存数据集
print(f'to make dataset is overwrite_cache {data_args.overwrite_cache}')
dataHelper.make_dataset_all()
print('make dataset complete!')
print('check data !')
dataset = dataHelper.load_sequential_sampler(dataHelper.load_dataset_files()["train_files"],
with_load_memory=data_args.data_backend == 'record',
batch_size=1,
collate_fn=dataHelper.collate_fn)
print('total', len(dataset))
for i, d in enumerate(dataset):
print(d)
if i > 3:
break