-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_utils.py
242 lines (202 loc) · 8.99 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
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
# @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.zoo.model_zoo.qwen_vl.qwen_generation_utils import get_ltor_masks_and_position_ids
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 data_processer import DataStrategy, TokenIdsMaker
from deep_training.zoo.model_zoo.qwen_vl.llm_model import QWenTokenizer,PetlArguments,QWenConfig,PromptArguments
from config import *
data_conf = {
'strategy': DataStrategy.truncation, # 数据策略选项
DataStrategy.truncation: {
'sup': True, # 是否监督训练
},
}
def preprocess(text):
#text = text.replace("\n", "\\n").replace("\t", "\\t")
return text
def postprocess(text):
# return text.replace("\\n", "\n").replace("\\t", "\t")
return text
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
max_seq_length = self.max_seq_length_dict[mode]
tokenizer: QWenTokenizer = self.tokenizer # noqa
config: QWenConfig = self.config # noqa
strategy = data_conf['strategy']
if strategy == DataStrategy.truncation:
ds = TokenIdsMaker.tunction(tokenizer,config,data, max_seq_length,**data_conf[strategy])
else:
raise ValueError('Invlid strategy',strategy)
if not ds:
return None
if self.index < 3:
print(ds[0])
return ds
def _get_paragraph(self,lines):
D = []
for line_id, line in enumerate(lines):
jd = json.loads(line)
if not jd:
continue
paragraph = jd['paragraph']
if line_id < 10:
print(paragraph)
prefix = jd.get('p', '')
paragraph = [(preprocess(session['q']),
preprocess('\n'.join(session['a'])) if isinstance(session['a'], list) else preprocess(
session['a']))
for session in paragraph]
D.append((prefix,paragraph))
return D
def _get_messages(self,lines):
D = []
for line_id, line in enumerate(lines):
jd = json.loads(line)
if not jd:
continue
conversations = jd['conversations']
if line_id < 10:
print(conversations)
paragraph = []
prefix = ''
pair = [None,None]
for m in conversations:
if m["from"] == 'user':
pair[0] = preprocess(m["value"])
elif m["from"] == 'assistant':
pair[1] = preprocess(m["value"])
elif m["from"] == 'system':
prefix = preprocess(m["value"])
if pair[0] is not None and pair[1] is not None:
paragraph.append(tuple(pair))
pair[0],pair[1] = None,None
D.append((prefix,paragraph))
return D
# 读取文件
def on_get_corpus(self, files: typing.List, mode: str):
D = []
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()
is_new = False
if len(lines) > 0:
is_new = 'conversations' in json.loads(lines[0])
if is_new:
D.extend(self._get_messages(lines))
else:
D.extend(self._get_paragraph(lines))
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])
seqlens = o.pop('seqlen')
max_len = torch.max(seqlens).tolist()
input_ids = o['input_ids'][:, :max_len]
attention_mask = torch.zeros_like(input_ids,dtype=torch.bool)
for i,seqlen in enumerate(seqlens):
attention_mask[i,:seqlen] = 1
o['input_ids'] = input_ids.long()
o['attention_mask'] = attention_mask
o['labels'] = o['labels'][:, :max_len].long()
return o
def make_dataset_all(self):
data_args = self.data_args
# schema for arrow parquet
schema = {
"input_ids": "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, lora_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, )
lora_args = lora_args.config
dataHelper = NN_DataHelper(model_args, training_args, data_args)
tokenizer, config, _,_ = dataHelper.load_tokenizer_and_config(tokenizer_class_name=QWenTokenizer,config_class_name=QWenConfig)
# 缓存数据集
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