-
Notifications
You must be signed in to change notification settings - Fork 17
/
data_utils.py
266 lines (227 loc) · 9.95 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# @Time : 2023/1/22 16:22
# @Author : tk
# @FileName: data_utils.py
import copy
import glob
import json
import os
import typing
from functools import cache
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
from data_processer import DataStrategy, TokenIdsMaker
from deep_training.zoo.model_zoo.chatglm2.llm_model import ChatGLMTokenizer,PetlArguments,ChatGLMConfig,build_masks_and_position_ids_glm
from config import *
assert config_args['max_seq_length'] > 20
data_conf = {
'strategy': DataStrategy.truncation, # 数据策略选项
DataStrategy.truncation: {
'sup': True, # 是否监督训练
},
DataStrategy.siding: {
'sliding_size': config_args['max_seq_length'] // 3 * 2, #prompt滑动窗口大小
'sup': True, # 是否监督训练
"src_max_length": config_args['max_seq_length'] - 10,
"dst_max_length": None,
},
}
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
tokenizer: ChatGLMTokenizer
config: ChatGLMConfig
max_seq_length = self.max_seq_length_dict[mode]
tokenizer = self.tokenizer
config = self.config
if not hasattr(self, 'sptoken'):
self.sptoken = tokenizer.encode(text="")[-2:]
examples = data
strategy = data_conf['strategy']
if strategy == DataStrategy.truncation:
ds = TokenIdsMaker.trunction(tokenizer,config,examples=examples, max_seq_length=max_seq_length,
sptoken=self.sptoken ,**data_conf[strategy])
elif strategy == DataStrategy.siding:
ds = TokenIdsMaker.slidding(tokenizer,config, examples=examples, max_seq_length=max_seq_length,
sptoken=self.sptoken, **data_conf[strategy])
else:
raise ValueError('Invalid 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)
paragraph = [(session.get("role", ""), preprocess(session['q']),
preprocess('\n'.join(session['a'])) if isinstance(session['a'], list) else preprocess(
session['a']))
for session in paragraph]
sub = []
# 自行做模板
for (role, q, a) in paragraph:
# 不是system prompt answer 必须存在
if role != "system":
assert len(a), ValueError('answer cannot empty')
sub.append((role, q, a))
D.append(copy.deepcopy(sub))
sub.clear()
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)
cid = 0
sub = []
while cid < len(conversations):
m = conversations[cid]
cid += 1
role = m["from"]
q = preprocess(m["value"])
if role == "system":
a = ""
sub.append((role, q, a))
continue
assert role in ['user', 'observation', 'function']
m = conversations[cid]
cid += 1
assert m["from"] == "assistant"
a = preprocess(m["value"])
assert len(a), ValueError('answer cannot empty')
sub.append((role, q, a))
D.append(sub)
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):
if not hasattr(self,'sptoken'):
self.sptoken = self.tokenizer.encode(text="")[-2:]
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,position_ids = build_masks_and_position_ids_glm(input_ids,seqlens)
o['input_ids'] = input_ids.long()
o['attention_mask'] = attention_mask.bool()
o['position_ids'] = position_ids.long()
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),
conflict_handler='resolve')
model_args, training_args, data_args, lora_args = parser.parse_dict(config_args,
allow_extra_keys=True, )
elif global_args[ "trainer_backend" ] == "pl":
parser = HfArgumentParser((ModelArguments, TrainingArguments, DataArguments, PetlArguments))
model_args, training_args, data_args, _ = parser.parse_dict(config_args)
elif global_args["trainer_backend"] == "cl":
parser = HfArgumentParser((ModelArguments, TrainingArgumentsCL, DataArguments, PetlArguments),
conflict_handler='resolve')
model_args, training_args, data_args, lora_args = parser.parse_dict(config_args, allow_extra_keys=True, )
else:
parser = HfArgumentParser((ModelArguments, TrainingArgumentsAC, DataArguments, PetlArguments),
conflict_handler='resolve')
model_args, training_args, data_args, lora_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=ChatGLMTokenizer,
config_class_name=ChatGLMConfig)
# 缓存数据集
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