data_process.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. content = obj.get('text', '')
  61. if len(content) > 512:
  62. continue
  63. text_id = tokenizer(f'{bos_token}{content}{eos_token}').data['input_ids']
  64. doc_ids += text_id
  65. if idx % 50000 == 0:
  66. print(f"seq_monkey: [{idx}]")
  67. arr = np.array(doc_ids, dtype=np.uint16)
  68. with open('./dataset/clean_seq_monkey.bin', 'wb') as f:
  69. f.write(arr.tobytes())
  70. def pretrain_process():
  71. # process_wiki_clean()
  72. process_seq_monkey()
  73. data_path_list = [
  74. # './dataset/clean-wikipedia-cn.bin',
  75. './dataset/clean_seq_monkey.bin'
  76. ]
  77. data_lst = []
  78. for data_path in data_path_list:
  79. with open(data_path, 'rb') as f:
  80. data = np.fromfile(f, dtype=np.uint16)
  81. data_lst.append(data)
  82. arr = np.concatenate(data_lst)
  83. print(arr.shape)
  84. with open('./dataset/pretrain_data.bin', 'wb') as f:
  85. f.write(arr.tobytes())
  86. def sft_process(contain_history=False):
  87. file_name = 'sft_data.csv'
  88. if not contain_history:
  89. file_name = 'sft_data_single.csv'
  90. def chinese_ratio(text):
  91. # 匹配所有中文字符
  92. chinese_chars = re.findall(r'[\u4e00-\u9fff]', text)
  93. # 中文字符数量占比
  94. return len(chinese_chars) / len(text) if text else 0
  95. def process_and_write_data(data):
  96. q_lst, a_lst, history_lst = [], [], []
  97. for per in data:
  98. history, q, a = per['history'], per['q'], per['a']
  99. if (contain_history and not history) or not q or not a:
  100. continue
  101. if len(q) < 10 or len(a) < 5:
  102. continue
  103. if len(q) > 256 or len(a) > 256:
  104. continue
  105. # 判断q和a中中文字符占比是否超过70%
  106. if not (chinese_ratio(q) > 0.9 and chinese_ratio(a) > 0.9):
  107. continue
  108. q_lst.append(q)
  109. a_lst.append(a)
  110. if contain_history:
  111. history_lst.append(history)
  112. else:
  113. history_lst.append([])
  114. # 创建DataFrame并追加到CSV文件
  115. df = pd.DataFrame({'history': history_lst, 'q': q_lst, 'a': a_lst})
  116. df.to_csv(f'./dataset/{file_name}', mode='a', header=False, index=False, lineterminator='\r\n')
  117. chunk_size = 1000 # 每次处理的记录数
  118. data = []
  119. with open(f'./dataset/{file_name}', 'w', encoding='utf-8') as f:
  120. f.write('history,q,a\n')
  121. sft_datasets = ['./dataset/sft_data_zh_2.jsonl']
  122. if not contain_history:
  123. sft_datasets = ['./dataset/sft_data_zh_2.jsonl']
  124. for path in sft_datasets:
  125. with jsonlines.open(path) as reader:
  126. for idx, obj in enumerate(reader):
  127. data.append({
  128. 'history': obj.get('history', ''),
  129. 'q': obj.get('input', '') + obj.get('q', ''),
  130. 'a': obj.get('output', '') + obj.get('a', '')
  131. })
  132. if len(data) >= chunk_size:
  133. process_and_write_data(data)
  134. data = []
  135. if data:
  136. process_and_write_data(data)
  137. data = []
  138. def rl_process():
  139. ################
  140. # Dataset
  141. ################
  142. dataset_path = ['./dataset/dpo/dpo_zh_demo.json',
  143. './dataset/dpo/train_1.json',
  144. './dataset/dpo/huozi_rlhf_data.json', ]
  145. train_dataset = load_dataset('json', data_files=dataset_path)
  146. def process(row):
  147. row["chosen"] = tokenizer.apply_chat_template(row["chosen"], tokenize=False)
  148. row["reject"] = tokenizer.apply_chat_template(row["rejected"], tokenize=False)
  149. return row
  150. ds = train_dataset.map(
  151. process,
  152. load_from_cache_file=False,
  153. )
  154. output_dataset_path = './dataset/dpo/train_data.json'
  155. ds['train'].to_json(output_dataset_path, force_ascii=False, orient='records', lines=True)
  156. if __name__ == "__main__":
  157. tokenizer = AutoTokenizer.from_pretrained('./model', use_fast=False)
  158. print('tokenizer词表大小:', len(tokenizer))
  159. ################
  160. # 1: pretrain
  161. # 2: sft
  162. # 3: RL
  163. ################
  164. process_type = 2
  165. if process_type == 1:
  166. pretrain_process()
  167. if process_type == 2:
  168. sft_process(contain_history=True)
  169. if process_type == 3:
  170. rl_process()