dataset.py 4.1 KB

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