lm_dataset.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. encoding = self.tokenizer(
  17. str(sample['text']),
  18. max_length=self.max_length,
  19. padding='max_length',
  20. truncation=True,
  21. return_tensors='pt'
  22. )
  23. input_ids = encoding.input_ids.squeeze()
  24. labels = input_ids.clone()
  25. labels[input_ids == self.tokenizer.pad_token_id] = -100
  26. return input_ids, labels
  27. class SFTDataset(Dataset):
  28. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  29. super().__init__()
  30. self.tokenizer = tokenizer
  31. self.max_length = max_length
  32. self.samples = load_dataset('json', data_files=jsonl_path, split='train')
  33. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant\n', add_special_tokens=False).input_ids
  34. self.eos_id = tokenizer(f'{tokenizer.eos_token}\n', add_special_tokens=False).input_ids
  35. def __len__(self):
  36. return len(self.samples)
  37. def create_chat_prompt(self, cs):
  38. messages = cs.copy()
  39. tools = cs[0]["functions"] if (cs and cs[0]["role"] == "system" and cs[0].get("functions")) else None
  40. return self.tokenizer.apply_chat_template(
  41. messages,
  42. tokenize=False,
  43. add_generation_prompt=False,
  44. tools=tools
  45. )
  46. def generate_labels(self, input_ids):
  47. labels = [-100] * len(input_ids)
  48. i = 0
  49. while i < len(input_ids):
  50. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  51. start = i + len(self.bos_id)
  52. end = start
  53. while end < len(input_ids):
  54. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  55. break
  56. end += 1
  57. for j in range(start, min(end + len(self.eos_id), self.max_length)):
  58. labels[j] = input_ids[j]
  59. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  60. else:
  61. i += 1
  62. return labels
  63. def __getitem__(self, index):
  64. sample = self.samples[index]
  65. prompt = self.create_chat_prompt(sample['conversations'])
  66. input_ids = self.tokenizer(prompt).input_ids[:self.max_length]
  67. input_ids += [self.tokenizer.pad_token_id] * (self.max_length - len(input_ids))
  68. labels = self.generate_labels(input_ids)
  69. # # === 调试打印 ===
  70. # print(f"\n--- Sample {index} ---")
  71. # for i, (x, y) in enumerate(zip(input_ids[:-1], labels[1:])):
  72. # print(f"{i:3d}: X={self.tokenizer.decode([x])!r:16s} ---> Y={self.tokenizer.decode([input_ids[i+1]])!r:16s} label={y}")
  73. # # ================
  74. return torch.tensor(input_ids, dtype=torch.long), torch.tensor(labels, dtype=torch.long)
  75. class DPODataset(Dataset):
  76. def __init__(self, file_path, tokenizer, max_length=4096):
  77. super().__init__()
  78. self.tokenizer = tokenizer
  79. self.max_length = max_length
  80. self.padding = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
  81. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant\n', add_special_tokens=False).input_ids
  82. self.eos_id = tokenizer(f'{tokenizer.eos_token}\n', add_special_tokens=False).input_ids
  83. self.data = load_dataset('json', data_files=file_path, split='train')
  84. def __len__(self):
  85. return len(self.data)
  86. def __getitem__(self, index):
  87. item = self.data[index]
  88. chosen = item['chosen'] # 是一个 list,里面包含若干 {role, content}
  89. rejected = item['rejected'] # 同上
  90. chosen_prompt = self.tokenizer.apply_chat_template(
  91. chosen, tokenize=False, add_generation_prompt=False
  92. )
  93. rejected_prompt = self.tokenizer.apply_chat_template(
  94. rejected, tokenize=False, add_generation_prompt=False
  95. )
  96. chosen_encoding = self.tokenizer(
  97. chosen_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  98. )
  99. rejected_encoding = self.tokenizer(
  100. rejected_prompt, truncation=True, max_length=self.max_length, padding='max_length'
  101. )
  102. chosen_input_ids = chosen_encoding['input_ids']
  103. chosen_loss_mask = self.generate_loss_mask(chosen_input_ids)
  104. rejected_input_ids = rejected_encoding['input_ids']
  105. rejected_loss_mask = self.generate_loss_mask(rejected_input_ids)
  106. x_chosen = torch.tensor(chosen_input_ids[:-1], dtype=torch.long)
  107. y_chosen = torch.tensor(chosen_input_ids[1:], dtype=torch.long)
  108. mask_chosen = torch.tensor(chosen_loss_mask[1:], dtype=torch.long)
  109. x_rejected = torch.tensor(rejected_input_ids[:-1], dtype=torch.long)
  110. y_rejected = torch.tensor(rejected_input_ids[1:], dtype=torch.long)
  111. mask_rejected = torch.tensor(rejected_loss_mask[1:], dtype=torch.long)
  112. return {
  113. 'x_chosen': x_chosen,
  114. 'y_chosen': y_chosen,
  115. 'mask_chosen': mask_chosen,
  116. 'x_rejected': x_rejected,
  117. 'y_rejected': y_rejected,
  118. 'mask_rejected': mask_rejected
  119. }
  120. def generate_loss_mask(self, input_ids):
  121. loss_mask = [0] * len(input_ids)
  122. i = 0
  123. while i < len(input_ids):
  124. if input_ids[i:i + len(self.bos_id)] == self.bos_id:
  125. start = i + len(self.bos_id)
  126. end = start
  127. while end < len(input_ids):
  128. if input_ids[end:end + len(self.eos_id)] == self.eos_id:
  129. break
  130. end += 1
  131. for j in range(start, min(end + len(self.eos_id), self.max_length)):
  132. loss_mask[j] = 1
  133. i = end + len(self.eos_id) if end < len(input_ids) else len(input_ids)
  134. else:
  135. i += 1
  136. return loss_mask
  137. class RLAIFDataset(Dataset):
  138. def __init__(self, jsonl_path, tokenizer, max_length=1024):
  139. super().__init__()
  140. self.tokenizer = tokenizer
  141. self.max_length = max_length
  142. self.samples = load_dataset('json', data_files=jsonl_path, split='train')
  143. self.bos_id = tokenizer(f'{tokenizer.bos_token}assistant', add_special_tokens=False).input_ids
  144. self.eos_id = tokenizer(f'{tokenizer.eos_token}', add_special_tokens=False).input_ids
  145. def __len__(self):
  146. return len(self.samples)
  147. def create_chat_prompt(self, conversations):
  148. messages = []
  149. answer = ''
  150. for i, turn in enumerate(conversations):
  151. role = 'user' if i % 2 == 0 else 'assistant'
  152. messages.append({"role": role, "content": turn['content']})
  153. answer = turn['content']
  154. return self.tokenizer.apply_chat_template(
  155. messages[:-1],
  156. tokenize=False,
  157. add_generation_prompt=True # 这里需要True
  158. ), answer
  159. def __getitem__(self, index):
  160. sample = self.samples[index]
  161. prompt, answer = self.create_chat_prompt(sample['conversations'])
  162. return {
  163. 'prompt': prompt,
  164. 'answer': answer
  165. }
  166. if __name__ == "__main__":
  167. pass