data_process.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import csv
  2. import glob
  3. import os
  4. import re
  5. import json
  6. import jsonlines
  7. import pandas as pd
  8. from tqdm import tqdm
  9. bos_token = "<s>"
  10. eos_token = "</s>"
  11. def pretrain_process():
  12. # 定义输入和输出路径
  13. input_dir = '../CCI3-HQ/data'
  14. output_file = '../dataset/pretrain_data_hq.csv'
  15. jsonl_files = glob.glob(os.path.join(input_dir, 'part_*.jsonl'))
  16. total_lines = 0
  17. print("正在计算总行数...")
  18. for file in jsonl_files:
  19. with open(file, 'r', encoding='utf-8') as f:
  20. for _ in f:
  21. total_lines += 1
  22. with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:
  23. writer = csv.writer(csvfile)
  24. writer.writerow(['text', 'score']) # 写入表头
  25. for jsonl_file in jsonl_files:
  26. with open(jsonl_file, 'r', encoding='utf-8') as f:
  27. for line in tqdm(f, desc=f'处理 {os.path.basename(jsonl_file)}', total=total_lines, unit='行',
  28. leave=False):
  29. try:
  30. data = json.loads(line)
  31. text = data.get('text', '')
  32. score = data.get('score', 0)
  33. if len(text) <= 512 and score > 3.5:
  34. writer.writerow([text, score])
  35. except json.JSONDecodeError:
  36. continue
  37. print(f"筛选完成,结果已保存到 {output_file}")
  38. def sft_process():
  39. sft_file_name = 'sft_data.csv'
  40. def process_and_write_data(data):
  41. q_lst, a_lst, history_lst = [], [], []
  42. for per in data:
  43. history, q, a = per['history'], per['q'], per['a']
  44. if not q or not a:
  45. continue
  46. history_len = sum(len(s) for s in history)
  47. message_len = history_len + len(q) + len(a)
  48. if message_len < 70 or message_len > 512:
  49. continue
  50. q_lst.append(q)
  51. a_lst.append(a)
  52. history_lst.append(history)
  53. df = pd.DataFrame({'history': history_lst, 'q': q_lst, 'a': a_lst})
  54. df.to_csv(f'../dataset/{sft_file_name}',
  55. mode='a', header=False, index=False,
  56. lineterminator='\r\n', escapechar='\\', encoding='utf-8')
  57. chunk_size = 1000
  58. data = []
  59. with open(f'../dataset/{sft_file_name}', 'w', encoding='utf-8') as f:
  60. f.write('history,q,a\n')
  61. # sft_path = ['/root/shared-nvme/sft_data_zh.jsonl', '/root/shared-nvme/sft_data_en.jsonl']
  62. sft_path = ['/root/shared-nvme/sft_data_en.jsonl']
  63. chunk_num = 0
  64. for path in sft_path:
  65. with jsonlines.open(path) as reader:
  66. for idx, obj in enumerate(reader):
  67. try:
  68. data.append({
  69. 'history': obj.get('history', ''),
  70. 'q': obj.get('input', '') + obj.get('q', ''),
  71. 'a': obj.get('output', '') + obj.get('a', '')
  72. })
  73. if len(data) >= chunk_size:
  74. chunk_num += 1
  75. process_and_write_data(data)
  76. data = []
  77. if chunk_num % 100 == 0:
  78. print(f'chunk:{chunk_num} process end')
  79. except jsonlines.InvalidLineError as e:
  80. print(f"Skipping invalid JSON line {idx + 1}: {e}")
  81. continue
  82. if data:
  83. process_and_write_data(data)
  84. data = []
  85. def rl_process():
  86. # 偏好数据默认只用中文(建议)
  87. input_paths = [
  88. # "../dataset/dpo_en.json",
  89. "../dataset/dpo_zh.json"
  90. ]
  91. output_path = "../dataset/dpo_data.jsonl" # 修改输出文件扩展名为 .jsonl
  92. all_converted = []
  93. for input_path in input_paths:
  94. with open(input_path, "r", encoding="utf-8") as f:
  95. data = json.load(f) # data is likely a list
  96. for item in data:
  97. new_data = {
  98. "chosen": [],
  99. "rejected": []
  100. }
  101. for turn in item["conversations"]:
  102. role = "user" if turn["from"] == "human" else "assistant"
  103. message = {"role": role, "content": turn["value"]}
  104. new_data["chosen"].append(message)
  105. new_data["rejected"].append(message)
  106. new_data["chosen"].append({
  107. "role": "assistant",
  108. "content": item["chosen"]["value"]
  109. })
  110. new_data["rejected"].append({
  111. "role": "assistant",
  112. "content": item["rejected"]["value"]
  113. })
  114. all_converted.append(new_data)
  115. with open(output_path, "w", encoding="utf-8") as f:
  116. for item in all_converted:
  117. f.write(json.dumps(item, ensure_ascii=False) + "\n")
  118. def lora_dataset():
  119. import json
  120. import csv
  121. # 读取JSON文件
  122. with open('../dataset/Chinese-medical-dialogue.json', 'r', encoding='utf-8') as f:
  123. data = json.load(f)
  124. # 准备CSV数据
  125. csv_data = []
  126. for item in data:
  127. # 提取input和output并去除首尾空白
  128. q = item['input'].strip()
  129. a = item['output'].strip()
  130. # 检查长度是否符合要求
  131. if len(q) + len(a) < 160:
  132. csv_data.append({
  133. 'history': '[]',
  134. 'q': q,
  135. 'a': a
  136. })
  137. # 写入CSV文件
  138. with open('../dataset/medical_sft.csv', 'w', newline='', encoding='utf-8') as csvfile:
  139. fieldnames = ['history', 'q', 'a']
  140. writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
  141. writer.writeheader()
  142. writer.writerows(csv_data)
  143. print(f'转换完成,共处理 {len(csv_data)} 条有效数据')
  144. if __name__ == "__main__":
  145. ################
  146. # 1: pretrain
  147. # 2: sft
  148. # 3: RL
  149. ################
  150. process_type = 4
  151. if process_type == 1:
  152. pretrain_process()
  153. if process_type == 2:
  154. sft_process()
  155. if process_type == 3:
  156. rl_process()
  157. if process_type == 4:
  158. lora_dataset()