datasets.py 39.8 KB
Newer Older
Raul Puri's avatar
Raul Puri committed
1
# coding=utf-8
Mohammad's avatar
Mohammad committed
2
# Copyright (c) 2020, NVIDIA CORPORATION.  All rights reserved.
Raul Puri's avatar
Raul Puri committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""dataset objects for jsons, csvs, and BERT datasets"""

import os
import time
from operator import itemgetter
from bisect import bisect_right
21
import itertools
Raul Puri's avatar
Raul Puri committed
22
23
24
25
import json
import csv
import math
import random
26
from itertools import accumulate
Raul Puri's avatar
Raul Puri committed
27
28
29
30
31
32
33
34
35
36
37

from torch.utils import data
import pandas as pd
import numpy as np

import nltk
from nltk import tokenize

from .lazy_loader import lazy_array_loader, exists_lazy, make_lazy
from .tokenization import Tokenization

Neel Kant's avatar
Neel Kant committed
38

Raul Puri's avatar
Raul Puri committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class ConcatDataset(data.Dataset):
    """
    Dataset to concatenate multiple datasets.
    Purpose: useful to assemble different existing datasets, possibly
    large-scale datasets as the concatenation operation is done in an
    on-the-fly manner.
    Arguments:
        datasets (sequence): List of datasets to be concatenated.
    """

    @staticmethod
    def cumsum(sequence):
        r, s = [], 0
        for e in sequence:
            l = len(e)
            r.append(l + s)
            s += l
        return r

    def __init__(self, datasets, **kwargs):
        super(ConcatDataset, self).__init__()
        assert len(datasets) > 0, 'datasets should not be an empty iterable'
        self.datasets = list(datasets)
Neel Kant's avatar
Neel Kant committed
62
63
        self.is_lazy = sum([isinstance(ds, lazy_array_loader)
                            for ds in self.datasets]) == len(self.datasets)
Raul Puri's avatar
Raul Puri committed
64
65
66
        self.cumulative_sizes = self.cumsum(self.datasets)
        self._X = None
        self._Y = None
67
        self._lens = None
Raul Puri's avatar
Raul Puri committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

    def SetTokenizer(self, tokenizer):
        for ds in self.datasets:
            ds.SetTokenizer(tokenizer)

    def GetTokenizer(self):
        return self.datasets[0].GetTokenizer()

    def __len__(self):
        return self.cumulative_sizes[-1]

    def __getitem__(self, idx):
        dataset_idx = bisect_right(self.cumulative_sizes, idx)
        if dataset_idx == 0:
            sample_idx = idx
        else:
            sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]
        return self.datasets[dataset_idx][sample_idx]

87
88
89
90
91
92
93
94
95
    @property
    def lens(self):
        if self._lens is None:
            self._lens = []
            if self.is_lazy:
                for data in self.datasets:
                    self._lens.extend(data.lens)
            else:
                for data in self.datasets:
Neel Kant's avatar
Neel Kant committed
96
97
                    self._lens.extend([len(d['text']) if isinstance(
                        d, dict) else len(d) for d in data])
98
99
        return self._lens

Raul Puri's avatar
Raul Puri committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    @property
    def X(self):
        if self._X is None:
            self._X = []
            for data in self.datasets:
                self._X.extend(data.X)
        return self._X

    @property
    def Y(self):
        if self._Y is None:
            self._Y = []
            for data in self.datasets:
                self._Y.extend(list(data.Y))
            self._Y = np.array(self._Y)
        return self._Y

    @property
    def cummulative_sizes(self):
        warnings.warn("cummulative_sizes attribute is renamed to "
                      "cumulative_sizes", DeprecationWarning, stacklevel=2)
        return self.cumulative_sizes

Neel Kant's avatar
Neel Kant committed
123

Raul Puri's avatar
Raul Puri committed
124
125
126
127
128
129
130
131
132
133
class SplitDataset(data.Dataset):
    """
    Dataset wrapper to access a subset of another dataset.
    Purpose: useful to index into existing datasets, possibly
    large-scale datasets as the subindexing operation is done in an
    on-the-fly manner.
    Arguments:
        ds (Dataset or array-like): List of datasets to be subindexed
        split_inds (1D array-like): List of indices part of subset
    """
Neel Kant's avatar
Neel Kant committed
134

Raul Puri's avatar
Raul Puri committed
135
136
137
    def __init__(self, ds, split_inds, **kwargs):
        self.split_inds = list(split_inds)
        self.wrapped_data = ds
138
        self.is_lazy = isinstance(ds, lazy_array_loader) or (hasattr(ds, 'is_lazy') and ds.is_lazy)
Raul Puri's avatar
Raul Puri committed
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
        if self.is_lazy:
            self.lens = itemgetter(*self.split_inds)(list(self.wrapped_data.lens))
        self._X = None
        self._Y = None

    def __len__(self):
        return len(self.split_inds)

    def __getitem__(self, index):
        return self.wrapped_data[self.split_inds[index]]

    def SetTokenizer(self, tokenizer):
        self.wrapped_data.SetTokenizer(tokenizer)

    def GetTokenizer(self):
        return self.wrapped_data.GetTokenizer()

    @property
    def X(self):
        if self._X is None:
            self._X = itemgetter(*self.split_inds)(self.wrapped_data.X)
        return self._X

    @property
    def Y(self):
        if self._Y is None:
            self._Y = np.array(itemgetter(*self.split_inds)(self.wrapped_data.Y))
        return self._Y

    def __iter__(self):
        for idx in self.split_inds:
            yield self.wrapped_data[idx]

Neel Kant's avatar
Neel Kant committed
172
173

def split_ds(ds, split=[.8, .2, .0], shuffle=True):
Raul Puri's avatar
Raul Puri committed
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
    """
    Split a dataset into subsets given proportions of how
    much to allocate per split. If a split is 0% returns None for that split.
    Purpose: Useful for creating train/val/test splits
    Arguments:
        ds (Dataset or array-like): Data to be split.
        split (1D array-like): proportions to split `ds`. `sum(splits) != 0`
        shuffle (boolean): Randomly split dataset. Default: True
    """
    split_sum = sum(split)
    if split_sum == 0:
        raise Exception('Split cannot sum to 0.')
    split = np.array(split)
    split /= split_sum
    ds_len = len(ds)
    inds = np.arange(ds_len)
    if shuffle:
        np.random.shuffle(inds)
    start_idx = 0
    residual_idx = 0
Neel Kant's avatar
Neel Kant committed
194
    rtn_ds = [None] * len(split)
Raul Puri's avatar
Raul Puri committed
195
196
    for i, f in enumerate(split):
        if f != 0:
Neel Kant's avatar
Neel Kant committed
197
            proportion = ds_len * split[i]
Raul Puri's avatar
Raul Puri committed
198
199
            residual_idx += proportion % 1
            split_ = int(int(proportion) + residual_idx)
Neel Kant's avatar
Neel Kant committed
200
            split_inds = inds[start_idx:start_idx + max(split_, 1)]
Raul Puri's avatar
Raul Puri committed
201
202
203
204
205
            rtn_ds[i] = SplitDataset(ds, split_inds)
            start_idx += split_
            residual_idx %= 1
    return rtn_ds

Neel Kant's avatar
Neel Kant committed
206

Raul Puri's avatar
Raul Puri committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
class csv_dataset(data.Dataset):
    """
    Class for loading datasets from csv files.
    Purpose: Useful for loading data for unsupervised modeling or transfer tasks
    Arguments:
        path (str): Path to csv file with dataset.
        tokenizer (data_utils.Tokenizer): Tokenizer to use when processing text. Default: None
        preprocess_fn (callable): Callable that process a string into desired format.
        delim (str): delimiter for csv. Default: ','
        binarize_sent (bool): binarize label values to 0 or 1 if they\'re on a different scale. Default: False
        drop_unlabeled (bool): drop rows with unlabelled values. Always fills remaining empty
            columns with -1 (regardless if rows are dropped based on value) Default: False
        text_key (str): key to get text from csv. Default: 'sentence'
        label_key (str): key to get label from json dictionary. Default: 'label'
    Attributes:
        X (list): all strings from the csv file
        Y (np.ndarray): labels to train with
    """
Neel Kant's avatar
Neel Kant committed
225

Raul Puri's avatar
Raul Puri committed
226
    def __init__(self, path, tokenizer=None, preprocess_fn=None, delim=',',
Neel Kant's avatar
Neel Kant committed
227
228
                 binarize_sent=False, drop_unlabeled=False, text_key='sentence', label_key='label',
                 **kwargs):
229
        self.is_lazy = False
Raul Puri's avatar
Raul Puri committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        self.preprocess_fn = preprocess_fn
        self.SetTokenizer(tokenizer)
        self.path = path
        self.delim = delim
        self.text_key = text_key
        self.label_key = label_key
        self.drop_unlabeled = drop_unlabeled

        if '.tsv' in self.path:
            self.delim = '\t'

        self.X = []
        self.Y = []
        try:
            cols = [text_key]
            if isinstance(label_key, list):
                cols += label_key
            else:
                cols += [label_key]
            data = pd.read_csv(self.path, sep=self.delim, usecols=cols, encoding='latin-1')
Neel Kant's avatar
Neel Kant committed
250
        except BaseException:
Raul Puri's avatar
Raul Puri committed
251
252
253
254
255
256
257
258
            data = pd.read_csv(self.path, sep=self.delim, usecols=[text_key], encoding='latin-1')

        data = data.dropna(axis=0)

        self.X = data[text_key].values.tolist()
        try:
            self.Y = data[label_key].values
        except Exception as e:
Neel Kant's avatar
Neel Kant committed
259
            self.Y = np.ones(len(self.X)) * -1
Raul Puri's avatar
Raul Puri committed
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

        if binarize_sent:
            self.Y = binarize_labels(self.Y, hard=binarize_sent)

    def SetTokenizer(self, tokenizer):
        if tokenizer is None:
            self.using_tokenizer = False
            if not hasattr(self, '_tokenizer'):
                self._tokenizer = tokenizer
        else:
            self.using_tokenizer = True
            self._tokenizer = tokenizer

    def GetTokenizer(self):
        return self._tokenizer

    @property
    def tokenizer(self):
        if self.using_tokenizer:
            return self._tokenizer
        return None

    def __len__(self):
        return len(self.X)

    def __getitem__(self, index):
        """process+tokenize string and return string,label,and stringlen"""
        x = self.X[index]
        if self.tokenizer is not None:
            x = self.tokenizer.EncodeAsIds(x, self.preprocess_fn)
        elif self.preprocess_fn is not None:
            x = self.preprocess_fn(x)
        y = self.Y[index]
        if isinstance(y, str):
            if self.tokenizer is not None:
                y = self.tokenizer.EncodeAsIds(y, self.preprocess_fn)
            elif self.preprocess_fn is not None:
                y = self.preprocess_fn(y)
        return {'text': x, 'length': len(x), 'label': y}

    def write(self, writer_gen=None, path=None, skip_header=False):
        """
        given a generator of metrics for each of the data points X_i,
            write the metrics, text, and labels to a csv file
        """
        if path is None:
Neel Kant's avatar
Neel Kant committed
306
            path = self.path + '.results'
Raul Puri's avatar
Raul Puri committed
307
308
309
310
        print('generating csv at ' + path)
        with open(path, 'w') as csvfile:
            c = csv.writer(csvfile, delimiter=self.delim)
            if writer_gen is not None:
Neel Kant's avatar
Neel Kant committed
311
312
                # if first item of generator is a header of what the metrics mean then
                # write header to csv file
Raul Puri's avatar
Raul Puri committed
313
                if not skip_header:
Neel Kant's avatar
Neel Kant committed
314
                    header = (self.label_key,) + tuple(next(writer_gen)) + (self.text_key,)
Raul Puri's avatar
Raul Puri committed
315
316
                    c.writerow(header)
                for i, row in enumerate(writer_gen):
Neel Kant's avatar
Neel Kant committed
317
                    row = (self.Y[i],) + tuple(row) + (self.X[i],)
Raul Puri's avatar
Raul Puri committed
318
319
320
321
322
323
                    c.writerow(row)
            else:
                c.writerow([self.label_key, self.text_key])
                for row in zip(self.Y, self.X):
                    c.writerow(row)

Neel Kant's avatar
Neel Kant committed
324

Raul Puri's avatar
Raul Puri committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
class json_dataset(data.Dataset):
    """
    Class for loading datasets from a json dump.
    Purpose: Useful for loading data for unsupervised modeling or transfer tasks
    Arguments:
        path (str): path to json file with dataset.
        tokenizer (data_utils.Tokenizer): Tokenizer to use when processing text. Default: None
        preprocess_fn (callable): callable function that process a string into desired format.
            Takes string, maxlen=None, encode=None as arguments. Default: process_str
        text_key (str): key to get text from json dictionary. Default: 'sentence'
        label_key (str): key to get label from json dictionary. Default: 'label'
    Attributes:
        all_strs (list): list of all strings from the dataset
        all_labels (list): list of all labels from the dataset (if they have it)
    """
    def __init__(self, path, tokenizer=None, preprocess_fn=None, binarize_sent=False,
Neel Kant's avatar
Neel Kant committed
341
                 text_key='sentence', label_key='label', loose_json=False, **kwargs):
342
        self.is_lazy = False
Raul Puri's avatar
Raul Puri committed
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
        self.preprocess_fn = preprocess_fn
        self.path = path
        self.SetTokenizer(tokenizer)
        self.X = []
        self.Y = []
        self.text_key = text_key
        self.label_key = label_key
        self.loose_json = loose_json

        for j in self.load_json_stream(self.path):
            s = j[text_key]
            self.X.append(s)
            self.Y.append(j[label_key])

    def SetTokenizer(self, tokenizer):
        if tokenizer is None:
            self.using_tokenizer = False
            if not hasattr(self, '_tokenizer'):
                self._tokenizer = tokenizer
        else:
            self.using_tokenizer = True
            self._tokenizer = tokenizer

    def GetTokenizer(self):
        return self._tokenizer

    @property
    def tokenizer(self):
        if self.using_tokenizer:
            return self._tokenizer
        return None

    def __getitem__(self, index):
        """gets the index'th string from the dataset"""
        x = self.X[index]
        if self.tokenizer is not None:
            x = self.tokenizer.EncodeAsIds(x, self.preprocess_fn)
        elif self.preprocess_fn is not None:
            x = self.preprocess_fn(x)
        y = self.Y[index]
        if isinstance(y, str):
            if self.tokenizer is not None:
                y = self.tokenizer.EncodeAsIds(y, self.preprocess_fn)
            elif self.preprocess_fn is not None:
                y = self.preprocess_fn(y)
        return {'text': x, 'length': len(x), 'label': y}

    def __len__(self):
        return len(self.X)

    def write(self, writer_gen=None, path=None, skip_header=False):
        """
        given a generator of metrics for each of the data points X_i,
            write the metrics, text, and labels to a json file
        """
        if path is None:
Neel Kant's avatar
Neel Kant committed
399
            path = self.path + '.results'
Raul Puri's avatar
Raul Puri committed
400
401
402
403

        jsons = []

        if writer_gen is not None:
Neel Kant's avatar
Neel Kant committed
404
405
            # if first item of generator is a header of what the metrics mean then
            # write header to csv file
Raul Puri's avatar
Raul Puri committed
406
407
408
409
410
            def gen_helper():
                keys = {}
                keys[0] = self.label_key
                if not skip_header:
                    for idx, k in enumerate(tuple(next(writer_gen))):
Neel Kant's avatar
Neel Kant committed
411
                        keys[idx + 1] = k
Raul Puri's avatar
Raul Puri committed
412
413
414
                for i, row in enumerate(writer_gen):
                    if i == 0 and skip_header:
                        for idx, _ in enumerate(row):
Neel Kant's avatar
Neel Kant committed
415
                            keys[idx + 1] = 'metric_%d' % (idx,)
Raul Puri's avatar
Raul Puri committed
416
                    j = {}
Neel Kant's avatar
Neel Kant committed
417
                    for idx, v in enumerate((self.Y[i],) + tuple(row)):
Raul Puri's avatar
Raul Puri committed
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
                        k = keys[idx]
                        j[k] = v
                    yield j
        else:
            def gen_helper():
                for y in self.Y:
                    j = {}
                    j[self.label_key] = y
                    yield j

        def out_stream():
            for i, j in enumerate(gen_helper()):
                j[self.text_key] = self.X[i]
                yield j

        self.save_json_stream(path, out_stream())

    def save_json_stream(self, save_path, json_stream):
        if self.loose_json:
            with open(save_path, 'w') as f:
                for i, j in enumerate(json_stream):
                    write_string = ''
                    if i != 0:
                        write_string = '\n'
                    write_string += json.dumps(j)
                    f.write(write_string)
        else:
            jsons = [j for j in json_stream]
            json.dump(jsons, open(save_path, 'w'), separators=(',', ':'))

    def load_json_stream(self, load_path):
        if not self.loose_json:
            jsons = json.load(open(load_path, 'r'))
            generator = iter(jsons)
        else:
            def gen_helper():
                with open(load_path, 'r') as f:
                    for row in f:
                        yield json.loads(row)
            generator = gen_helper()

        for j in generator:
            if self.label_key not in j:
                j[self.label_key] = -1
            yield j

Neel Kant's avatar
Neel Kant committed
464

465
466
467
468
469
470
471
472
class GPT2Dataset(data.Dataset):

    def __init__(self, ds,
                 max_seq_len=1024,
                 num_samples=None,
                 weighted=True,
                 sample_across_doc=True,
                 random_across_doc_sampling=True,
473
                 bias_for_single_doc=False,
474
475
476
477
478
479
480
481
482
483
484
485
                 sentence_start=False, **kwargs):
        self.ds = ds
        self.ds_len = len(self.ds)
        self.num_samples = num_samples
        if num_samples is None:
            self.num_samples = 1000 * self.ds_len
        self.max_seq_len = max_seq_len
        self.tokenizer = self.ds.GetTokenizer()
        self.ds.SetTokenizer(None)
        self.weighted = weighted
        self.sample_across_doc = sample_across_doc
        self.random_across_doc_sampling = random_across_doc_sampling
486
        self.bias_for_single_doc = bias_for_single_doc
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
        self.sentence_start = sentence_start
        self.init_weighting()

    def init_weighting(self):
        if self.weighted:
            if hasattr(self.ds, 'is_lazy') and self.ds.is_lazy:
                lens = np.array(self.ds.lens)
            else:
                lens = np.array([len(d['text']) if isinstance(d, dict)
                                 else len(d) for d in self.ds])
            self.total_len = np.sum(lens)
            self.weighting = list(accumulate(lens))
        else:
            self.weighting = None

    def get_weighted_samples(self, np_rng):
        if self.weighting is not None:
            idx = np_rng.randint(self.total_len)
            return bisect_right(self.weighting, idx)
        else:
            return np_rng.randint(self.ds_len)

    def __len__(self):
        return self.num_samples

    def __getitem__(self, idx):
        # init rng
        rng = random.Random(idx)
Neel Kant's avatar
Neel Kant committed
515
        rng = np.random.RandomState(seed=[rng.randint(0, 2**32 - 1) for _ in range(16)])
516
517
518
519
520
521
522
523

        # get possibly weighted random index from dataset
        data_idx = self.get_weighted_samples(rng)
#        data_idx = rng.choice(self.ds_len, p=self.weighting)
        tokens = self.getidx(data_idx)

        # truncate or pad tokens
        num_tokens = len(tokens)
524
525
526
527
        if self.bias_for_single_doc:
            tokens_to_strip = num_tokens - self.max_seq_len - 1
        else:
            tokens_to_strip = num_tokens - 1
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
        if tokens_to_strip > 0:
            strip_left_tokens = rng.randint(tokens_to_strip + 1)
            tokens = tokens[strip_left_tokens:]
            if self.sentence_start:
                token_copy = list(tokens)
                not_done = True
                while (len(token_copy) > 0) and not_done:
                    tok = token_copy.pop(0)
                    if self.contains_sentence_end(tok):
                        tokens = token_copy
                        not_done = False
            strip_right_rokens = len(tokens) - self.max_seq_len - 1
            if strip_right_rokens > 0:
                tokens = tokens[:-strip_right_rokens]

        if self.sample_across_doc:
            while (len(tokens) < (self.max_seq_len + 1)):
                if self.random_across_doc_sampling:
                    data_idx = self.get_weighted_samples(rng)
                else:
                    data_idx = (data_idx + 1) % self.ds_len
                tokens += self.getidx(data_idx)
Neel Kant's avatar
Neel Kant committed
550
            tokens = tokens[:(self.max_seq_len + 1)]
551
552

        tokens = self.pad_seq(tokens)
Neel Kant's avatar
Neel Kant committed
553
        return {'text': np.array(tokens), }
554
555
556
557
558
559
560
561
562
563
564
565
566
567

    def getidx(self, data_idx):
        data = self.ds[data_idx]
        if isinstance(data, dict):
            data = data['text']
        # tokenize
        tokenization = self.tokenizer.EncodeAsIds(data)
        tokenization.append(self.tokenizer.get_command('eos'))
        tokens = tokenization.tokenization
        return tokens

    def pad_seq(self, seq):
        total_tokens = self.max_seq_len + 1
        num_pad_tokens = max(0, total_tokens - len(seq))
Neel Kant's avatar
Neel Kant committed
568
        seq += [self.tokenizer.get_command('pad').Id] * (num_pad_tokens)
569
570
571
572
573
574
575
576
577
578
579
580
        return seq

    def contains_sentence_end(self, tok):
        tok = self.tokenizer.IdToToken(tok)
        if '.' in tok:
            return True
        if '?' in tok:
            return True
        if '!' in tok:
            return True
        return False

Neel Kant's avatar
Neel Kant committed
581

Raul Puri's avatar
Raul Puri committed
582
583
584
585
586
587
588
589
590
591
592
593
class bert_sentencepair_dataset(data.Dataset):
    """
    Dataset containing sentencepairs for BERT training. Each index corresponds to a randomly generated sentence pair.
    Arguments:
        ds (Dataset or array-like): data corpus to use for training
        max_seq_len (int): maximum sequence length to use for a sentence pair
        mask_lm_prob (float): proportion of tokens to mask for masked LM
        max_preds_per_seq (int): Maximum number of masked tokens per sentence pair. Default: math.ceil(max_seq_len*mask_lm_prob/10)*10
        short_seq_prob (float): Proportion of sentence pairs purposefully shorter than max_seq_len
        dataset_size (int): number of random sentencepairs in the dataset. Default: len(ds)*(len(ds)-1)

    """
Neel Kant's avatar
Neel Kant committed
594
595
596

    def __init__(self, ds, max_seq_len=512, mask_lm_prob=.15, max_preds_per_seq=None,
                 short_seq_prob=.01, dataset_size=None, presplit_sentences=False, weighted=True, **kwargs):
Raul Puri's avatar
Raul Puri committed
597
598
599
600
601
602
603
604
        self.ds = ds
        self.ds_len = len(self.ds)
        self.tokenizer = self.ds.GetTokenizer()
        self.vocab_words = list(self.tokenizer.text_token_vocab.values())
        self.ds.SetTokenizer(None)
        self.max_seq_len = max_seq_len
        self.mask_lm_prob = mask_lm_prob
        if max_preds_per_seq is None:
Neel Kant's avatar
Neel Kant committed
605
            max_preds_per_seq = math.ceil(max_seq_len * mask_lm_prob / 10) * 10
Raul Puri's avatar
Raul Puri committed
606
607
608
609
        self.max_preds_per_seq = max_preds_per_seq
        self.short_seq_prob = short_seq_prob
        self.dataset_size = dataset_size
        if self.dataset_size is None:
Neel Kant's avatar
Neel Kant committed
610
            self.dataset_size = self.ds_len * (self.ds_len - 1)
Raul Puri's avatar
Raul Puri committed
611
        self.presplit_sentences = presplit_sentences
612
613
614
615
616
617
618
619
620
621
        if not self.presplit_sentences:
            nltk.download('punkt', download_dir="./nltk")
        self.weighted = weighted
        self.get_weighting()

    def get_weighting(self):
        if self.weighted:
            if hasattr(self.ds, 'is_lazy') and self.ds.is_lazy:
                lens = np.array(self.ds.lens)
            else:
Neel Kant's avatar
Neel Kant committed
622
623
                lens = np.array([len(d['text']) if isinstance(d, dict) else len(d)
                                 for d in self.ds])
624
625
626
627
628
629
630
631
632
633
634
            self.total_len = np.sum(lens)
            self.weighting = list(accumulate(lens))
        else:
            self.weighting = None

    def get_weighted_samples(self, np_rng):
        if self.weighting is not None:
            idx = np_rng.randint(self.total_len)
            return bisect_right(self.weighting, idx)
        else:
            return np_rng.randint(self.ds_len)
Raul Puri's avatar
Raul Puri committed
635
636
637
638
639
640
641

    def __len__(self):
        return self.dataset_size

    def __getitem__(self, idx):
        # get rng state corresponding to index (allows deterministic random pair)
        rng = random.Random(idx)
Neel Kant's avatar
Neel Kant committed
642
        np_rng = np.random.RandomState(seed=[rng.randint(0, 2**32 - 1) for _ in range(16)])
Raul Puri's avatar
Raul Puri committed
643
644
645
646
        # get seq length
        target_seq_length = self.max_seq_len
        if rng.random() < self.short_seq_prob:
            target_seq_length = rng.randint(2, target_seq_length)
647

Raul Puri's avatar
Raul Puri committed
648
649
650
651
652
        # get sentence pair and label
        is_random_next = None
        lena = 0
        lenb = 0
        while (is_random_next is None) or (lena < 1) or (lenb < 1):
Neel Kant's avatar
Neel Kant committed
653
654
            tokensa, tokensb, is_random_next = self.create_random_sentencepair(
                target_seq_length, rng, np_rng)
Raul Puri's avatar
Raul Puri committed
655
656
            lena = len(tokensa[0])
            lenb = len(tokensb[0])
657

Raul Puri's avatar
Raul Puri committed
658
659
660
        # truncate sentence pair to max_seq_len
        tokensa, tokensb = self.truncate_seq_pair(tokensa, tokensb, self.max_seq_len, rng)
        # join sentence pair, mask, and pad
Neel Kant's avatar
Neel Kant committed
661
662
663
664
665
666
667
668
669
670
671
        tokens, mask, mask_labels, pad_mask = self.create_masked_lm_predictions(
            tokensa, tokensb, self.mask_lm_prob, self.max_preds_per_seq, self.vocab_words, rng)
        sample = {
            'text': np.array(
                tokens[0]),
            'types': np.array(
                tokens[1]),
            'is_random': int(is_random_next),
            'mask': np.array(mask),
            'mask_labels': np.array(mask_labels),
            'pad_mask': np.array(pad_mask)}
Raul Puri's avatar
Raul Puri committed
672
673
674
675
        return sample

    def sentence_split(self, document):
        """split document into sentences"""
Raul Puri's avatar
Raul Puri committed
676
677
678
679
680
681
682
683
        lines = document.split('\n')
        if self.presplit_sentences:
            return [line for line in lines if line]
        rtn = []
        for line in lines:
            if line != '':
                rtn.extend(tokenize.sent_tokenize(line))
        return rtn
Raul Puri's avatar
Raul Puri committed
684
685
686
687
688

    def sentence_tokenize(self, sent, sentence_num=0, beginning=False, ending=False):
        """tokenize sentence and get token types"""
        tokens = self.tokenizer.EncodeAsIds(sent).tokenization
        str_type = 'str' + str(sentence_num)
Neel Kant's avatar
Neel Kant committed
689
        token_types = [self.tokenizer.get_type(str_type).Id] * len(tokens)
Raul Puri's avatar
Raul Puri committed
690
691
692
693
694
695
696
697
698
        return tokens, token_types

    def get_doc(self, idx):
        """gets text of document corresponding to idx"""
        rtn = self.ds[idx]
        if isinstance(rtn, dict):
            rtn = rtn['text']
        return rtn

699
    def create_random_sentencepair(self, target_seq_length, rng, np_rng):
Raul Puri's avatar
Raul Puri committed
700
701
702
703
704
705
706
707
708
709
710
711
712
713
        """
        fetches a random sentencepair corresponding to rng state similar to
        https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L248-L294
        """
        is_random_next = None

        curr_strs = []
        curr_str_types = []
        curr_len = 0

        while curr_len < 1:
            curr_len = 0
            doc_a = None
            while doc_a is None:
714
715
716
717
                if self.weighted:
                    # doc_a_idx = np_rng.choice(self.ds_len, p=self.weighting)
                    doc_a_idx = self.get_weighted_samples(np_rng)
                else:
Neel Kant's avatar
Neel Kant committed
718
                    doc_a_idx = rng.randint(0, self.ds_len - 1)
Raul Puri's avatar
Raul Puri committed
719
720
721
722
                doc_a = self.sentence_split(self.get_doc(doc_a_idx))
                if not doc_a:
                    doc_a = None

Neel Kant's avatar
Neel Kant committed
723
            random_start_a = rng.randint(0, len(doc_a) - 1)
Raul Puri's avatar
Raul Puri committed
724
725
            while random_start_a < len(doc_a):
                sentence = doc_a[random_start_a]
Neel Kant's avatar
Neel Kant committed
726
727
                sentence, sentence_types = self.sentence_tokenize(
                    sentence, 0, random_start_a == 0, random_start_a == len(doc_a))
Raul Puri's avatar
Raul Puri committed
728
729
730
731
732
                curr_strs.append(sentence)
                curr_str_types.append(sentence_types)
                curr_len += len(sentence)
                if random_start_a == len(doc_a) - 1 or curr_len >= target_seq_length:
                    break
Neel Kant's avatar
Neel Kant committed
733
                random_start_a = (random_start_a + 1)
Raul Puri's avatar
Raul Puri committed
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762

        if curr_strs:
            num_a = 1
            if len(curr_strs) >= 2:
                num_a = rng.randint(0, len(curr_strs))

            tokens_a = []
            token_types_a = []
            for j in range(num_a):
                tokens_a.extend(curr_strs[j])
                token_types_a.extend(curr_str_types[j])

            tokens_b = []
            token_types_b = []
            is_random_next = False
            if len(curr_strs) == 1 or rng.random() < 0.5:
                is_random_next = True
                target_b_length = target_seq_length - len(tokens_a)
                b_len = 0
                while b_len < 1:
                    doc_b = None
                    while doc_b is None:
                        doc_b_idx = rng.randint(0, self.ds_len - 2)
                        doc_b_idx += int(doc_b_idx >= doc_a_idx)

                        doc_b = self.sentence_split(self.get_doc(doc_b_idx))
                        if not doc_b:
                            doc_b = None

Neel Kant's avatar
Neel Kant committed
763
                    random_start_b = rng.randint(0, len(doc_b) - 1)
Raul Puri's avatar
Raul Puri committed
764
765
                    while random_start_b < len(doc_b):
                        sentence_b = doc_b[random_start_b]
Neel Kant's avatar
Neel Kant committed
766
767
                        new_b_tokens, new_b_types = self.sentence_tokenize(
                            sentence_b, 1, random_start_b == 0, random_start_b == len(doc_b))
Raul Puri's avatar
Raul Puri committed
768
769
770
771
772
                        b_len += len(new_b_tokens)
                        tokens_b.extend(new_b_tokens)
                        token_types_b.extend(new_b_types)
                        if len(tokens_b) >= target_b_length:
                            break
Neel Kant's avatar
Neel Kant committed
773
                        random_start_b = (random_start_b + 1)
Raul Puri's avatar
Raul Puri committed
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
            else:
                is_random_next = False
                for j in range(num_a, len(curr_strs)):
                    tokens_b.extend(curr_strs[j])
                    token_types_b.extend(curr_str_types[j])

        return (tokens_a, token_types_a), (tokens_b, token_types_b), is_random_next

    def truncate_seq_pair(self, a, b, max_seq_len, rng):
        """
        Truncate sequence pair according to original BERT implementation:
        https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L391
        """
        tokens_a, token_types_a = a
        tokens_b, token_types_b = b
789
790
        max_num_tokens = self.calc_seq_len(max_seq_len)
        # max_num_tokens = max_seq_len - 3
Raul Puri's avatar
Raul Puri committed
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
        while True:
            len_a = len(tokens_a)
            len_b = len(tokens_b)
            total_length = len_a + len_b
            if total_length <= max_num_tokens:
                break
            if len(tokens_a) > len(tokens_b):
                trunc_tokens = tokens_a
                trunc_types = token_types_a
            else:
                trunc_tokens = tokens_b
                trunc_types = token_types_b

            assert len(trunc_tokens) >= 1

            if rng.random() < 0.5:
                trunc_tokens.pop(0)
                trunc_types.pop(0)
            else:
                trunc_tokens.pop()
                trunc_types.pop()
        return (tokens_a, token_types_a), (tokens_b, token_types_b)

814
815
816
    def calc_seq_len(self, max_seq_len):
        return max_seq_len - 3

Raul Puri's avatar
Raul Puri committed
817
818
819
    def mask_token(self, idx, tokens, types, vocab_words, rng):
        """
        helper function to mask `idx` token from `tokens` according to
820
        section 3.1.1 of https://arxiv.org/pdf/1810.04805.pdf
Raul Puri's avatar
Raul Puri committed
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
        """
        label = tokens[idx]
        if rng.random() < 0.8:
            new_label = self.tokenizer.get_command('MASK').Id
        else:
            if rng.random() < 0.5:
                new_label = label
            else:
                new_label = rng.choice(vocab_words)

        tokens[idx] = new_label

        return label

    def pad_seq(self, seq):
        """helper function to pad sequence pair"""
        num_pad = max(0, self.max_seq_len - len(seq))
838
        pad_mask = [0] * len(seq) + [1] * num_pad
Raul Puri's avatar
Raul Puri committed
839
840
841
        seq += [self.tokenizer.get_command('pad').Id] * num_pad
        return seq, pad_mask

842
    def concat_tokens(self, tokens_a, token_types_a, tokens_b, token_types_b):
Neel Kant's avatar
Neel Kant committed
843
844
845
846
        tokens = [self.tokenizer.get_command('ENC').Id] + tokens_a + [self.tokenizer.get_command(
            'sep').Id] + tokens_b + [self.tokenizer.get_command('sep').Id]
        token_types = [token_types_a[0]] + token_types_a + \
            [token_types_a[0]] + token_types_b + [token_types_b[0]]
847
848
        return tokens, token_types

Raul Puri's avatar
Raul Puri committed
849
850
851
852
853
854
855
    def create_masked_lm_predictions(self, a, b, mask_lm_prob, max_preds_per_seq, vocab_words, rng):
        """
        Mask sequence pair for BERT training according to:
        https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L338
        """
        tokens_a, token_types_a = a
        tokens_b, token_types_b = b
856
        tokens, token_types = self.concat_tokens(tokens_a, token_types_a, tokens_b, token_types_b)
Raul Puri's avatar
Raul Puri committed
857
858
859
860

        len_a = len(tokens_a)
        len_b = len(tokens_b)

Neel Kant's avatar
Neel Kant committed
861
        cand_indices = [idx + 1 for idx in range(len_a)] + [idx + 2 + len_a for idx in range(len_b)]
Raul Puri's avatar
Raul Puri committed
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878

        rng.shuffle(cand_indices)

        output_tokens, pad_mask = self.pad_seq(list(tokens))
        output_types, _ = self.pad_seq(list(token_types))

        num_to_predict = min(max_preds_per_seq, max(1, int(round(len(tokens) * mask_lm_prob))))

        mask = [0] * len(output_tokens)
        mask_labels = [-1] * len(output_tokens)

        for idx in sorted(cand_indices[:num_to_predict]):
            mask[idx] = 1
            label = self.mask_token(idx, output_tokens, output_types, vocab_words, rng)
            mask_labels[idx] = label

        return (output_tokens, output_types), mask, mask_labels, pad_mask
879
880
881
882
883
884
885


class InverseClozeDataset(data.Dataset):
    """
    Dataset containing sentences and various 'blocks' for an inverse cloze task.
    Arguments:
        ds (Dataset or array-like): data corpus to use for training
886
887
888
        max_seq_len (int): maximum sequence length to use for an input sentence
        short_seq_prob (float): Proportion of input sentences purposefully shorter than max_seq_len
        dataset_size (int): number of input sentences in the dataset.
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
    """
    def __init__(self,
                 ds,
                 max_seq_len=512,
                 short_seq_prob=.01,
                 dataset_size=None,
                 presplit_sentences=False,
                 weighted=True,
                 **kwargs):
        self.ds = ds
        self.ds_len = len(self.ds)
        self.tokenizer = self.ds.GetTokenizer()
        self.vocab_words = list(self.tokenizer.text_token_vocab.values())
        self.ds.SetTokenizer(None)
        self.max_seq_len = max_seq_len
        self.short_seq_prob = short_seq_prob
        self.dataset_size = dataset_size
        if self.dataset_size is None:
907
            # this is wrong
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
            self.dataset_size = self.ds_len * (self.ds_len-1)
        self.presplit_sentences = presplit_sentences
        if not self.presplit_sentences:
            nltk.download('punkt', download_dir="./nltk")
        self.weighted = weighted
        if self.weighted:
            if hasattr(self.ds, 'is_lazy') and self.ds.is_lazy:
                lens = np.array(self.ds.lens)
            else:
                lens = np.array([len(d['text']) if isinstance(d, dict) else len(d) for d in self.ds])
            self.total_len = np.sum(lens)
            self.weighting = list(accumulate(lens))
        else:
            self.weighting = None

    def get_weighted_samples(self, np_rng):
        if self.weighting is not None:
            idx = np_rng.randint(self.total_len)
            return bisect_right(self.weighting, idx)
        else:
928
            return np_rng.randint(self.ds_len - 1)
929
930
931
932
933
934

    def __len__(self):
        return self.dataset_size

    def __getitem__(self, idx):
        # get rng state corresponding to index (allows deterministic random pair)
Neel Kant's avatar
Neel Kant committed
935
        rng = random.Random(idx + 1000)
936
937
        np_rng = np.random.RandomState(seed=[rng.randint(0, 2**32-1) for _ in range(16)])

938
939
        # get seq length. Save 2 tokens for beginning and end
        target_seq_length = self.max_seq_len - 2
940
        if rng.random() < self.short_seq_prob:
941
            target_seq_length = rng.randint(5, target_seq_length)
942

943
944
945
946
947
948
        input_data, context_data = self.get_input_and_context(target_seq_length, rng, np_rng)
        input_tokens, input_token_types, input_pad_mask = input_data
        context_tokens, context_token_types, context_pad_mask = context_data

        sample = {
            'input_text': np.array(input_tokens),
Neel Kant's avatar
Neel Kant committed
949
            'query_types': np.array(input_token_types),
950
951
            'input_pad_mask': np.array(input_pad_mask),
            'context_text': np.array(context_tokens),
Neel Kant's avatar
Neel Kant committed
952
            'block_types': np.array(context_token_types),
953
954
            'context_pad_mask': np.array(context_pad_mask)
        }
955

956
        return sample
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980

    def get_sentence_split_doc(self, idx):
        """fetch document at index idx and split into sentences"""
        document = self.ds[idx]
        if isinstance(document, dict):
            document = document['text']
        lines = document.split('\n')
        if self.presplit_sentences:
            return [line for line in lines if line]
        rtn = []
        for line in lines:
            if line != '':
                rtn.extend(tokenize.sent_tokenize(line))
        return rtn

    def sentence_tokenize(self, sent, sentence_num=0, beginning=False, ending=False):
        """tokenize sentence and get token types"""
        tokens = self.tokenizer.EncodeAsIds(sent).tokenization
        str_type = 'str' + str(sentence_num)
        token_types = [self.tokenizer.get_type(str_type).Id]*len(tokens)
        return tokens, token_types

    def get_input_and_context(self, target_seq_length, rng, np_rng):
        """fetches a sentence and its surrounding context"""
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
        num_tries = 0
        while num_tries < 20:
            num_tries += 1
            doc = None
            while doc is None:
                doc_idx = self.get_weighted_samples(np_rng)
                # doc is a list of sentences
                doc = self.get_sentence_split_doc(doc_idx)
                if not doc:
                    doc = None

            # set up and tokenize the entire selected document
            num_sentences = len(doc)
            padless_max_len = self.max_seq_len - 2

            # select a random sentence from the document as input
997
            # TODO: consider adding multiple input sentences.
Neel Kant's avatar
Neel Kant committed
998
            input_sentence_idx = rng.randint(0, num_sentences - 1)
999
1000
            tokens, token_types = self.sentence_tokenize(doc[input_sentence_idx], 0)
            input_tokens, input_token_types = tokens[:target_seq_length], token_types[:target_seq_length]
1001
1002
1003
            if not len(input_tokens) > 0:
                continue

1004
            context_tokens, context_token_types = [], []
1005
1006
1007
            # 10% of the time, the input sentence is left in the context.
            # The other 90% of the time, remove it.
            if rng.random() < 0.1:
1008
1009
                context_tokens = input_tokens.copy()
                context_token_types = input_token_types.copy()
1010

Neel Kant's avatar
Neel Kant committed
1011
            # parameters for examining sentences to add to the context
1012
1013
            view_preceding = True
            view_radius = 1
1014
            while len(context_tokens) < padless_max_len:
1015
                # keep adding sentences while the context can accommodate more.
1016
1017
1018
                if view_preceding:
                    examine_idx = input_sentence_idx - view_radius
                    if examine_idx >= 0:
1019
1020
1021
                        new_tokens, new_token_types = self.sentence_tokenize(doc[examine_idx], 0)
                        context_tokens = new_tokens + context_tokens
                        context_token_types = new_token_types + context_token_types
1022
1023
1024
                else:
                    examine_idx = input_sentence_idx + view_radius
                    if examine_idx < num_sentences:
1025
1026
1027
                        new_tokens, new_token_types = self.sentence_tokenize(doc[examine_idx], 0)
                        context_tokens += new_tokens
                        context_token_types += new_token_types
1028
1029
1030
1031
                    view_radius += 1
                view_preceding = not view_preceding
                if view_radius > num_sentences:
                    break
Neel Kant's avatar
Neel Kant committed
1032

1033
            # assemble the tokens and token types of the context
1034
1035
            context_tokens = context_tokens[:padless_max_len]
            context_token_types = context_token_types[:padless_max_len]
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
            if not len(context_tokens) > 0:
                continue

            # concatenate 'CLS' and 'SEP' tokens and add extra token types
            input_tokens, input_token_types, input_pad_mask = self.concat_and_pad_tokens(
                input_tokens, input_token_types)
            context_tokens, context_token_types, context_pad_mask = self.concat_and_pad_tokens(
                context_tokens, context_token_types)

            return (input_tokens, input_token_types, input_pad_mask), \
                   (context_tokens, context_token_types, context_pad_mask)
        else:
            raise RuntimeError("Could not get a valid data point from InverseClozeDataset")
1049

1050
1051
1052
1053
    def concat_and_pad_tokens(self, tokens, token_types):
        """concat with special tokens and pad sequence to self.max_seq_len"""
        tokens = [self.tokenizer.get_command('ENC').Id] + tokens + [self.tokenizer.get_command('sep').Id]
        token_types = [token_types[0]] + token_types + [token_types[0]]
1054

1055
        assert len(tokens) <= self.max_seq_len
1056
1057
1058
        num_pad = max(0, self.max_seq_len - len(tokens))
        pad_mask = [0] * len(tokens) + [1] * num_pad
        tokens += [self.tokenizer.get_command('pad').Id] * num_pad
1059
        token_types += [token_types[0]] * num_pad
1060
        return tokens, token_types, pad_mask