lm_dataset.py 8.1 KB

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