__init__.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. """数据预处理器:将不同格式的数据集转换为训练所需格式。"""
  2. import json
  3. from pathlib import Path
  4. from typing import Any
  5. # 常见列名映射
  6. _PROMPT_COLUMNS = {"prompt", "question", "query", "text", "input"}
  7. _COMPLETION_COLUMNS = {"completion", "answer", "response", "target", "output"}
  8. _ALPACA_COLUMNS = {"instruction", "input", "output"}
  9. _SHAREGPT_COLUMNS = {"conversations"}
  10. _DPO_COLUMNS = {"prompt", "chosen", "rejected"}
  11. def apply_auto_template(item: dict, column_map: dict[str, str]) -> dict:
  12. """Auto 模板:根据实际列名自动映射。"""
  13. prompt = ""
  14. completion = ""
  15. # 先找 prompt 列
  16. for col in column_map.get("prompt_candidates", []):
  17. if col in item and item[col] is not None:
  18. prompt = str(item[col])
  19. break
  20. # 再找 completion 列
  21. for col in column_map.get("completion_candidates", []):
  22. if col in item and item[col] is not None:
  23. completion = str(item[col])
  24. break
  25. return {"prompt": prompt, "completion": completion}
  26. def _detect_columns(raw_data: list[dict]) -> dict[str, list[str]]:
  27. """扫描数据集前几行,自动检测列名并返回映射关系。"""
  28. if not raw_data:
  29. return {"prompt_candidates": [], "completion_candidates": [], "template": "raw"}
  30. # 取前 5 行扫描
  31. sample = raw_data[:5]
  32. all_columns = set()
  33. for item in sample:
  34. all_columns.update(item.keys())
  35. lower_cols = {c.lower().strip(): c for c in all_columns}
  36. # 检测模板类型
  37. if _SHAREGPT_COLUMNS & all_columns:
  38. return {"template": "sharegpt"}
  39. if _DPO_COLUMNS & all_columns:
  40. return {"template": "dpo"}
  41. if _ALPACA_COLUMNS & all_columns:
  42. return {"template": "alpaca"}
  43. # 查找 prompt 和 completion 候选列
  44. prompt_candidates = [lower_cols.get(c) for c in ["prompt", "question", "query", "text", "input"] if lower_cols.get(c)]
  45. completion_candidates = [lower_cols.get(c) for c in ["completion", "answer", "response", "target", "output"] if lower_cols.get(c)]
  46. return {
  47. "template": "auto",
  48. "prompt_candidates": prompt_candidates,
  49. "completion_candidates": completion_candidates,
  50. }
  51. def apply_alpaca_template(item: dict) -> dict:
  52. """Alpaca 模板: instruction + input -> output。"""
  53. instruction = item.get("instruction", "")
  54. input_text = item.get("input", "")
  55. output = item.get("output", "")
  56. # 确保所有值为字符串
  57. instruction = str(instruction) if instruction is not None else ""
  58. input_text = str(input_text) if input_text is not None else ""
  59. output = str(output) if output is not None else ""
  60. prompt = f"{instruction}\n\n{input_text}" if input_text else instruction
  61. return {"prompt": prompt, "completion": output}
  62. def apply_sharegpt_template(item: dict) -> dict:
  63. """ShareGPT 模板: conversations list -> formatted prompt + completion。"""
  64. conversations = item.get("conversations", [])
  65. if len(conversations) < 2:
  66. return {"prompt": "", "completion": ""}
  67. prompt_parts = []
  68. completion = ""
  69. for i, turn in enumerate(conversations):
  70. role = turn.get("from", turn.get("role", "human"))
  71. content = turn.get("value", turn.get("content", ""))
  72. if i == 0:
  73. prompt_parts.append(content)
  74. elif i == 1:
  75. completion = content
  76. break
  77. else:
  78. prompt_parts.append(f"{role}: {content}")
  79. prompt = "\n".join(prompt_parts)
  80. return {"prompt": prompt, "completion": completion}
  81. def apply_raw_template(item: dict) -> dict:
  82. """Raw 模板: 直接读取 prompt/text 和 completion/output 字段。"""
  83. prompt = item.get("prompt", item.get("text", item.get("input", item.get("question", item.get("query", "")))))
  84. completion = item.get("completion", item.get("output", item.get("target", item.get("answer", item.get("response", "")))))
  85. return {"prompt": str(prompt), "completion": str(completion)}
  86. def apply_dpo_template(item: dict) -> dict:
  87. """DPO 模板: prompt + chosen + rejected。"""
  88. return {
  89. "prompt": item.get("prompt", item.get("input", item.get("question", item.get("query", "")))),
  90. "chosen": item.get("chosen", item.get("positive", item.get("answer", ""))),
  91. "rejected": item.get("rejected", item.get("negative", "")),
  92. }
  93. def apply_kto_template(item: dict) -> dict:
  94. """KTO 模板: prompt + completion + label。"""
  95. return {
  96. "prompt": item.get("prompt", item.get("input", item.get("question", item.get("query", "")))),
  97. "completion": item.get("completion", item.get("output", item.get("answer", item.get("response", "")))),
  98. "label": item.get("label", True),
  99. }
  100. def apply_orpo_template(item: dict) -> dict:
  101. """ORPO 模板: prompt + chosen + rejected (类似 DPO)。"""
  102. return {
  103. "prompt": item.get("prompt", item.get("input", item.get("question", item.get("query", "")))),
  104. "chosen": item.get("chosen", item.get("positive", item.get("answer", ""))),
  105. "rejected": item.get("rejected", item.get("negative", "")),
  106. }
  107. def apply_rm_template(item: dict) -> dict:
  108. """Reward Modeling 模板: prompt + chosen + rejected。"""
  109. return {
  110. "prompt": item.get("prompt", item.get("input", item.get("question", item.get("query", "")))),
  111. "chosen": item.get("chosen", item.get("positive", item.get("answer", ""))),
  112. "rejected": item.get("rejected", item.get("negative", "")),
  113. }
  114. TEMPLATE_MAP = {
  115. "sft": {
  116. "auto": None, # 特殊处理:自动检测
  117. "alpaca": apply_alpaca_template,
  118. "sharegpt": apply_sharegpt_template,
  119. "raw": apply_raw_template,
  120. },
  121. "dpo": {
  122. "auto": apply_dpo_template,
  123. "alpaca": apply_dpo_template,
  124. "sharegpt": apply_dpo_template,
  125. "raw": apply_dpo_template,
  126. },
  127. "kto": {
  128. "auto": apply_kto_template,
  129. "raw": apply_kto_template,
  130. },
  131. "orpo": {
  132. "auto": apply_orpo_template,
  133. "alpaca": apply_orpo_template,
  134. "raw": apply_orpo_template,
  135. },
  136. "rm": {
  137. "auto": apply_rm_template,
  138. "raw": apply_rm_template,
  139. },
  140. "ppo": {
  141. "auto": apply_raw_template,
  142. "raw": apply_raw_template,
  143. },
  144. }
  145. def preprocess_file(
  146. input_path: str,
  147. output_path: str,
  148. task_type: str = "sft",
  149. template: str = "auto",
  150. ) -> list[dict[str, Any]]:
  151. """读取文件并应用模板,返回处理后的数据列表。"""
  152. input_p = Path(input_path)
  153. ext = input_p.suffix.lower()
  154. # 读取原始数据
  155. if ext == ".jsonl":
  156. with open(input_path, "r", encoding="utf-8") as f:
  157. raw_data = [json.loads(line) for line in f if line.strip()]
  158. elif ext == ".json":
  159. with open(input_path, "r", encoding="utf-8") as f:
  160. try:
  161. data = json.load(f)
  162. raw_data = data if isinstance(data, list) else [data]
  163. except json.JSONDecodeError:
  164. # 回退到 JSONL 格式(每行一个 JSON 对象)
  165. f.seek(0)
  166. raw_data = [json.loads(line) for line in f if line.strip()]
  167. elif ext == ".csv":
  168. import csv
  169. with open(input_path, "r", encoding="utf-8") as f:
  170. reader = csv.DictReader(f)
  171. raw_data = [dict(row) for row in reader]
  172. elif ext == ".parquet":
  173. import pandas as pd
  174. df = pd.read_parquet(input_path)
  175. raw_data = df.to_dict(orient="records")
  176. else:
  177. raise ValueError(f"Unsupported format: {ext}")
  178. # 获取模板函数
  179. templates = TEMPLATE_MAP.get(task_type, TEMPLATE_MAP["sft"])
  180. apply_fn = templates.get(template, templates.get("raw", apply_raw_template))
  181. # Auto 模板:自动检测列名
  182. column_map = {}
  183. if template == "auto" and apply_fn is None:
  184. column_map = _detect_columns(raw_data)
  185. detected = column_map.get("template", "raw")
  186. if detected == "sharegpt":
  187. apply_fn = apply_sharegpt_template
  188. elif detected == "alpaca":
  189. apply_fn = apply_alpaca_template
  190. elif detected == "dpo":
  191. apply_fn = apply_dpo_template
  192. elif detected == "auto":
  193. apply_fn = lambda item, cm=column_map: apply_auto_template(item, cm)
  194. else:
  195. apply_fn = apply_raw_template
  196. # 应用模板
  197. processed = []
  198. for item in raw_data:
  199. try:
  200. result = apply_fn(item)
  201. if result.get("prompt"):
  202. processed.append(result)
  203. except Exception:
  204. continue
  205. # 写入处理后的数据(先删旧文件避免权限冲突)
  206. output_p = Path(output_path)
  207. output_p.parent.mkdir(parents=True, exist_ok=True)
  208. if output_p.exists():
  209. output_p.unlink()
  210. with open(output_path, "w", encoding="utf-8") as f:
  211. for item in processed:
  212. f.write(json.dumps(item, ensure_ascii=False) + "\n")
  213. return processed