lm_dataset.py 9.1 KB

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