-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdatasets_loader.py
More file actions
441 lines (363 loc) · 16.3 KB
/
datasets_loader.py
File metadata and controls
441 lines (363 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
from typing import List, Dict, Union
import torch
from torch.utils.data import Dataset
import datasets
# Workaround toolkit misreporting available disk space.
datasets.builder.has_sufficient_disk_space = lambda needed_bytes, directory=".": True
from datasets import load_dataset, load_from_disk
from datasets.builder import DatasetBuildError
from transformers import AutoTokenizer
from src.preprocessing_utils import (
perturb_tokens,
get_special_tokens_mask,
get_pooling_mask,
pre_process_codesearchnet_train,
pre_process_codesearchnet_test,
pre_process_gfg,
pre_process_the_stack,
)
from src.constants import MASK_TOKEN, PAD_TOKEN, SEPARATOR_TOKEN, CLS_TOKEN
DATASET_NAME_TO_PREPROCESSING_FUNCTION = {
"the-stack": {
"train": pre_process_the_stack,
"test": pre_process_the_stack,
},
"code_search_net": {
"train": pre_process_codesearchnet_train,
"test": pre_process_codesearchnet_test,
},
"gfg": {
"train": pre_process_gfg,
"test": pre_process_gfg,
},
}
class RandomlyPairedDataset(Dataset):
"""Indexed dataset class with randomly picked negative pairs."""
def __init__(self, base_dataset: datasets.Dataset) -> None:
"""Intanstiates an indexed dataset wrapping a base data source.
We use this class to be able to get examples from the dataset including negative pairs.
Args:
base_dataset (datasets.Dataset): Base indexed data source.
"""
self.data_source = base_dataset
def __len__(self) -> int:
"""Returns the length of the dataset which matches that of the base data source.
Returns:
int: Dataset length.
"""
return len(self.data_source)
def __getitem__(self, i: int) -> List[Dict]:
"""Reads from the base dataset and returns an addition random entry that serves as negative example.
Args:
i (int): Index to be read.
Returns:
List[Dict]: Pair of examples. The example indexed by i is returned along with a different random point.
"""
rand_idx = torch.randint(0, len(self.data_source), (1,)).item()
while rand_idx == i:
rand_idx = torch.randint(0, len(self.data_source), (1,)).item()
example = self.data_source[i]
negative_example = self.data_source[rand_idx]
return example["source"], example["target"], negative_example["source"]
class PairedDataset(Dataset):
"""Indexed dataset class yielding source/target pairs."""
def __init__(self, base_dataset: datasets.Dataset) -> None:
"""Intanstiates an indexed dataset wrapping a base data source.
We use this class to be able to get paired examples from the base dataset.
The base dataset must be pre-processed to include the fields 'source' and 'target'.
Args:
base_dataset (datasets.Dataset): Base indexed pre-processed data source.
"""
self.data_source = base_dataset
def __len__(self) -> int:
"""Returns the length of the dataset which matches that of the base data source.
Returns:
int: Dataset length.
"""
return len(self.data_source)
def __getitem__(self, i: int) -> List[Dict]:
"""Reads from the base dataset and returns a paier of examples.
Args:
i (int): Index to be read.
Returns:
List[Dict]: Pair of examples. The 'source' and 'target' fields of the example indexed by i are returned.
"""
example = self.data_source[i]
return example["source"], example["target"]
def get_dataset(
dataset_name: str,
path_to_cache: str,
split: str,
maximum_raw_length: int,
force_preprocess: bool = False,
maximum_row_cout: int = None,
) -> Union[PairedDataset, RandomlyPairedDataset]:
"""Get dataset instance.
Args:
dataset_name (str): Name of the base dataset.
path_to_cache (str): Path to the base dataset.
split (str): data split in {'train', 'valid', 'test'}.
maximum_raw_length (int, optional): Maximum length of the raw entries from the source dataset.
force_preprocess (bool, optional): Whether to force pre-processing. Defaults to False.
maximum_row_cout (int, optional) = Maximum size of the dataset in term of row count. Defaults to None.
Returns:
dataset: An indexed dataset object.
"""
try:
base_dataset = load_dataset(
dataset_name,
use_auth_token=True,
cache_dir=path_to_cache,
split=split,
)
except DatasetBuildError:
# Try to specify data files. Specific for The Stack.
base_dataset = load_dataset(
dataset_name,
use_auth_token=True,
cache_dir=path_to_cache,
data_files="sample.parquet",
split=split,
)
except FileNotFoundError:
# Try to load from disk if above failed.
base_dataset = load_from_disk(path_to_cache)
if force_preprocess:
base_dataset.cleanup_cache_files()
base_dataset = base_dataset.shuffle(seed=42)
if maximum_row_cout is not None:
base_dataset = base_dataset.select(
range(min(len(base_dataset), maximum_row_cout))
)
if "train" in split.lower():
split_preproc_key = "train"
else:
split_preproc_key = "test"
try:
pre_proc_fn = DATASET_NAME_TO_PREPROCESSING_FUNCTION[dataset_name][
split_preproc_key
]
except KeyError:
for k in DATASET_NAME_TO_PREPROCESSING_FUNCTION.keys():
if "the-stack" in dataset_name.lower() and "the-stack" in k:
pre_proc_fn = DATASET_NAME_TO_PREPROCESSING_FUNCTION[k][
split_preproc_key
]
base_dataset = base_dataset.map(pre_proc_fn(maximum_raw_length), num_proc=96)
base_dataset = base_dataset.shuffle(seed=42)
if "train" in split_preproc_key:
return RandomlyPairedDataset(base_dataset)
else:
return PairedDataset(base_dataset)
def prepare_tokenizer(tokenizer_path):
try:
tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
except OSError:
tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, use_auth_token=True)
tokenizer.add_special_tokens({"pad_token": PAD_TOKEN})
tokenizer.add_special_tokens({"sep_token": SEPARATOR_TOKEN})
tokenizer.add_special_tokens({"cls_token": CLS_TOKEN})
tokenizer.add_special_tokens({"mask_token": MASK_TOKEN})
return tokenizer
class TrainCollator:
"""Train collator object mapping sequences of items from dataset instance
into batches of IDs and masks used for training models.
"""
def __init__(
self,
tokenizer_path: str,
maximum_length: int,
mlm_masking_probability: float,
contrastive_masking_probability: float,
ignore_contrastive_loss_data: bool = False,
**kwargs,
) -> None:
"""Creates instance of collator.
Args:
tokenizer_path (str): Path to tokenizer.
maximum_length (int): Truncating length of token sequences.
mlm_masking_probability (float): Masking probability for MLM objective.
contrastive_masking_probability (float): Masking probability for contrastive objective.
ignore_contrastive_loss_data (bool, optional): Do not add append positive pairs to batch. Defaults to False.
"""
self.mlm_masking_probability = mlm_masking_probability
self.contrastive_masking_probability = contrastive_masking_probability
self.maximum_length = maximum_length
self.ignore_contrastive_loss_data = ignore_contrastive_loss_data
self.tokenizer = prepare_tokenizer(tokenizer_path)
self.sep_token_id = self.tokenizer.get_vocab()[self.tokenizer.sep_token]
self.pad_token_id = self.tokenizer.get_vocab()[self.tokenizer.pad_token]
self.mask_token_id = self.tokenizer.get_vocab()[self.tokenizer.mask_token]
self.cls_token_id = self.tokenizer.get_vocab()[self.tokenizer.cls_token]
def __call__(self, batch: List[Dict]) -> Dict[str, torch.Tensor]:
"""Maps list of triplets of examples to batches of token ids, masks, and labels used for training.
The firt two elements in a triplet correspond to neighbor chunkes from the same file. The third
element corresponds to a chunk from a random file.
Args:
batch (List[Dict]): List of pairs of examples.
Returns:
Dict[str, torch.Tensor]: Batches of tokens, masks, and labels.
"""
source_list = [
el[0] for el in batch
] # el[0] is the first half of a code snippet.
# Following are the labels for the seq relationship loss: 0 -> negative pair, 1 -> positive pair.
seq_relationship_labels = torch.randint(0, 2, (len(batch),)).long()
target_list = [
# seq_relationship_label==1 -> positive pair -> we take the second half of the code snippet
# seq_relationship_label==0 -> negative pair -> we take a random code snippet given in el[1]
el[1] if seq_relationship_labels[i] == 1 else el[2]
for i, el in enumerate(batch)
]
input_examples_list = [ # Combine source and target w/ template: [CLS] SOURCE [SEP] [TARGET] [SEP]
f"{CLS_TOKEN}{source_list[i]}{SEPARATOR_TOKEN}{target_list[i]}{SEPARATOR_TOKEN}"
for i in range(len(batch))
]
input_examples_encoding = self.tokenizer(
input_examples_list,
padding="longest",
max_length=self.maximum_length,
truncation=True,
return_tensors="pt",
)
input_examples_ids = input_examples_encoding.input_ids
input_examples_att_mask = (
input_examples_encoding.attention_mask
) # Padding masks.
special_tokens_mask = get_special_tokens_mask(
self.tokenizer, input_examples_ids
)
input_examples_ids, mlm_labels = perturb_tokens(
input_examples_ids,
special_tokens_mask,
self.mlm_masking_probability,
self.mask_token_id,
len(self.tokenizer),
) # Dynamically perturbs input tokens and generates corresponding mlm labels.
if not self.ignore_contrastive_loss_data:
positive_examples_ids, positive_mlm_labels = perturb_tokens(
input_examples_ids,
special_tokens_mask,
self.contrastive_masking_probability,
self.mask_token_id,
len(self.tokenizer),
) # Positve examples are independently perturbed versions of the source, used for the contrastive loss.
input_ids = torch.cat([input_examples_ids, positive_examples_ids], 0)
attention_mask = torch.cat(
[input_examples_att_mask, input_examples_att_mask.clone()], 0
)
pooling_mask = get_pooling_mask(
input_ids, self.sep_token_id
) # Pooling masks indicate the first [SEP] occurrence, used for seq embedding.
labels = torch.cat([mlm_labels, positive_mlm_labels], 0)
next_sentence_label = torch.cat(
[seq_relationship_labels, seq_relationship_labels.clone()], 0
)
else:
input_ids = input_examples_ids
attention_mask = input_examples_att_mask
pooling_mask = get_pooling_mask(
input_ids, self.sep_token_id
) # Pooling masks indicate the first [SEP] occurrence, used for seq embedding.
labels = mlm_labels
next_sentence_label = seq_relationship_labels
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"pooling_mask": pooling_mask,
"labels": labels,
"next_sentence_label": next_sentence_label,
}
class TestCollator:
"""Test collator object mapping sequences of items from dataset instance
into batches of IDs and masks used for training models.
"""
def __init__(self, tokenizer_path: str, maximum_length: int, **kwargs) -> None:
"""Creates instance of collator.
Args:
tokenizer_path (str): Path to tokenizer.
maximum_length (int): Truncating length of token sequences.
"""
self.maximum_length = maximum_length
self.tokenizer = prepare_tokenizer(tokenizer_path)
self.sep_token_id = self.tokenizer.get_vocab()[self.tokenizer.sep_token]
self.pad_token_id = self.tokenizer.get_vocab()[self.tokenizer.pad_token]
self.mask_token_id = self.tokenizer.get_vocab()[self.tokenizer.mask_token]
self.cls_token_id = self.tokenizer.get_vocab()[self.tokenizer.cls_token]
def __call__(self, batch: List[Dict]) -> Dict[str, torch.Tensor]:
"""Maps list of pairs of examples to batches of token ids, masks, and labels used for training.
Args:
batch (List[Dict]): List of pairs of examples.
Returns:
Dict[str, torch.Tensor]: Batches of tokens and masks.
"""
source_list = [el[0] for el in batch]
target_list = [el[1] for el in batch]
source_examples_list = [
f"{CLS_TOKEN}{source_list[i]}{SEPARATOR_TOKEN}" for i in range(len(batch))
]
target_examples_list = [
f"{CLS_TOKEN}{target_list[i]}{SEPARATOR_TOKEN}" for i in range(len(batch))
]
source_target_examples_encoding = self.tokenizer(
source_examples_list + target_examples_list,
padding="longest",
max_length=self.maximum_length,
truncation=True,
return_tensors="pt",
)
source_target_examples_ids = source_target_examples_encoding.input_ids
source_target_examples_att_mask = source_target_examples_encoding.attention_mask
return {
"source_target_ids": source_target_examples_ids,
"source_target_att_mask": source_target_examples_att_mask,
"return_loss": True, # This is so Trainer.prediction_step() will call Trainer.compute_loss during eval()
}
class Collator:
"""Object wrapping both train and test collators.
Decides which collator to use depending on the configuration of the batch.
Pair of examples --> test instance
Triplet of examples --> train instances
"""
def __init__(
self,
tokenizer_path: str,
maximum_length: int,
mlm_masking_probability: float = 0.5,
contrastive_masking_probability: float = 0.5,
ignore_contrastive_loss_data: bool = False,
) -> None:
"""Creates instance of collator.
Args:
tokenizer_path (str): Path to tokenizer.
maximum_length (int): Truncating length of token sequences.
mlm_masking_probability (float, optional): Masking probability for MLM objective. Defaults to 0.5.
contrastive_masking_probability (float, optional): Masking probability for contrastive objective. Defaults to 0.5.
ignore_contrastive_loss_data (bool, optional): Do not add append positive pairs to batch. Defaults to False.
"""
self.train_collator = TrainCollator(
tokenizer_path=tokenizer_path,
maximum_length=maximum_length,
mlm_masking_probability=mlm_masking_probability,
contrastive_masking_probability=contrastive_masking_probability,
ignore_contrastive_loss_data=ignore_contrastive_loss_data,
)
self.test_collator = TestCollator(
tokenizer_path=tokenizer_path,
maximum_length=maximum_length,
)
self.vocabulary_size = len(self.train_collator.tokenizer.vocab)
self.pad_token_id = self.train_collator.pad_token_id
def __call__(self, batch: List[Dict]) -> Dict[str, torch.Tensor]:
"""Maps list of pairs of examples to batches of token ids, masks, and labels used for training.
Args:
batch (List[Dict]): List of pairs of examples.
Returns:
Dict[str, torch.Tensor]: Batches of tokens and masks.
"""
if len(batch[0]) == 3:
return self.train_collator(batch)
elif len(batch[0]) == 2:
return self.test_collator(batch)
else:
raise AttributeError("Unknown batch configuration.")