dataset.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. def pad_batch(tokens, position_ids, attention_mask, max_seq_length):
  15. attention_mask = np.pad(
  16. attention_mask,
  17. pad_width=((0, max_seq_length - len(tokens)),),
  18. mode="constant",
  19. constant_values=0,
  20. )
  21. tokens = np.concatenate((tokens, np.zeros(max_seq_length - len(tokens), dtype=np.int64)))
  22. position_ids = np.concatenate((position_ids, np.zeros(max_seq_length - len(position_ids), dtype=np.int64)))
  23. return tokens, position_ids, attention_mask
  24. class EvaluationDataset(torch.utils.data.Dataset, ABC):
  25. """
  26. Jsonlines of {
  27. "text": context
  28. "choices": [choice_id1,...], if not None, len(target) == 1
  29. "label": If generation task -1, else [0, len(choices))
  30. }
  31. If [MASK] not in context, will append [MASK] after text
  32. """
  33. def __init__(self, path: Union[str, List[str]], config: BaseConfig):
  34. self.path = path if isinstance(path, list) else [path]
  35. self.config = config
  36. self.max_seq_length = self.config.max_seq_length
  37. self.dtype = np.int64
  38. self.tokenizer = get_tokenizer()
  39. self.mask_id = self.tokenizer.get_command("[MASK]")
  40. self.gmask_id = self.tokenizer.get_command("[gMASK]")
  41. self.data = []
  42. for p in self.path:
  43. self.process_single_file(p)
  44. @property
  45. def has_collate_fn(self) -> bool:
  46. return False
  47. def collate_fn(self, samples):
  48. return None
  49. def process_single_file(self, path):
  50. with open(os.path.join(path), "r", encoding="utf-8") as file:
  51. for line in file:
  52. item = json.loads(line)
  53. self.data.append(self.process_single_item(item))
  54. @abstractmethod
  55. def process_single_item(self, item) -> 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):
  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}
  67. @property
  68. def has_collate_fn(self) -> bool:
  69. return True
  70. def collate_fn(self, samples):
  71. TILE = 32
  72. length_to_pad = (max(map(lambda spl: len(spl["token"]), samples)) + TILE - 1) // TILE * TILE
  73. token_batch, position_id_batch, attention_mask_batch = [], [], []
  74. context_length_batch, target_position_id_batch = [], []
  75. for sample in samples:
  76. token, position_id, attention_mask = pad_batch(
  77. sample["token"], sample["position_id"], sample["attention_mask"], length_to_pad
  78. )
  79. token_batch.append(token)
  80. position_id_batch.append(position_id)
  81. attention_mask_batch.append(attention_mask)
  82. context_length_batch.append(sample['context_length'])
  83. target_position_id_batch.append(sample['target_position_id'])
  84. return {
  85. "tokens": torch.tensor(np.array(token_batch), dtype=torch.int64),
  86. "position_ids": torch.tensor(np.array(position_id_batch), dtype=torch.int64),
  87. "attention_mask": torch.tensor(np.array(attention_mask_batch), dtype=torch.int64) < 0.5,
  88. "context_length": torch.tensor(context_length_batch, dtype=torch.int64),
  89. "target_position_ids": torch.tensor(np.array(target_position_id_batch), dtype=torch.int64),
  90. }
  91. @staticmethod
  92. def build_generation_sample(text, max_gen_length, use_task_mask, unidirectional=True):
  93. tokenizer = get_tokenizer()
  94. sop_id = tokenizer.get_command("sop")
  95. mask_id = tokenizer.get_command("[gMASK]") if use_task_mask else tokenizer.get_command("[MASK]")
  96. token = np.array(text, dtype=np.int64)
  97. blank_filling = mask_id in text
  98. if blank_filling:
  99. assert not unidirectional, "Unidirectional attention doesn't support blank filling"
  100. assert not use_task_mask, "Unidirectional attention doesn't support task mask"
  101. mask_position = text.index(mask_id)
  102. token = np.concatenate((token, [sop_id]))
  103. else:
  104. mask_position = len(token)
  105. if unidirectional:
  106. token = np.concatenate(([mask_id, sop_id], token))
  107. else:
  108. token = np.concatenate((token, [mask_id, sop_id]))
  109. context_length = len(token)
  110. position_id = np.arange(0, context_length, dtype=np.int64)
  111. target_position_id = np.arange(context_length, context_length + max_gen_length, dtype=np.int64)
  112. if not use_task_mask:
  113. position_id[context_length - 1:] = mask_position
  114. target_position_id[:] = mask_position
  115. attention_mask = np.tril(np.ones((context_length, context_length), dtype=np.int64))
  116. if not unidirectional:
  117. attention_mask[: context_length - 1, : context_length - 1] = 1
  118. item = {
  119. "token": token,
  120. "position_id": position_id,
  121. "target_position_id": target_position_id,
  122. "attention_mask": attention_mask,
  123. "context_length": context_length,
  124. }
  125. return item
  126. def __getitem__(self, idx):
  127. item = self.data[idx]
  128. sample = self.build_generation_sample(
  129. item["text"],
  130. max_gen_length=self.config.max_gen_length,
  131. use_task_mask=self.config.use_task_mask,
  132. unidirectional=self.config.unidirectional,
  133. )
  134. sample["targets"] = [np.array(target, dtype=self.dtype) for target in item["targets"]]
  135. return sample
  136. class MultiChoiceTaskDataset(EvaluationDataset):
  137. config: MultiChoiceTaskConfig
  138. def __init__(self, path, config: MultiChoiceTaskConfig):
  139. self.is_single_token = True # set to False later in process_single_item func
  140. super().__init__(path, config)
  141. @property
  142. def has_collate_fn(self) -> bool:
  143. return True
  144. def collate_fn(self, samples):
  145. TILE = 32
  146. length_to_pad = (max(map(lambda spl: len(spl["token"]), samples)) + TILE - 1) // TILE * TILE
  147. token_batch, position_id_batch, attention_mask_batch = [], [], []
  148. choices_batch, choice_target_ids_batch = [], []
  149. for sample in samples:
  150. token, position_id, attention_mask = pad_batch(
  151. sample["token"], sample["position_id"], sample["attention_mask"], length_to_pad
  152. )
  153. token_batch.append(token)
  154. position_id_batch.append(position_id)
  155. attention_mask_batch.append(attention_mask)
  156. choices_batch.append(sample["choices"])
  157. choice_target_ids_batch.append(sample["choice_target_ids"])
  158. return {
  159. "tokens": torch.tensor(np.array(token_batch), dtype=torch.int64),
  160. "position_ids": torch.tensor(np.array(position_id_batch), dtype=torch.int64),
  161. "attention_mask": torch.tensor(np.array(attention_mask_batch), dtype=torch.int64) < 0.5,
  162. "choices": choices_batch,
  163. "choice_target_ids": choice_target_ids_batch,
  164. "is_single_token": self.is_single_token,
  165. }
  166. def process_single_item(self, item):
  167. text, choices, label = get_tokenized_input(item, "inputs"), get_tokenized_input(item, "choices"), item["label"]
  168. tgt_seq_length = sum([len(choice) for choice in choices])
  169. if tgt_seq_length == len(choices):
  170. # For single token, we only insert one [sop]
  171. tgt_seq_length = 1
  172. assert tgt_seq_length < self.config.max_seq_length
  173. if len(text) + tgt_seq_length + 2 > self.config.max_seq_length:
  174. text_length = self.config.max_seq_length - tgt_seq_length - 2
  175. text = text[len(text) - text_length : len(text)]
  176. assert not (
  177. self.mask_id in text and self.config.use_multitask_encoding
  178. ), "Unified multitask encoding don't support blank filling"
  179. if tgt_seq_length != 1:
  180. self.is_single_token = False
  181. return {
  182. "text": text,
  183. "choices": choices,
  184. "label": label,
  185. }
  186. @staticmethod
  187. def build_multiple_choice_sample(text, choices, is_single_token, unified_multitask_encoding=False):
  188. tokenizer = get_tokenizer()
  189. sop_id = tokenizer.get_command("sop")
  190. mask_id = tokenizer.get_command("[MASK]")
  191. token = np.array(text, dtype=np.int64)
  192. target = np.array(text, dtype=np.int64)
  193. position_id = np.arange(len(text), dtype=np.int64)
  194. choice_target_id = []
  195. blank_filling = mask_id in text
  196. if not blank_filling:
  197. mask_position = len(token)
  198. token = np.concatenate((token, [mask_id]))
  199. target = np.concatenate((target, [mask_id]))
  200. position_id = np.concatenate((position_id, [mask_position]))
  201. else:
  202. mask_position = text.index(mask_id)
  203. division = len(token)
  204. attention_mask = [np.ones((len(token), len(token)), dtype=np.int64)]
  205. for choice in choices:
  206. position_id = np.concatenate(
  207. (
  208. position_id,
  209. [mask_position] * len(choice)
  210. if blank_filling or not unified_multitask_encoding
  211. else np.arange(mask_position, mask_position + len(choice), dtype=np.int64),
  212. )
  213. )
  214. choice_target_id.append(np.arange(len(token), len(token) + len(choice), dtype=np.int64))
  215. attention_mask.append(np.tril(np.ones((len(choice), len(choice)), dtype=np.int64)))
  216. token = np.concatenate((token, [sop_id], choice[:-1]))
  217. target = np.concatenate((target, choice))
  218. if is_single_token:
  219. break
  220. attention_mask = block_diag(*attention_mask)
  221. attention_mask[: len(token), :division] = 1
  222. if is_single_token:
  223. choices = np.array(choices, dtype=np.int64).squeeze().tolist()
  224. item = {
  225. "token": token,
  226. "position_id": position_id,
  227. "attention_mask": attention_mask,
  228. "choices": choices,
  229. "choice_target_ids": choice_target_id[0] if is_single_token else choice_target_id,
  230. }
  231. return item
  232. def __getitem__(self, idx):
  233. item = self.data[idx]
  234. sample = self.build_multiple_choice_sample(
  235. item["text"],
  236. item["choices"],
  237. is_single_token=self.is_single_token,
  238. unified_multitask_encoding=self.config.use_multitask_encoding,
  239. )
  240. sample["label"] = item["label"]
  241. return sample
  242. class LanguageModelTaskDataset(EvaluationDataset):
  243. config: LanguageModelTaskConfig
  244. def process_single_file(self, path):
  245. with open(os.path.join(path), "r", encoding="utf-8") as file:
  246. raw_text = file.read()
  247. tokens = self.tokenizer.tokenize(raw_text)
  248. self.data.append(
  249. {
  250. "raw_text": tokens,
  251. "num_original_tokens": len(raw_text.strip().split(" ")),
  252. "num_sequences": max(
  253. math.ceil(
  254. max(len(tokens) - (self.config.max_seq_length - 1), 0) / self.config.generation_length
  255. )
  256. + 1,
  257. 1,
  258. ),
  259. }
  260. )
  261. def process_single_item(self, item):
  262. pass
  263. def __len__(self):
  264. return self.data[0]["num_sequences"]
  265. def __getitem__(self, idx):
  266. start_idx = idx * self.config.generation_length
  267. end_idx = start_idx + self.config.max_seq_length - 1 # for additional [gMASK]
  268. tokens = self.data[0]["raw_text"][start_idx:end_idx]
  269. mask_id = self.gmask_id if self.config.use_task_mask else self.mask_id
  270. sop_id = self.tokenizer.get_command("sop")
  271. if idx == 0 or self.config.unidirectional:
  272. prompt, text = tokens[:1], tokens[1:]
  273. else:
  274. prompt_length = self.config.max_seq_length - 1 - self.config.generation_length
  275. prompt, text = tokens[:prompt_length], tokens[prompt_length:]
  276. seq_length = len(prompt) + len(text) + 1
  277. attention_mask = np.tril(np.ones((seq_length, seq_length), dtype=np.int64))
  278. attention_mask[: len(prompt) + 1, : len(prompt) + 1] = 1
  279. return {
  280. "tokens": np.array(prompt + [mask_id, sop_id] + text[:-1], dtype=np.int64),
  281. "targets": np.array(prompt + [mask_id] + text, dtype=np.int64),
  282. "position_ids": np.arange(0, seq_length, dtype=np.int64),
  283. "attention_mask": attention_mask < 0.5,
  284. "loss_masks": np.array([0] * (len(prompt) + 1) + [1] * len(text), dtype=np.int64),
  285. }