dataset.py 3.8 KB

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