lm_dataset.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import json
  2. import random
  3. import re
  4. import pandas as pd
  5. import numpy as np
  6. from torch.utils.data import Dataset, DataLoader
  7. import torch
  8. from sklearn.model_selection import train_test_split
  9. import os
  10. import ast
  11. os.environ["TOKENIZERS_PARALLELISM"] = "false"
  12. class PretrainDataset(Dataset):
  13. def __init__(self, data_path, tokenizer, max_length=512):
  14. super().__init__()
  15. self.tokenizer = tokenizer
  16. self.max_length = max_length
  17. self.samples = self.load_data(data_path)
  18. def load_data(self, path):
  19. samples = []
  20. with open(path, 'r', encoding='utf-8') as f:
  21. for line_num, line in enumerate(f, 1):
  22. data = json.loads(line.strip())
  23. samples.append(data)
  24. return samples
  25. def __len__(self):
  26. return len(self.samples)
  27. def __getitem__(self, index):
  28. sample = self.samples[index]
  29. # 构建输入文本
  30. encoding = self.tokenizer(
  31. str(sample['text']),
  32. max_length=self.max_length,
  33. padding='max_length',
  34. truncation=True,
  35. return_tensors='pt'
  36. )
  37. input_ids = encoding.input_ids.squeeze()
  38. loss_mask = (input_ids != self.tokenizer.pad_token_id)
  39. X = torch.tensor(input_ids[:-1], dtype=torch.long)
  40. Y = torch.tensor(input_ids[1:], dtype=torch.long)
  41. loss_mask = torch.tensor(loss_mask[1:], dtype=torch.long)
  42. return X, Y, loss_mask
  43. class SFTDataset(Dataset):
  44. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  45. super().__init__()
  46. self.tokenizer = tokenizer
  47. self.max_length = max_length
  48. self.samples = self.load_data(jsonl_path)
  49. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant', add_special_tokens=False).input_ids
  50. self.eos_id = tokenizer(f'{tokenizer.eos_token}', add_special_tokens=False).input_ids
  51. def __len__(self):
  52. return len(self.samples)
  53. def load_data(self, path):
  54. samples = []
  55. with open(path, 'r', encoding='utf-8') as f:
  56. for line_num, line in enumerate(f, 1):
  57. data = json.loads(line.strip())
  58. samples.append(data)
  59. return samples
  60. def _create_chat_prompt(self, cs):
  61. messages = cs.copy()
  62. tools = cs[0]["functions"] if (cs and cs[0]["role"] == "system" and cs[0].get("functions")) else None
  63. return self.tokenizer.apply_chat_template(
  64. messages,
  65. tokenize=False,
  66. add_generation_prompt=False,
  67. tools=tools
  68. )
  69. def _generate_loss_mask(self, input_ids):
  70. loss_mask = [0] * len(input_ids)
  71. i = 0
  72. while i < len(input_ids):
  73. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  74. start = i + len(self.bos_id)
  75. end = start
  76. while end < len(input_ids):
  77. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  78. break
  79. end += 1
  80. for j in range(start + 1, min(end + len(self.eos_id) + 1, self.max_length)):
  81. loss_mask[j] = 1
  82. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  83. else:
  84. i += 1
  85. return loss_mask
  86. def __getitem__(self, index):
  87. sample = self.samples[index]
  88. # 构建对话提示
  89. prompt = self._create_chat_prompt(sample['conversations'])
  90. input_ids = self.tokenizer(prompt).input_ids[:self.max_length]
  91. input_ids += [self.tokenizer.pad_token_id] * (self.max_length - len(input_ids))
  92. # 生成动态损失掩码
  93. loss_mask = self._generate_loss_mask(input_ids)
  94. # 构建训练数据
  95. X = torch.tensor(input_ids[:-1], dtype=torch.long)
  96. Y = torch.tensor(input_ids[1:], dtype=torch.long)
  97. loss_mask = torch.tensor(loss_mask[1:], dtype=torch.long) # 对齐预测位置
  98. # # === 打印每个token的掩码情况 ===
  99. # print(f"\n--- Sample {index} Token Loss Mask (length: {len(input_ids)}) ---")
  100. # for i, (token_id, mask) in enumerate(zip(input_ids, loss_mask)):
  101. # token_str = self.tokenizer.decode([token_id], skip_special_tokens=False)
  102. # token_str = token_str.replace('\n', '\\n').replace('\t', '\\t') # 处理换行等不可见字符
  103. # print(f"Token {i:3d}: {token_id:5d} -> '{token_str:10s}' | mask: {mask}")
  104. # print(f"--- End of Sample {index} ---")
  105. # # ================================
  106. return X, Y, loss_mask
  107. class DPODataset(Dataset):
  108. def __init__(self, file_path, tokenizer, max_length=4096):
  109. super().__init__()
  110. self.tokenizer = tokenizer
  111. self.max_length = max_length
  112. self.padding = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
  113. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant', add_special_tokens=False).input_ids
  114. self.eos_id = tokenizer(f'{tokenizer.eos_token}', add_special_tokens=False).input_ids
  115. with open(file_path, 'r', encoding='utf-8') as f:
  116. self.data = []
  117. for line in f:
  118. line = line.strip()
  119. obj = json.loads(line)
  120. self.data.append(obj)
  121. def __len__(self):
  122. return len(self.data)
  123. def __getitem__(self, index):
  124. item = self.data[index]
  125. chosen = item['chosen'] # 是一个 list,里面包含若干 {role, content}
  126. rejected = item['rejected'] # 同上
  127. chosen_prompt = self.tokenizer.apply_chat_template(
  128. chosen, tokenize=False, add_generation_prompt=False
  129. )
  130. rejected_prompt = self.tokenizer.apply_chat_template(
  131. rejected, tokenize=False, add_generation_prompt=False
  132. )
  133. chosen_encoding = self.tokenizer(
  134. chosen_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  135. )
  136. rejected_encoding = self.tokenizer(
  137. rejected_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  138. )
  139. chosen_input_ids = chosen_encoding['input_ids']
  140. chosen_loss_mask = self._generate_loss_mask(chosen_input_ids)
  141. rejected_input_ids = rejected_encoding['input_ids']
  142. rejected_loss_mask = self._generate_loss_mask(rejected_input_ids)
  143. x_chosen = torch.tensor(chosen_input_ids[:-1], dtype=torch.long)
  144. y_chosen = torch.tensor(chosen_input_ids[1:], dtype=torch.long)
  145. mask_chosen = torch.tensor(chosen_loss_mask[1:], dtype=torch.long)
  146. x_rejected = torch.tensor(rejected_input_ids[:-1], dtype=torch.long)
  147. y_rejected = torch.tensor(rejected_input_ids[1:], dtype=torch.long)
  148. mask_rejected = torch.tensor(rejected_loss_mask[1:], dtype=torch.long)
  149. return {
  150. 'x_chosen': x_chosen,
  151. 'y_chosen': y_chosen,
  152. 'mask_chosen': mask_chosen,
  153. 'x_rejected': x_rejected,
  154. 'y_rejected': y_rejected,
  155. 'mask_rejected': mask_rejected
  156. }
  157. def _generate_loss_mask(self, input_ids):
  158. loss_mask = [0] * len(input_ids)
  159. i = 0
  160. while i < len(input_ids):
  161. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  162. start = i + len(self.bos_id)
  163. end = start
  164. while end < len(input_ids):
  165. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  166. break
  167. end += 1
  168. for j in range(start + 1, min(end + len(self.eos_id) + 1, self.max_length)):
  169. loss_mask[j] = 1
  170. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  171. else:
  172. i += 1
  173. return loss_mask
  174. class RLAIFDataset(Dataset):
  175. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  176. super().__init__()
  177. self.tokenizer = tokenizer
  178. self.max_length = max_length
  179. self.samples = self.load_data(jsonl_path)
  180. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant', add_special_tokens=False).input_ids
  181. self.eos_id = tokenizer(f'{tokenizer.eos_token}', add_special_tokens=False).input_ids
  182. def __len__(self):
  183. return len(self.samples)
  184. def load_data(self, path):
  185. samples = []
  186. with open(path, 'r', encoding='utf-8') as f:
  187. for line_num, line in enumerate(f, 1):
  188. data = json.loads(line.strip())
  189. samples.append(data)
  190. return samples
  191. def _create_chat_prompt(self, conversations):
  192. """构建符合ChatML格式的对话"""
  193. messages = []
  194. answer = ''
  195. for i, turn in enumerate(conversations):
  196. role = 'user' if i % 2 == 0 else 'assistant'
  197. messages.append({"role": role, "content": turn['content']})
  198. answer = turn['content']
  199. return self.tokenizer.apply_chat_template(
  200. messages[:-1],
  201. tokenize=False,
  202. add_generation_prompt=True # 这里需要True
  203. ), answer
  204. def __getitem__(self, index):
  205. sample = self.samples[index]
  206. # 构建对话提示
  207. prompt, answer = self._create_chat_prompt(sample['conversations'])
  208. return {
  209. 'prompt': prompt,
  210. 'answer': answer
  211. }
  212. if __name__ == "__main__":
  213. pass