lm_dataset.py 8.6 KB

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