dataset.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. text = f"{self.tokenizer.bos_token}{str(sample['text'])}{self.tokenizer.eos_token}"
  31. encoding = self.tokenizer(
  32. text,
  33. max_length=self.max_length,
  34. padding='max_length',
  35. truncation=True,
  36. return_tensors='pt'
  37. )
  38. input_ids = encoding.input_ids.squeeze()
  39. loss_mask = (input_ids != self.tokenizer.pad_token_id)
  40. X = torch.tensor(input_ids[:-1], dtype=torch.long)
  41. Y = torch.tensor(input_ids[1:], dtype=torch.long)
  42. loss_mask = torch.tensor(loss_mask[1:], dtype=torch.long)
  43. return X, Y, loss_mask
  44. class SFTDataset(Dataset):
  45. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  46. super().__init__()
  47. self.tokenizer = tokenizer
  48. self.max_length = max_length
  49. self.samples = self.load_data(jsonl_path)
  50. self.bos_id = tokenizer('<s>assistant', add_special_tokens=False).input_ids
  51. self.eos_id = tokenizer('</s>', add_special_tokens=False).input_ids
  52. def __len__(self):
  53. return len(self.samples)
  54. def load_data(self, path):
  55. samples = []
  56. with open(path, 'r', encoding='utf-8') as f:
  57. for line_num, line in enumerate(f, 1):
  58. data = json.loads(line.strip())
  59. samples.append(data)
  60. return samples
  61. def _create_chat_prompt(self, conversations):
  62. """构建符合ChatML格式的对话"""
  63. messages = []
  64. for i, turn in enumerate(conversations):
  65. role = 'user' if i % 2 == 0 else 'assistant'
  66. messages.append({"role": role, "content": turn['content']})
  67. return self.tokenizer.apply_chat_template(
  68. messages,
  69. tokenize=False,
  70. add_generation_prompt=False
  71. )
  72. def _generate_loss_mask(self, input_ids):
  73. loss_mask = [0] * len(input_ids)
  74. i = 0
  75. while i < len(input_ids):
  76. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  77. start = i + len(self.bos_id)
  78. end = start
  79. while end < len(input_ids):
  80. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  81. break
  82. end += 1
  83. for j in range(start + 1, min(end + len(self.eos_id) + 1, self.max_length)):
  84. loss_mask[j] = 1
  85. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  86. else:
  87. i += 1
  88. return loss_mask
  89. def __getitem__(self, index):
  90. sample = self.samples[index]
  91. # 构建对话提示
  92. prompt = self._create_chat_prompt(sample['conversations'])
  93. input_ids = self.tokenizer(prompt).input_ids[:self.max_length]
  94. input_ids += [self.tokenizer.pad_token_id] * (self.max_length - len(input_ids))
  95. # 生成动态损失掩码
  96. loss_mask = self._generate_loss_mask(input_ids)
  97. # 构建训练数据
  98. X = torch.tensor(input_ids[:-1], dtype=torch.long)
  99. Y = torch.tensor(input_ids[1:], dtype=torch.long)
  100. loss_mask = torch.tensor(loss_mask[1:], dtype=torch.long) # 对齐预测位置
  101. return X, Y, loss_mask
  102. class DPODataset(Dataset):
  103. def __init__(self, file_path, tokenizer, max_length=4096):
  104. super().__init__()
  105. self.tokenizer = tokenizer
  106. self.max_length = max_length
  107. self.padding = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
  108. self.bos_id = tokenizer('<s>assistant', add_special_tokens=False).input_ids
  109. self.eos_id = tokenizer('</s>', add_special_tokens=False).input_ids
  110. with open(file_path, 'r', encoding='utf-8') as f:
  111. self.data = []
  112. for line in f:
  113. line = line.strip()
  114. obj = json.loads(line)
  115. self.data.append(obj)
  116. def __len__(self):
  117. return len(self.data)
  118. def __getitem__(self, index):
  119. item = self.data[index]
  120. chosen = item['chosen'] # 是一个 list,里面包含若干 {role, content}
  121. rejected = item['rejected'] # 同上
  122. chosen_prompt = self.tokenizer.apply_chat_template(
  123. chosen, tokenize=False, add_generation_prompt=False
  124. )
  125. rejected_prompt = self.tokenizer.apply_chat_template(
  126. rejected, tokenize=False, add_generation_prompt=False
  127. )
  128. chosen_encoding = self.tokenizer(
  129. chosen_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  130. )
  131. rejected_encoding = self.tokenizer(
  132. rejected_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  133. )
  134. chosen_input_ids = chosen_encoding['input_ids']
  135. chosen_loss_mask = self._generate_loss_mask(chosen_input_ids)
  136. rejected_input_ids = rejected_encoding['input_ids']
  137. rejected_loss_mask = self._generate_loss_mask(rejected_input_ids)
  138. x_chosen = torch.tensor(chosen_input_ids[:-1], dtype=torch.long)
  139. y_chosen = torch.tensor(chosen_input_ids[1:], dtype=torch.long)
  140. mask_chosen = torch.tensor(chosen_loss_mask[1:], dtype=torch.long)
  141. x_rejected = torch.tensor(rejected_input_ids[:-1], dtype=torch.long)
  142. y_rejected = torch.tensor(rejected_input_ids[1:], dtype=torch.long)
  143. mask_rejected = torch.tensor(rejected_loss_mask[1:], dtype=torch.long)
  144. return {
  145. 'x_chosen': x_chosen,
  146. 'y_chosen': y_chosen,
  147. 'mask_chosen': mask_chosen,
  148. 'x_rejected': x_rejected,
  149. 'y_rejected': y_rejected,
  150. 'mask_rejected': mask_rejected
  151. }
  152. def _generate_loss_mask(self, input_ids):
  153. loss_mask = [0] * len(input_ids)
  154. i = 0
  155. while i < len(input_ids):
  156. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  157. start = i + len(self.bos_id)
  158. end = start
  159. while end < len(input_ids):
  160. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  161. break
  162. end += 1
  163. for j in range(start + 1, min(end + len(self.eos_id) + 1, self.max_length)):
  164. loss_mask[j] = 1
  165. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  166. else:
  167. i += 1
  168. return loss_mask
  169. class RLAIFDataset(Dataset):
  170. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  171. super().__init__()
  172. self.tokenizer = tokenizer
  173. self.max_length = max_length
  174. self.samples = self.load_data(jsonl_path)
  175. self.bos_id = tokenizer('<s>assistant', add_special_tokens=False).input_ids
  176. self.eos_id = tokenizer('</s>', add_special_tokens=False).input_ids
  177. def __len__(self):
  178. return len(self.samples)
  179. def load_data(self, path):
  180. samples = []
  181. with open(path, 'r', encoding='utf-8') as f:
  182. for line_num, line in enumerate(f, 1):
  183. data = json.loads(line.strip())
  184. samples.append(data)
  185. return samples
  186. def _create_chat_prompt(self, conversations):
  187. """构建符合ChatML格式的对话"""
  188. messages = []
  189. answer = ''
  190. for i, turn in enumerate(conversations):
  191. role = 'user' if i % 2 == 0 else 'assistant'
  192. messages.append({"role": role, "content": turn['content']})
  193. answer = turn['content']
  194. return self.tokenizer.apply_chat_template(
  195. messages[:-1],
  196. tokenize=False,
  197. add_generation_prompt=True
  198. ), answer
  199. def __getitem__(self, index):
  200. sample = self.samples[index]
  201. # 构建对话提示
  202. prompt, answer = self._create_chat_prompt(sample['conversations'])
  203. return {
  204. 'prompt': prompt,
  205. 'answer': answer
  206. }
  207. if __name__ == "__main__":
  208. pass