__init__.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """数据预处理器:将不同格式的数据集转换为训练所需格式。"""
  2. import json
  3. from pathlib import Path
  4. from typing import Any
  5. def apply_alpaca_template(item: dict) -> dict:
  6. """Alpaca 模板: instruction + input -> output。"""
  7. instruction = item.get("instruction", "")
  8. input_text = item.get("input", "")
  9. output = item.get("output", "")
  10. prompt = f"{instruction}\n\n{input_text}" if input_text else instruction
  11. return {"prompt": prompt, "completion": output}
  12. def apply_sharegpt_template(item: dict) -> dict:
  13. """ShareGPT 模板: conversations list -> formatted prompt + completion。"""
  14. conversations = item.get("conversations", [])
  15. if len(conversations) < 2:
  16. return {"prompt": "", "completion": ""}
  17. prompt_parts = []
  18. completion = ""
  19. for i, turn in enumerate(conversations):
  20. role = turn.get("from", turn.get("role", "human"))
  21. content = turn.get("value", turn.get("content", ""))
  22. if i == 0:
  23. prompt_parts.append(content)
  24. elif i == 1:
  25. completion = content
  26. break
  27. else:
  28. prompt_parts.append(f"{role}: {content}")
  29. prompt = "\n".join(prompt_parts)
  30. return {"prompt": prompt, "completion": completion}
  31. def apply_raw_template(item: dict) -> dict:
  32. """Raw 模板: 直接读取 prompt/text 和 completion/output 字段。"""
  33. prompt = item.get("prompt", item.get("text", item.get("input", "")))
  34. completion = item.get("completion", item.get("output", item.get("target", "")))
  35. return {"prompt": str(prompt), "completion": str(completion)}
  36. def apply_dpo_template(item: dict) -> dict:
  37. """DPO 模板: prompt + chosen + rejected。"""
  38. return {
  39. "prompt": item.get("prompt", item.get("input", "")),
  40. "chosen": item.get("chosen", item.get("positive", "")),
  41. "rejected": item.get("rejected", item.get("negative", "")),
  42. }
  43. def apply_kto_template(item: dict) -> dict:
  44. """KTO 模板: prompt + completion + label。"""
  45. return {
  46. "prompt": item.get("prompt", item.get("input", "")),
  47. "completion": item.get("completion", item.get("output", "")),
  48. "label": item.get("label", True),
  49. }
  50. def apply_orpo_template(item: dict) -> dict:
  51. """ORPO 模板: prompt + chosen + rejected (类似 DPO)。"""
  52. return {
  53. "prompt": item.get("prompt", item.get("input", "")),
  54. "chosen": item.get("chosen", item.get("positive", "")),
  55. "rejected": item.get("rejected", item.get("negative", "")),
  56. }
  57. def apply_rm_template(item: dict) -> dict:
  58. """Reward Modeling 模板: prompt + chosen + rejected。"""
  59. return {
  60. "prompt": item.get("prompt", item.get("input", "")),
  61. "chosen": item.get("chosen", item.get("positive", "")),
  62. "rejected": item.get("rejected", item.get("negative", "")),
  63. }
  64. TEMPLATE_MAP = {
  65. "sft": {
  66. "alpaca": apply_alpaca_template,
  67. "sharegpt": apply_sharegpt_template,
  68. "raw": apply_raw_template,
  69. },
  70. "dpo": {
  71. "alpaca": apply_dpo_template,
  72. "sharegpt": apply_dpo_template,
  73. "raw": apply_dpo_template,
  74. },
  75. "kto": {
  76. "raw": apply_kto_template,
  77. },
  78. "orpo": {
  79. "alpaca": apply_orpo_template,
  80. "raw": apply_orpo_template,
  81. },
  82. "rm": {
  83. "raw": apply_rm_template,
  84. },
  85. "ppo": {
  86. "raw": apply_raw_template,
  87. },
  88. }
  89. def preprocess_file(
  90. input_path: str,
  91. output_path: str,
  92. task_type: str = "sft",
  93. template: str = "alpaca",
  94. ) -> list[dict[str, Any]]:
  95. """读取文件并应用模板,返回处理后的数据列表。"""
  96. input_p = Path(input_path)
  97. ext = input_p.suffix.lower()
  98. # 读取原始数据
  99. if ext == ".jsonl":
  100. with open(input_path, "r", encoding="utf-8") as f:
  101. raw_data = [json.loads(line) for line in f if line.strip()]
  102. elif ext == ".json":
  103. with open(input_path, "r", encoding="utf-8") as f:
  104. data = json.load(f)
  105. raw_data = data if isinstance(data, list) else [data]
  106. elif ext == ".csv":
  107. import csv
  108. with open(input_path, "r", encoding="utf-8") as f:
  109. reader = csv.DictReader(f)
  110. raw_data = [dict(row) for row in reader]
  111. elif ext == ".parquet":
  112. import pandas as pd
  113. df = pd.read_parquet(input_path)
  114. raw_data = df.to_dict(orient="records")
  115. else:
  116. raise ValueError(f"Unsupported format: {ext}")
  117. # 获取模板函数
  118. templates = TEMPLATE_MAP.get(task_type, TEMPLATE_MAP["sft"])
  119. apply_fn = templates.get(template, templates.get("raw", apply_raw_template))
  120. # 应用模板
  121. processed = []
  122. for item in raw_data:
  123. try:
  124. result = apply_fn(item)
  125. if result.get("prompt"):
  126. processed.append(result)
  127. except Exception:
  128. continue
  129. # 写入处理后的数据
  130. output_p = Path(output_path)
  131. output_p.parent.mkdir(parents=True, exist_ok=True)
  132. with open(output_path, "w", encoding="utf-8") as f:
  133. for item in processed:
  134. f.write(json.dumps(item, ensure_ascii=False) + "\n")
  135. return processed