data_process.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import csv
  2. import itertools
  3. import re
  4. import json
  5. import jsonlines
  6. import psutil
  7. import ujson
  8. import numpy as np
  9. import pandas as pd
  10. from transformers import AutoTokenizer
  11. from datasets import load_dataset
  12. bos_token = "<s>"
  13. eos_token = "</s>"
  14. def pretrain_process(chunk_size=50000):
  15. chunk_idx = 0
  16. with jsonlines.open('./dataset/mobvoi_seq_monkey_general_open_corpus.jsonl') as reader:
  17. with open('./dataset/pretrain_data.csv', 'w', newline='', encoding='utf-8') as csvfile:
  18. writer = csv.writer(csvfile)
  19. writer.writerow(['text'])
  20. while True:
  21. chunk = list(itertools.islice(reader, chunk_size))
  22. if not chunk:
  23. break
  24. for idx, obj in enumerate(chunk):
  25. try:
  26. content = obj.get('text', '')
  27. if len(content) > 512:
  28. continue
  29. writer.writerow([content])
  30. except UnicodeDecodeError as e:
  31. print(f"Skipping invalid line {chunk_idx * chunk_size + idx + 1}: {e}")
  32. continue
  33. chunk_idx += 1
  34. print('chunk:', ((chunk_idx - 1) * chunk_size, chunk_idx * chunk_size), 'process end')
  35. def sft_process(contain_history=False):
  36. file_name = 'sft_data.csv'
  37. if not contain_history:
  38. file_name = 'sft_data_single.csv'
  39. def chinese_ratio(text):
  40. # 匹配所有中文字符
  41. chinese_chars = re.findall(r'[\u4e00-\u9fff]', text)
  42. # 中文字符数量占比
  43. return len(chinese_chars) / len(text) if text else 0
  44. def process_and_write_data(data):
  45. q_lst, a_lst, history_lst = [], [], []
  46. for per in data:
  47. history, q, a = per['history'], per['q'], per['a']
  48. if (contain_history and not history) or not q or not a:
  49. continue
  50. if len(q) < 10 or len(a) < 5:
  51. continue
  52. if len(q) > 512 or len(a) > 512:
  53. continue
  54. # 判断q和a中中文字符占比是否超过70%
  55. if not (chinese_ratio(q) > 0.86 and chinese_ratio(a) > 0.86):
  56. continue
  57. q_lst.append(q)
  58. a_lst.append(a)
  59. if contain_history:
  60. history_lst.append(history)
  61. else:
  62. history_lst.append([])
  63. # 创建DataFrame并追加到CSV文件
  64. df = pd.DataFrame({'history': history_lst, 'q': q_lst, 'a': a_lst})
  65. df.to_csv(f'./dataset/{file_name}', mode='a', header=False, index=False, lineterminator='\r\n')
  66. chunk_size = 1000 # 每次处理的记录数
  67. data = []
  68. with open(f'./dataset/{file_name}', 'w', encoding='utf-8') as f:
  69. f.write('history,q,a\n')
  70. sft_datasets = ['./dataset/sft_data_zh.jsonl']
  71. if not contain_history:
  72. sft_datasets = ['./dataset/sft_data_zh.jsonl']
  73. chunk_num = 0
  74. for path in sft_datasets:
  75. with jsonlines.open(path) as reader:
  76. for idx, obj in enumerate(reader):
  77. try:
  78. data.append({
  79. 'history': obj.get('history', ''),
  80. 'q': obj.get('input', '') + obj.get('q', ''),
  81. 'a': obj.get('output', '') + obj.get('a', '')
  82. })
  83. if len(data) >= chunk_size:
  84. chunk_num += 1
  85. process_and_write_data(data)
  86. data = []
  87. if chunk_num % 100 == 0:
  88. print(f'chunk:{chunk_num} process end')
  89. except jsonlines.InvalidLineError as e:
  90. print(f"Skipping invalid JSON line {idx + 1}: {e}")
  91. continue
  92. if data:
  93. process_and_write_data(data)
  94. data = []
  95. def rl_process():
  96. ################
  97. # Dataset
  98. ################
  99. dataset_paths = [
  100. './dataset/dpo/dpo_zh_demo.json',
  101. './dataset/dpo/dpo_train_data.json',
  102. './dataset/dpo/huozi_rlhf_data.json',
  103. ]
  104. train_dataset = load_dataset('json', data_files=dataset_paths)
  105. merged_data = []
  106. for split in train_dataset.keys():
  107. merged_data.extend(train_dataset[split])
  108. with open('./dataset/dpo/train_data.json', 'w', encoding='utf-8') as f:
  109. json.dump(merged_data, f, ensure_ascii=False, indent=4)
  110. if __name__ == "__main__":
  111. tokenizer = AutoTokenizer.from_pretrained('./model/minimind_tokenizer', use_fast=False)
  112. print('tokenizer词表大小:', len(tokenizer))
  113. ################
  114. # 1: pretrain
  115. # 2: sft
  116. # 3: RL
  117. ################
  118. process_type = 2
  119. if process_type == 1:
  120. pretrain_process()
  121. if process_type == 2:
  122. sft_process(contain_history=False)
  123. if process_type == 3:
  124. rl_process()