dataset.py 9.9 KB

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