dataset.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. os.environ["TOKENIZERS_PARALLELISM"] = "false"
  11. class PretrainDataset(Dataset):
  12. def __init__(self, df, tokenizer, max_length=512):
  13. super().__init__()
  14. self.df = df
  15. self.tokenizer = tokenizer
  16. self.max_length = max_length
  17. self.padding = 0
  18. def __len__(self):
  19. return self.df.shape[0]
  20. def __getitem__(self, index: int):
  21. #
  22. sample = self.df.iloc[index]
  23. text = f"{self.tokenizer.bos_token}{str(sample['text'])}{self.tokenizer.eos_token}"
  24. input_id = self.tokenizer(text).data['input_ids'][:self.max_length]
  25. text_len = len(input_id)
  26. # 没满最大长度的剩余部分
  27. padding_len = self.max_length - text_len
  28. input_id = input_id + [self.padding] * padding_len
  29. # 0表示不计算损失
  30. loss_mask = [1] * text_len + [0] * padding_len
  31. input_id = np.array(input_id)
  32. X = np.array(input_id[:-1]).astype(np.int64)
  33. Y = np.array(input_id[1:]).astype(np.int64)
  34. loss_mask = np.array(loss_mask[1:]).astype(np.int64)
  35. return torch.from_numpy(X), torch.from_numpy(Y), torch.from_numpy(loss_mask)
  36. class SFTDataset(Dataset):
  37. def __init__(self, df, tokenizer, max_length=1024, prompt_max_len=512, answer_max_len=256):
  38. super().__init__()
  39. self.df = df
  40. self.max_length = max_length
  41. self.prompt_max_len = prompt_max_len
  42. self.answer_max_len = answer_max_len
  43. #
  44. self.tokenizer = tokenizer
  45. self.padding = 0
  46. self.bos_id = self.tokenizer('<s>assistant').data['input_ids']
  47. def __len__(self):
  48. return self.df.shape[0]
  49. def find_sublist_index(self, main_list, sub_list) -> int:
  50. last_index = -1
  51. for i in range(len(main_list) - len(sub_list) + 1):
  52. if main_list[i:i + len(sub_list)] == sub_list:
  53. last_index = i
  54. return last_index
  55. def safe_eval(self, s):
  56. try:
  57. res = eval(s)
  58. except Exception as e:
  59. return []
  60. return res
  61. def __getitem__(self, index: int):
  62. #
  63. sample = self.df.iloc[index]
  64. history = self.safe_eval(sample['history'])
  65. q = str(sample['q'])
  66. a = str(sample['a'])
  67. messages = []
  68. for history_message in history:
  69. if len(history_message) <= 1:
  70. continue
  71. messages.append(
  72. {"role": 'user', "content": str(history_message[0])[:self.max_length // 2]}
  73. )
  74. messages.append(
  75. {"role": 'assistant', "content": str(history_message[1])[:self.max_length // 2]}
  76. )
  77. messages += [
  78. {"role": "user", "content": q},
  79. {"role": "assistant", "content": a},
  80. ]
  81. new_prompt = self.tokenizer.apply_chat_template(
  82. messages,
  83. tokenize=False,
  84. add_generation_prompt=True
  85. )
  86. input_id = self.tokenizer(new_prompt).data['input_ids'][:self.max_length]
  87. # 实际长度
  88. question_length = self.find_sublist_index(input_id, self.bos_id) + len(self.bos_id)
  89. # 没满最大长度的剩余部分
  90. padding_len = self.max_length - len(input_id)
  91. input_id = input_id + [self.padding] * padding_len
  92. mask_len = len(input_id) - question_length - padding_len
  93. # 0表示不计算损失
  94. loss_mask = [0] * question_length + [1] * (mask_len) + [0] * padding_len
  95. input_id = np.array(input_id)
  96. X = np.array(input_id[:-1]).astype(np.int64)
  97. Y = np.array(input_id[1:]).astype(np.int64)
  98. loss_mask = np.array(loss_mask[1:]).astype(np.int64)
  99. X_tensor = torch.from_numpy(X)
  100. Y_tensor = torch.from_numpy(Y)
  101. loss_mask_tensor = torch.from_numpy(loss_mask)
  102. return X_tensor, Y_tensor, loss_mask_tensor
  103. if __name__ == "__main__":
  104. pass