dataset.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import os
  2. import math
  3. import json
  4. import numpy as np
  5. import torch
  6. from typing import List, Union
  7. from abc import ABC, abstractmethod
  8. from scipy.linalg import block_diag
  9. from itertools import accumulate
  10. from bisect import bisect_right
  11. from SwissArmyTransformer import get_tokenizer
  12. from .configs import BaseConfig, MultiChoiceTaskConfig, GenerationTaskConfig, LanguageModelTaskConfig
  13. from .utils import get_tokenized_input
  14. from .model import ModelForEvaluation
  15. def pad_batch(tokens, position_ids, attention_mask, max_seq_length):
  16. pad_length = max_seq_length - len(tokens)
  17. attention_mask = np.pad(
  18. attention_mask,
  19. pad_width=((0, pad_length),),
  20. mode="constant",
  21. constant_values=0,
  22. )
  23. tokens = np.concatenate((tokens, np.zeros(pad_length, dtype=np.int64)))
  24. position_ids = np.concatenate(
  25. (position_ids, np.zeros_like(position_ids[..., -1:], dtype=np.int64).repeat(pad_length, -1)), axis=-1
  26. )
  27. return tokens, position_ids, attention_mask
  28. class EvaluationDataset(torch.utils.data.Dataset, ABC):
  29. """
  30. Jsonlines of {
  31. "text": context
  32. "choices": [choice_id1,...], if not None, len(target) == 1
  33. "label": If generation task -1, else [0, len(choices))
  34. }
  35. If [MASK] not in context, will append [MASK] after text
  36. """
  37. def __init__(self, path: Union[str, List[str]], model: ModelForEvaluation, config: BaseConfig):
  38. self.path = path if isinstance(path, list) else [path]
  39. self.model = model
  40. self.config = config
  41. self.max_seq_length = self.config.max_seq_length
  42. self.dtype = np.int64
  43. self.tokenizer = get_tokenizer()
  44. self.mask_id = self.tokenizer.get_command("[MASK]")
  45. self.gmask_id = self.tokenizer.get_command("[gMASK]")
  46. self.data = []
  47. for p in self.path:
  48. self.process_single_file(p)
  49. @property
  50. def has_collate_fn(self) -> bool:
  51. return False
  52. def collate_fn(self, samples):
  53. return None
  54. def process_single_file(self, path):
  55. with open(os.path.join(path), "r", encoding="utf-8") as file:
  56. for line in file:
  57. item = json.loads(line)
  58. self.data.extend(self.process_single_item(item))
  59. @abstractmethod
  60. def process_single_item(self, item, **kwargs) -> List[dict]:
  61. pass
  62. def __len__(self):
  63. return len(self.data)
  64. class GenerationTaskDataset(EvaluationDataset):
  65. config: GenerationTaskConfig
  66. def process_single_item(self, item, **kwargs):
  67. text, targets = get_tokenized_input(item, "inputs"), get_tokenized_input(item, "targets")
  68. if len(targets) and (not isinstance(targets[0], list)):
  69. targets = [targets]
  70. if len(text) + self.config.max_gen_length + 2 > self.config.max_seq_length:
  71. text_length = self.config.max_seq_length - self.config.max_gen_length - 2
  72. text = text[len(text) - text_length : len(text)]
  73. return [{"text": text, "targets": targets, **kwargs}]
  74. @property
  75. def has_collate_fn(self) -> bool:
  76. return True
  77. def collate_fn(self, samples):
  78. TILE = 32
  79. length_to_pad = (max(map(lambda spl: len(spl["token"]), samples)) + TILE - 1) // TILE * TILE
  80. token_batch, position_id_batch, attention_mask_batch = [], [], []
  81. context_length_batch, target_position_id_batch = [], []
  82. for sample in samples:
  83. token, position_id, attention_mask = pad_batch(
  84. sample["token"], sample["position_id"], sample["attention_mask"], length_to_pad
  85. )
  86. token_batch.append(token)
  87. position_id_batch.append(position_id)
  88. attention_mask_batch.append(attention_mask)
  89. context_length_batch.append(sample["context_length"])
  90. target_position_id_batch.append(sample["target_position_id"])
  91. return {
  92. "tokens": torch.tensor(np.array(token_batch), dtype=torch.int64),
  93. "position_ids": torch.tensor(np.array(position_id_batch), dtype=torch.int64),
  94. "attention_mask": torch.tensor(np.array(attention_mask_batch), dtype=torch.int64) < 0.5,
  95. "context_length": torch.tensor(context_length_batch, dtype=torch.int64),
  96. "target_position_ids": torch.tensor(np.array(target_position_id_batch), dtype=torch.int64),
  97. }
  98. def __getitem__(self, idx):
  99. item = self.data[idx]
  100. sample = self.model.build_generation_sample(
  101. item["text"],
  102. max_gen_length=self.config.max_gen_length,
  103. use_task_mask=self.config.use_task_mask,
  104. unidirectional=self.config.unidirectional,
  105. )
  106. return sample
  107. class MultiChoiceTaskDataset(EvaluationDataset):
  108. config: MultiChoiceTaskConfig
  109. def __init__(self, path: Union[str, List[str]], model: ModelForEvaluation, config: BaseConfig):
  110. self.is_single_token = True # set to False later in process_single_item func
  111. super().__init__(path, model, config)
  112. @property
  113. def has_collate_fn(self) -> bool:
  114. return True
  115. def collate_fn(self, samples):
  116. TILE = 32
  117. length_to_pad = (max(map(lambda spl: len(spl["token"]), samples)) + TILE - 1) // TILE * TILE
  118. token_batch, position_id_batch, attention_mask_batch = [], [], []
  119. choices_batch, choice_target_ids_batch = [], []
  120. for sample in samples:
  121. token, position_id, attention_mask = pad_batch(
  122. sample["token"], sample["position_id"], sample["attention_mask"], length_to_pad
  123. )
  124. token_batch.append(token)
  125. position_id_batch.append(position_id)
  126. attention_mask_batch.append(attention_mask)
  127. choices_batch.append(sample["choices"])
  128. choice_target_ids_batch.append(sample["choice_target_ids"])
  129. return {
  130. "tokens": torch.tensor(np.array(token_batch), dtype=torch.int64),
  131. "position_ids": torch.tensor(np.array(position_id_batch), dtype=torch.int64),
  132. "attention_mask": torch.tensor(np.array(attention_mask_batch), dtype=torch.int64) < 0.5,
  133. "choices": choices_batch,
  134. "choice_target_ids": choice_target_ids_batch,
  135. "is_single_token": self.is_single_token,
  136. }
  137. def process_single_item(self, item, **kwargs):
  138. text, choices, label = get_tokenized_input(item, "inputs"), get_tokenized_input(item, "choices"), item["label"]
  139. tgt_seq_length = sum([len(choice) for choice in choices])
  140. if tgt_seq_length == len(choices):
  141. # For single token, we only insert one [sop]
  142. tgt_seq_length = 1
  143. assert tgt_seq_length < self.config.max_seq_length
  144. if len(text) + tgt_seq_length + 2 > self.config.max_seq_length:
  145. text_length = self.config.max_seq_length - tgt_seq_length - 2
  146. text = text[len(text) - text_length : len(text)]
  147. assert not (
  148. self.mask_id in text and self.config.use_multitask_encoding
  149. ), "Unified multitask encoding don't support blank filling"
  150. if tgt_seq_length != 1:
  151. self.is_single_token = False
  152. return [{"text": text, "choices": choices, "label": label, **kwargs}]
  153. def __getitem__(self, idx):
  154. item = self.data[idx]
  155. sample = self.model.build_multiple_choice_sample(
  156. item["text"],
  157. item["choices"],
  158. is_single_token=self.is_single_token,
  159. unified_multitask_encoding=self.config.use_multitask_encoding,
  160. unidirectional=self.config.unidirectional,
  161. use_task_mask=self.config.use_task_mask,
  162. )
  163. return sample
  164. class LanguageModelTaskDataset(EvaluationDataset):
  165. config: LanguageModelTaskConfig
  166. left_weights: List[int]
  167. weights: List[int]
  168. def process_single_file(self, path):
  169. num_sequences = []
  170. with open(os.path.join(path), "r", encoding="utf-8") as file:
  171. raw_text = file.read()
  172. tokens = self.tokenizer.tokenize(raw_text)
  173. self.data.append(
  174. {
  175. "raw_text": tokens,
  176. "num_original_tokens": len(raw_text.strip().split(" ")),
  177. "num_sequences": max(
  178. math.ceil(
  179. max(len(tokens) - (self.config.max_seq_length - 1), 0) / self.config.generation_length
  180. )
  181. + 1,
  182. 1,
  183. ),
  184. }
  185. )
  186. num_sequences.append(self.data[-1]["num_sequences"])
  187. self.weights = list(accumulate(num_sequences))
  188. self.left_weights = [0] + self.weights[:-1]
  189. def process_single_item(self, item):
  190. pass
  191. def __len__(self):
  192. return self.data[0]["num_sequences"]
  193. def __getitem__(self, idx):
  194. document_idx = bisect_right(self.weights, idx)
  195. idx = idx - self.left_weights[document_idx]
  196. start_idx = idx * self.config.generation_length
  197. end_idx = start_idx + self.config.max_seq_length - 1 # for additional [gMASK]
  198. tokens = self.data[document_idx]["raw_text"][start_idx:end_idx]
  199. return self.model.build_language_model_sample(
  200. tokens,
  201. is_first_segment=idx == 0,
  202. max_seq_length=self.config.max_seq_length,
  203. generation_length=self.config.generation_length,
  204. unidirectional=self.config.unidirectional,
  205. use_gmask=self.config.use_task_mask,
  206. )