data_process.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import itertools
  2. import re
  3. import json
  4. import jsonlines
  5. import psutil
  6. import ujson
  7. import numpy as np
  8. import pandas as pd
  9. from transformers import AutoTokenizer
  10. from datasets import load_dataset
  11. bos_token = "<s>"
  12. eos_token = "</s>"
  13. # pretrain
  14. def process_wiki_clean():
  15. with open('./dataset/clean-wikipedia-cn.json', 'r', encoding='utf-8') as f_read:
  16. data = [ujson.loads(line) for line in f_read]
  17. data_len = len(data)
  18. doc_ids = []
  19. for idx, line in enumerate(data):
  20. text = line['response']
  21. text_id = tokenizer(f'{bos_token}{text}{eos_token}').data['input_ids']
  22. if len(text_id) > 5:
  23. doc_ids += text_id
  24. if idx % (int(data_len / 20)) == 0:
  25. print(f"[{idx}/{data_len}] {text}")
  26. arr = np.array(doc_ids, dtype=np.uint16)
  27. with open('./dataset/clean-wikipedia-cn.bin', 'wb') as f:
  28. f.write(arr.tobytes())
  29. # pretrain
  30. def process_other():
  31. data = []
  32. with open('./dataset/alpaca_gpt4_data_zh.json', 'r', encoding='utf-8') as f:
  33. data_ = json.load(f)
  34. data += data_
  35. with open('./dataset/alpaca_data_zh_51k.json', 'r', encoding='utf-8') as f:
  36. data_ = json.load(f)
  37. data += data_
  38. doc_ids = []
  39. for idx, per in enumerate(data):
  40. q = per['instruction']
  41. i = per['input']
  42. a = per['output']
  43. q = q + i
  44. if len(q) < 10 or len(a) < 5:
  45. continue
  46. if len(q) > 256 or len(a) > 256:
  47. continue
  48. text_id = tokenizer(f'{bos_token}{q},{a}{eos_token}').data['input_ids']
  49. if len(text_id) > 5:
  50. doc_ids += text_id
  51. if idx % 50000 == 0:
  52. print(idx, len(data))
  53. arr = np.array(doc_ids, dtype=np.uint16)
  54. with open('./dataset/clean_other.bin', 'wb') as f:
  55. f.write(arr.tobytes())
  56. def process_seq_monkey(chunk_size=50000):
  57. doc_ids = []
  58. chunk_idx = 0
  59. with jsonlines.open('./dataset/mobvoi_seq_monkey_general_open_corpus.jsonl') as reader:
  60. while True:
  61. chunk = list(itertools.islice(reader, chunk_size))
  62. if not chunk:
  63. break
  64. for idx, obj in enumerate(chunk):
  65. try:
  66. content = obj.get('text', '')
  67. if len(content) > 512:
  68. continue
  69. text_id = tokenizer(f'{bos_token}{content}{eos_token}').data['input_ids']
  70. doc_ids += text_id
  71. except UnicodeDecodeError as e:
  72. print(f"Skipping invalid line {chunk_idx * chunk_size + idx + 1}: {e}")
  73. continue
  74. chunk_idx += 1
  75. print(f"Processed chunk {chunk_idx} with {chunk_size} lines")
  76. if len(doc_ids) > 1000000:
  77. arr = np.array(doc_ids, dtype=np.uint16)
  78. with open(f'./dataset/clean_seq_monkey.bin', 'ab') as f:
  79. f.write(arr.tobytes())
  80. doc_ids = []
  81. if doc_ids:
  82. arr = np.array(doc_ids, dtype=np.uint16)
  83. with open(f'./dataset/clean_seq_monkey.bin', 'ab') as f:
  84. f.write(arr.tobytes())
  85. def pretrain_process():
  86. # process_wiki_clean()
  87. process_seq_monkey()
  88. data_path_list = [
  89. # './dataset/clean-wikipedia-cn.bin',
  90. './dataset/clean_seq_monkey.bin'
  91. ]
  92. data_lst = []
  93. for data_path in data_path_list:
  94. with open(data_path, 'rb') as f:
  95. data = np.fromfile(f, dtype=np.uint16)
  96. data_lst.append(data)
  97. arr = np.concatenate(data_lst)
  98. print(arr.shape)
  99. with open('./dataset/pretrain_data.bin', 'wb') as f:
  100. f.write(arr.tobytes())
  101. def sft_process(contain_history=False):
  102. file_name = 'sft_data.csv'
  103. if not contain_history:
  104. file_name = 'sft_data_single.csv'
  105. def chinese_ratio(text):
  106. # 匹配所有中文字符
  107. chinese_chars = re.findall(r'[\u4e00-\u9fff]', text)
  108. # 中文字符数量占比
  109. return len(chinese_chars) / len(text) if text else 0
  110. def process_and_write_data(data):
  111. q_lst, a_lst, history_lst = [], [], []
  112. for per in data:
  113. history, q, a = per['history'], per['q'], per['a']
  114. if (contain_history and not history) or not q or not a:
  115. continue
  116. if len(q) < 10 or len(a) < 5:
  117. continue
  118. if len(q) > 256 or len(a) > 256:
  119. continue
  120. # 判断q和a中中文字符占比是否超过70%
  121. if not (chinese_ratio(q) > 0.9 and chinese_ratio(a) > 0.9):
  122. continue
  123. q_lst.append(q)
  124. a_lst.append(a)
  125. if contain_history:
  126. history_lst.append(history)
  127. else:
  128. history_lst.append([])
  129. # 创建DataFrame并追加到CSV文件
  130. df = pd.DataFrame({'history': history_lst, 'q': q_lst, 'a': a_lst})
  131. df.to_csv(f'./dataset/{file_name}', mode='a', header=False, index=False, lineterminator='\r\n')
  132. chunk_size = 1000 # 每次处理的记录数
  133. data = []
  134. with open(f'./dataset/{file_name}', 'w', encoding='utf-8') as f:
  135. f.write('history,q,a\n')
  136. sft_datasets = ['./dataset/sft_data_zh.jsonl']
  137. if not contain_history:
  138. sft_datasets = ['./dataset/sft_data_zh.jsonl']
  139. for path in sft_datasets:
  140. with jsonlines.open(path) as reader:
  141. for idx, obj in enumerate(reader):
  142. try:
  143. data.append({
  144. 'history': obj.get('history', ''),
  145. 'q': obj.get('input', '') + obj.get('q', ''),
  146. 'a': obj.get('output', '') + obj.get('a', '')
  147. })
  148. if len(data) >= chunk_size:
  149. process_and_write_data(data)
  150. data = []
  151. except jsonlines.InvalidLineError as e:
  152. print(f"Skipping invalid JSON line {idx + 1}: {e}")
  153. continue
  154. if data:
  155. process_and_write_data(data)
  156. data = []
  157. def rl_process():
  158. ################
  159. # Dataset
  160. ################
  161. dataset_path = ['./dataset/dpo/dpo_zh_demo.json',
  162. './dataset/dpo/train_data.json',
  163. './dataset/dpo/huozi_rlhf_data.json', ]
  164. train_dataset = load_dataset('json', data_files=dataset_path)
  165. def process(row):
  166. row["chosen"] = tokenizer.apply_chat_template(row["chosen"], tokenize=False)
  167. row["reject"] = tokenizer.apply_chat_template(row["rejected"], tokenize=False)
  168. return row
  169. ds = train_dataset.map(
  170. process,
  171. load_from_cache_file=False,
  172. )
  173. output_dataset_path = './dataset/dpo/train_data.json'
  174. ds['train'].to_json(output_dataset_path, force_ascii=False, orient='records', lines=True)
  175. if __name__ == "__main__":
  176. tokenizer = AutoTokenizer.from_pretrained('./model/minimind_tokenizer', use_fast=False)
  177. print('tokenizer词表大小:', len(tokenizer))
  178. ################
  179. # 1: pretrain
  180. # 2: sft
  181. # 3: RL
  182. ################
  183. process_type = 1
  184. if process_type == 1:
  185. pretrain_process()
  186. if process_type == 2:
  187. sft_process(contain_history=False)
  188. if process_type == 3:
  189. rl_process()