lm_dataset.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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):
  29. # 以80%概率移除空思考标签
  30. if '<think>\n\n</think>\n\n' in prompt_content and random.random() > empty_think_ratio:
  31. prompt_content = prompt_content.replace('<think>\n\n</think>\n\n', '')
  32. return prompt_content
  33. class PretrainDataset(Dataset):
  34. def __init__(self, data_path, tokenizer, max_length=512):
  35. super().__init__()
  36. self.tokenizer = tokenizer
  37. self.max_length = max_length
  38. self.samples = load_dataset('json', data_files=data_path, split='train')
  39. def __len__(self):
  40. return len(self.samples)
  41. def __getitem__(self, index):
  42. sample = self.samples[index]
  43. tokens = self.tokenizer(str(sample['text']), add_special_tokens=False, max_length=self.max_length - 2, truncation=True).input_ids
  44. tokens = [self.tokenizer.bos_token_id] + tokens + [self.tokenizer.eos_token_id]
  45. input_ids = tokens + [self.tokenizer.pad_token_id] * (self.max_length - len(tokens))
  46. input_ids = torch.tensor(input_ids, dtype=torch.long)
  47. labels = input_ids.clone()
  48. labels[input_ids == self.tokenizer.pad_token_id] = -100
  49. return input_ids, labels
  50. class SFTDataset(Dataset):
  51. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  52. super().__init__()
  53. self.tokenizer = tokenizer
  54. self.max_length = max_length
  55. features = Features({'conversations': [{'role': Value('string'), 'content': Value('string'), 'reasoning_content': Value('string'), 'tools': Value('string'), 'tool_calls': Value('string')}]})
  56. self.samples = load_dataset('json', data_files=jsonl_path, split='train', features=features)
  57. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant\n', add_special_tokens=False).input_ids
  58. self.eos_id = tokenizer(f'{tokenizer.eos_token}\n', add_special_tokens=False).input_ids
  59. def __len__(self):
  60. return len(self.samples)
  61. def create_chat_prompt(self, conversations):
  62. messages = []
  63. tools = None
  64. for message in conversations:
  65. message = dict(message)
  66. if message.get("role") == "system" and message.get("tools"):
  67. tools = json.loads(message["tools"]) if isinstance(message["tools"], str) else message["tools"]
  68. if message.get("tool_calls") and isinstance(message["tool_calls"], str):
  69. message["tool_calls"] = json.loads(message["tool_calls"])
  70. messages.append(message)
  71. return self.tokenizer.apply_chat_template(
  72. messages,
  73. tokenize=False,
  74. add_generation_prompt=False,
  75. tools=tools
  76. )
  77. def generate_labels(self, input_ids):
  78. labels = [-100] * len(input_ids)
  79. i = 0
  80. while i < len(input_ids):
  81. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  82. start = i + len(self.bos_id)
  83. end = start
  84. while end < len(input_ids):
  85. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  86. break
  87. end += 1
  88. for j in range(start, min(end + len(self.eos_id), self.max_length)):
  89. labels[j] = input_ids[j]
  90. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  91. else:
  92. i += 1
  93. return labels
  94. def __getitem__(self, index):
  95. sample = self.samples[index]
  96. conversations = pre_processing_chat(sample['conversations'])
  97. prompt = self.create_chat_prompt(conversations)
  98. prompt = post_processing_chat(prompt)
  99. input_ids = self.tokenizer(prompt).input_ids[:self.max_length]
  100. input_ids += [self.tokenizer.pad_token_id] * (self.max_length - len(input_ids))
  101. labels = self.generate_labels(input_ids)
  102. # # === 调试打印 ===
  103. # print(f"\n--- Sample {index} ---")
  104. # for i, (x, y) in enumerate(zip(input_ids[:-1], labels[1:])):
  105. # print(f"{i:3d}: X={self.tokenizer.decode([x])!r:16s} ---> Y={self.tokenizer.decode([input_ids[i+1]])!r:16s} label={y}")
  106. # # ================
  107. return torch.tensor(input_ids, dtype=torch.long), torch.tensor(labels, dtype=torch.long)
  108. class DPODataset(Dataset):
  109. def __init__(self, file_path, tokenizer, max_length=4096):
  110. super().__init__()
  111. self.tokenizer = tokenizer
  112. self.max_length = max_length
  113. self.padding = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
  114. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant\n', add_special_tokens=False).input_ids
  115. self.eos_id = tokenizer(f'{tokenizer.eos_token}\n', add_special_tokens=False).input_ids
  116. self.samples = load_dataset('json', data_files=file_path, split='train')
  117. def __len__(self):
  118. return len(self.samples)
  119. def __getitem__(self, index):
  120. sample = self.samples[index]
  121. chosen = sample['chosen'] # 是一个 list,里面包含若干 {role, content}
  122. rejected = sample['rejected'] # 同上
  123. chosen_prompt = self.tokenizer.apply_chat_template(
  124. chosen, tokenize=False, add_generation_prompt=False
  125. )
  126. chosen_prompt = post_processing_chat(chosen_prompt)
  127. rejected_prompt = self.tokenizer.apply_chat_template(
  128. rejected, tokenize=False, add_generation_prompt=False
  129. )
  130. rejected_prompt = post_processing_chat(rejected_prompt)
  131. chosen_encoding = self.tokenizer(
  132. chosen_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  133. )
  134. rejected_encoding = self.tokenizer(
  135. rejected_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  136. )
  137. chosen_input_ids = chosen_encoding['input_ids']
  138. chosen_loss_mask = self.generate_loss_mask(chosen_input_ids)
  139. rejected_input_ids = rejected_encoding['input_ids']
  140. rejected_loss_mask = self.generate_loss_mask(rejected_input_ids)
  141. x_chosen = torch.tensor(chosen_input_ids[:-1], dtype=torch.long)
  142. y_chosen = torch.tensor(chosen_input_ids[1:], dtype=torch.long)
  143. mask_chosen = torch.tensor(chosen_loss_mask[1:], dtype=torch.long)
  144. x_rejected = torch.tensor(rejected_input_ids[:-1], dtype=torch.long)
  145. y_rejected = torch.tensor(rejected_input_ids[1:], dtype=torch.long)
  146. mask_rejected = torch.tensor(rejected_loss_mask[1:], dtype=torch.long)
  147. return {
  148. 'x_chosen': x_chosen,
  149. 'y_chosen': y_chosen,
  150. 'mask_chosen': mask_chosen,
  151. 'x_rejected': x_rejected,
  152. 'y_rejected': y_rejected,
  153. 'mask_rejected': mask_rejected
  154. }
  155. def generate_loss_mask(self, input_ids):
  156. loss_mask = [0] * len(input_ids)
  157. i = 0
  158. while i < len(input_ids):
  159. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  160. start = i + len(self.bos_id)
  161. end = start
  162. while end < len(input_ids):
  163. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  164. break
  165. end += 1
  166. for j in range(start, min(end + len(self.eos_id), self.max_length)):
  167. loss_mask[j] = 1
  168. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  169. else:
  170. i += 1
  171. return loss_mask
  172. class RLAIFDataset(Dataset):
  173. def __init__(self, jsonl_path, tokenizer, max_length=1024, thinking_ratio=0.5):
  174. super().__init__()
  175. self.tokenizer = tokenizer
  176. self.max_length = max_length
  177. self.thinking_ratio = thinking_ratio # 按概率开启 thinking
  178. self.samples = load_dataset('json', data_files=jsonl_path, split='train')
  179. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant', add_special_tokens=False).input_ids
  180. self.eos_id = tokenizer(f'{tokenizer.eos_token}', add_special_tokens=False).input_ids
  181. def __len__(self):
  182. return len(self.samples)
  183. def create_chat_prompt(self, conversations):
  184. conversations = pre_processing_chat(conversations)
  185. use_thinking = random.random() < self.thinking_ratio
  186. return self.tokenizer.apply_chat_template(
  187. conversations[:-1],
  188. tokenize=False,
  189. open_thinking=use_thinking,
  190. add_generation_prompt=True
  191. )
  192. def __getitem__(self, index):
  193. sample = self.samples[index]
  194. prompt = self.create_chat_prompt(sample['conversations'])
  195. return {
  196. 'prompt': prompt,
  197. 'answer': ""
  198. }
  199. class AgentRLDataset(Dataset):
  200. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  201. super().__init__()
  202. self.tokenizer = tokenizer
  203. self.max_length = max_length
  204. self.samples = []
  205. with open(jsonl_path, 'r', encoding='utf-8') as f:
  206. for line in f:
  207. self.samples.append(json.loads(line.strip()))
  208. def __len__(self):
  209. return len(self.samples)
  210. def parse_conversations(self, conversations):
  211. messages = []
  212. tools = None
  213. for message in conversations:
  214. message = dict(message)
  215. if message.get("role") == "system" and message.get("tools"):
  216. tools = json.loads(message["tools"]) if isinstance(message["tools"], str) else message["tools"]
  217. messages.append(message)
  218. return messages[:-1], tools
  219. def __getitem__(self, index):
  220. sample = self.samples[index]
  221. messages, tools = self.parse_conversations(sample['conversations'])
  222. return {'messages': messages, 'tools': tools, 'gt': sample['gt']}
  223. if __name__ == "__main__":
  224. pass