lm_dataset.py 8.3 KB

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