lm_dataset.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. from torch.utils.data import Dataset
  2. import torch
  3. import json
  4. import os
  5. import random
  6. from datasets import load_dataset, Features, Sequence, Value
  7. os.environ["TOKENIZERS_PARALLELISM"] = "false"
  8. def pre_processing_chat(conversations, add_system_ratio=0.2):
  9. # tool use 数据完整保留不做处理
  10. if any(conv.get('tools') for conv in conversations): return conversations
  11. SYSTEM_PROMPTS = [
  12. "你是一个知识丰富的AI,尽力为用户提供准确的信息。",
  13. "你是minimind,一个小巧但有用的语言模型。",
  14. "你是一个专业的AI助手,请提供有价值的回答。",
  15. "你是minimind,请尽力帮助用户解决问题。",
  16. "你是一个可靠的AI,请给出准确的回答。",
  17. "You are a helpful AI assistant.",
  18. "You are minimind, a lightweight intelligent assistant.",
  19. "You are a friendly chatbot. Please answer the user's questions carefully.",
  20. "You are a knowledgeable AI. Try your best to provide accurate information.",
  21. "You are minimind, a small but useful language model."
  22. ]
  23. # 概率性添加system
  24. if conversations[0].get('role') != 'system':
  25. if random.random() < add_system_ratio:
  26. return [{'role': 'system', 'content': random.choice(SYSTEM_PROMPTS)}] + conversations
  27. return conversations
  28. def post_processing_chat(prompt_content, empty_think_ratio=0.2, remove_empty_think=None):
  29. # 以80%概率移除空思考标签
  30. if '<think>\n\n</think>\n\n' in prompt_content:
  31. if remove_empty_think is None:
  32. remove_empty_think = random.random() > empty_think_ratio
  33. if remove_empty_think:
  34. prompt_content = prompt_content.replace('<think>\n\n</think>\n\n', '')
  35. return prompt_content
  36. class PretrainDataset(Dataset):
  37. def __init__(self, data_path, tokenizer, max_length=512):
  38. super().__init__()
  39. self.tokenizer = tokenizer
  40. self.max_length = max_length
  41. self.samples = load_dataset('json', data_files=data_path, split='train')
  42. def __len__(self):
  43. return len(self.samples)
  44. def __getitem__(self, index):
  45. sample = self.samples[index]
  46. tokens = self.tokenizer(str(sample['text']), add_special_tokens=False, max_length=self.max_length - 2, truncation=True).input_ids
  47. tokens = [self.tokenizer.bos_token_id] + tokens + [self.tokenizer.eos_token_id]
  48. input_ids = tokens + [self.tokenizer.pad_token_id] * (self.max_length - len(tokens))
  49. input_ids = torch.tensor(input_ids, dtype=torch.long)
  50. labels = input_ids.clone()
  51. labels[input_ids == self.tokenizer.pad_token_id] = -100
  52. return input_ids, labels
  53. class SFTDataset(Dataset):
  54. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  55. super().__init__()
  56. self.tokenizer = tokenizer
  57. self.max_length = max_length
  58. features = Features({'conversations': [{'role': Value('string'), 'content': Value('string'), 'reasoning_content': Value('string'), 'tools': Value('string'), 'tool_calls': Value('string')}]})
  59. self.samples = load_dataset('json', data_files=jsonl_path, split='train', features=features)
  60. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant\n', add_special_tokens=False).input_ids
  61. self.eos_id = tokenizer(f'{tokenizer.eos_token}\n', add_special_tokens=False).input_ids
  62. def __len__(self):
  63. return len(self.samples)
  64. def create_chat_prompt(self, conversations):
  65. messages = []
  66. tools = None
  67. for message in conversations:
  68. message = dict(message)
  69. if message.get("role") == "system" and message.get("tools"):
  70. tools = json.loads(message["tools"]) if isinstance(message["tools"], str) else message["tools"]
  71. if message.get("tool_calls") and isinstance(message["tool_calls"], str):
  72. message["tool_calls"] = json.loads(message["tool_calls"])
  73. messages.append(message)
  74. return self.tokenizer.apply_chat_template(
  75. messages,
  76. tokenize=False,
  77. add_generation_prompt=False,
  78. tools=tools
  79. )
  80. def generate_labels(self, input_ids):
  81. labels = [-100] * len(input_ids)
  82. i = 0
  83. while i < len(input_ids):
  84. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  85. start = i + len(self.bos_id)
  86. end = start
  87. while end < len(input_ids):
  88. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  89. break
  90. end += 1
  91. for j in range(start, min(end + len(self.eos_id), self.max_length)):
  92. labels[j] = input_ids[j]
  93. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  94. else:
  95. i += 1
  96. return labels
  97. def __getitem__(self, index):
  98. sample = self.samples[index]
  99. conversations = pre_processing_chat(sample['conversations'])
  100. prompt = self.create_chat_prompt(conversations)
  101. prompt = post_processing_chat(prompt)
  102. input_ids = self.tokenizer(prompt).input_ids[:self.max_length]
  103. input_ids += [self.tokenizer.pad_token_id] * (self.max_length - len(input_ids))
  104. labels = self.generate_labels(input_ids)
  105. # # === 调试打印 ===
  106. # print(f"\n--- Sample {index} ---")
  107. # for i, (x, y) in enumerate(zip(input_ids[:-1], labels[1:])):
  108. # print(f"{i:3d}: X={self.tokenizer.decode([x])!r:16s} ---> Y={self.tokenizer.decode([input_ids[i+1]])!r:16s} label={y}")
  109. # # ================
  110. return torch.tensor(input_ids, dtype=torch.long), torch.tensor(labels, dtype=torch.long)
  111. class DPODataset(Dataset):
  112. def __init__(self, file_path, tokenizer, max_length=4096):
  113. super().__init__()
  114. self.tokenizer = tokenizer
  115. self.max_length = max_length
  116. self.padding = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
  117. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant\n', add_special_tokens=False).input_ids
  118. self.eos_id = tokenizer(f'{tokenizer.eos_token}\n', add_special_tokens=False).input_ids
  119. self.samples = load_dataset('json', data_files=file_path, split='train')
  120. def __len__(self):
  121. return len(self.samples)
  122. def __getitem__(self, index):
  123. sample = self.samples[index]
  124. chosen = sample['chosen'] # 是一个 list,里面包含若干 {role, content}
  125. rejected = sample['rejected'] # 同上
  126. chosen_prompt = self.tokenizer.apply_chat_template(
  127. chosen, tokenize=False, add_generation_prompt=False
  128. )
  129. rejected_prompt = self.tokenizer.apply_chat_template(
  130. rejected, tokenize=False, add_generation_prompt=False
  131. )
  132. remove_empty_think = random.random() > 0.2
  133. chosen_prompt = post_processing_chat(chosen_prompt, remove_empty_think=remove_empty_think)
  134. rejected_prompt = post_processing_chat(rejected_prompt, remove_empty_think=remove_empty_think)
  135. chosen_encoding = self.tokenizer(
  136. chosen_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  137. )
  138. rejected_encoding = self.tokenizer(
  139. rejected_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  140. )
  141. chosen_input_ids = chosen_encoding['input_ids']
  142. chosen_loss_mask = self.generate_loss_mask(chosen_input_ids)
  143. rejected_input_ids = rejected_encoding['input_ids']
  144. rejected_loss_mask = self.generate_loss_mask(rejected_input_ids)
  145. x_chosen = torch.tensor(chosen_input_ids[:-1], dtype=torch.long)
  146. y_chosen = torch.tensor(chosen_input_ids[1:], dtype=torch.long)
  147. mask_chosen = torch.tensor(chosen_loss_mask[1:], dtype=torch.long)
  148. x_rejected = torch.tensor(rejected_input_ids[:-1], dtype=torch.long)
  149. y_rejected = torch.tensor(rejected_input_ids[1:], dtype=torch.long)
  150. mask_rejected = torch.tensor(rejected_loss_mask[1:], dtype=torch.long)
  151. return {
  152. 'x_chosen': x_chosen,
  153. 'y_chosen': y_chosen,
  154. 'mask_chosen': mask_chosen,
  155. 'x_rejected': x_rejected,
  156. 'y_rejected': y_rejected,
  157. 'mask_rejected': mask_rejected
  158. }
  159. def generate_loss_mask(self, input_ids):
  160. loss_mask = [0] * len(input_ids)
  161. i = 0
  162. while i < len(input_ids):
  163. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  164. start = i + len(self.bos_id)
  165. end = start
  166. while end < len(input_ids):
  167. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  168. break
  169. end += 1
  170. for j in range(start, min(end + len(self.eos_id), self.max_length)):
  171. loss_mask[j] = 1
  172. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  173. else:
  174. i += 1
  175. return loss_mask
  176. class RLAIFDataset(Dataset):
  177. def __init__(self, jsonl_path, tokenizer, max_length=1024, thinking_ratio=0.5):
  178. super().__init__()
  179. self.tokenizer = tokenizer
  180. self.max_length = max_length
  181. self.thinking_ratio = thinking_ratio # 按概率开启 thinking
  182. self.samples = load_dataset('json', data_files=jsonl_path, split='train')
  183. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant', add_special_tokens=False).input_ids
  184. self.eos_id = tokenizer(f'{tokenizer.eos_token}', add_special_tokens=False).input_ids
  185. def __len__(self):
  186. return len(self.samples)
  187. def create_chat_prompt(self, conversations):
  188. conversations = pre_processing_chat(conversations)
  189. use_thinking = random.random() < self.thinking_ratio
  190. return self.tokenizer.apply_chat_template(
  191. conversations[:-1],
  192. tokenize=False,
  193. open_thinking=use_thinking,
  194. add_generation_prompt=True
  195. )
  196. def __getitem__(self, index):
  197. sample = self.samples[index]
  198. prompt = self.create_chat_prompt(sample['conversations'])
  199. return {
  200. 'prompt': prompt,
  201. 'answer': ""
  202. }
  203. class AgentRLDataset(Dataset):
  204. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  205. super().__init__()
  206. self.tokenizer = tokenizer
  207. self.max_length = max_length
  208. self.samples = []
  209. with open(jsonl_path, 'r', encoding='utf-8') as f:
  210. for line in f:
  211. self.samples.append(json.loads(line.strip()))
  212. def __len__(self):
  213. return len(self.samples)
  214. def parse_conversations(self, conversations):
  215. messages = []
  216. tools = None
  217. for message in conversations:
  218. message = dict(message)
  219. if message.get("role") == "system" and message.get("tools"):
  220. tools = json.loads(message["tools"]) if isinstance(message["tools"], str) else message["tools"]
  221. messages.append(message)
  222. return messages[:-1], tools
  223. def __getitem__(self, index):
  224. sample = self.samples[index]
  225. messages, tools = self.parse_conversations(sample['conversations'])
  226. return {'messages': messages, 'tools': tools, 'gt': sample['gt']}
  227. if __name__ == "__main__":
  228. pass