data_process.py 6.6 KB

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