bert_dataset.py 12.4 KB
Newer Older
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
1
# coding=utf-8
Mohammad's avatar
Mohammad committed
2
# Copyright (c) 2020, NVIDIA CORPORATION.  All rights reserved.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
3
4
5
6
7
8
9
10
11
12
13
14
15
#
# 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.

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
16
"""BERT Style dataset."""
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
17

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
18
import os
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
19
20
21
22
23
24
import time

import numpy as np
import torch
from torch.utils.data import Dataset

25
from megatron import get_tokenizer
26
from megatron import mpu
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
27
from megatron.data.dataset_utils import build_training_sample
28
from megatron.data.indexed_dataset import make_dataset as make_indexed_dataset
29
from megatron.data.realm_dataset import InverseClozeDataset
30
from megatron import print_rank_0
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
31

Neel Kant's avatar
Neel Kant committed
32
33
DATASET_TYPES = ['standard_bert', 'ict', 'realm']

34

35
36
def build_train_valid_test_datasets(data_prefix, data_impl, splits_string,
                                    train_valid_test_num_samples,
37
                                    max_seq_length, masked_lm_prob,
38
                                    short_seq_prob, seed, skip_warmup,
Neel Kant's avatar
Neel Kant committed
39
40
41
42
                                    dataset_type='standard_bert'):

    if dataset_type not in DATASET_TYPES:
        raise ValueError("Invalid dataset_type: ", dataset_type)
43
44
45
46
47
48

    # Indexed dataset.
    indexed_dataset = get_indexed_dataset_(data_prefix,
                                           data_impl,
                                           skip_warmup)

Neel Kant's avatar
Neel Kant committed
49
    if dataset_type == 'ict':
Neel Kant's avatar
Neel Kant committed
50
51
52
        title_dataset = get_indexed_dataset_(data_prefix + '-titles',
                                             data_impl,
                                             skip_warmup)
53

54
55
56
57
58
59
60
61
    # Get start and end indices of train/valid/train into doc-idx
    # Note that doc-idx is desinged to be num-docs + 1 so we can
    # easily iterate over it.
    total_num_of_documents = indexed_dataset.doc_idx.shape[0] - 1
    splits = get_train_valid_test_split_(splits_string, total_num_of_documents)

    # Print stats about the splits.
    print_rank_0(' > dataset split:')
Neel Kant's avatar
Neel Kant committed
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    def print_split_stats(name, index):
        print_rank_0('    {}:'.format(name))
        print_rank_0('     document indices in [{}, {}) total of {} '
                     'documents'.format(splits[index], splits[index + 1],
                                        splits[index + 1] - splits[index]))
        start_index = indexed_dataset.doc_idx[splits[index]]
        end_index = indexed_dataset.doc_idx[splits[index + 1]]
        print_rank_0('     sentence indices in [{}, {}) total of {} '
                     'sentences'.format(start_index, end_index,
                                        end_index - start_index))
    print_split_stats('train', 0)
    print_split_stats('validation', 1)
    print_split_stats('test', 2)

    def build_dataset(index, name):
Neel Kant's avatar
Neel Kant committed
78
        from megatron.data.realm_dataset import RealmDataset
79
80
81
82
83
84
85
86
87
88
89
        dataset = None
        if splits[index + 1] > splits[index]:
            # Get the pointer to the original doc-idx so we can set it later.
            doc_idx_ptr = indexed_dataset.get_doc_idx()
            # Slice the doc-idx
            start_index = splits[index]
            # Add +1 so we can index into the dataset to get the upper bound.
            end_index = splits[index + 1] + 1
            # New doc_idx view.
            indexed_dataset.set_doc_idx(doc_idx_ptr[start_index:end_index])
            # Build the dataset accordingly.
90
            kwargs = dict(
91
92
93
94
95
96
                name=name,
                data_prefix=data_prefix,
                num_epochs=None,
                max_num_samples=train_valid_test_num_samples[index],
                max_seq_length=max_seq_length,
                short_seq_prob=short_seq_prob,
97
98
99
                seed=seed
            )

Neel Kant's avatar
Neel Kant committed
100
            if dataset_type == 'ict':
Neel Kant's avatar
Neel Kant committed
101
102
103
104
105
                dataset = InverseClozeDataset(
                    block_dataset=indexed_dataset,
                    title_dataset=title_dataset,
                    **kwargs
                )
106
            else:
Neel Kant's avatar
Neel Kant committed
107
108
                dataset_cls = BertDataset if dataset_type == 'standard_bert' else RealmDataset
                dataset = dataset_cls(
Neel Kant's avatar
Neel Kant committed
109
110
111
112
                    indexed_dataset=indexed_dataset,
                    masked_lm_prob=masked_lm_prob,
                    **kwargs
                )
Neel Kant's avatar
Neel Kant committed
113

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
            # Set the original pointer so dataset remains the main dataset.
            indexed_dataset.set_doc_idx(doc_idx_ptr)
            # Checks.
            assert indexed_dataset.doc_idx[0] == 0
            assert indexed_dataset.doc_idx.shape[0] == \
                (total_num_of_documents + 1)
        return dataset

    train_dataset = build_dataset(0, 'train')
    valid_dataset = build_dataset(1, 'valid')
    test_dataset = build_dataset(2, 'test')

    return (train_dataset, valid_dataset, test_dataset)


Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
129
class BertDataset(Dataset):
130

131
    def __init__(self, name, indexed_dataset, data_prefix,
132
133
                 num_epochs, max_num_samples, masked_lm_prob,
                 max_seq_length, short_seq_prob, seed):
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
134
135

        # Params to store.
136
        self.name = name
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
137
138
139
140
        self.seed = seed
        self.masked_lm_prob = masked_lm_prob
        self.max_seq_length = max_seq_length

141
        # Dataset.
142
143
        self.indexed_dataset = indexed_dataset

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
144
        # Build the samples mapping.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
145
146
147
148
149
150
        self.samples_mapping = get_samples_mapping_(self.indexed_dataset,
                                                    data_prefix,
                                                    num_epochs,
                                                    max_num_samples,
                                                    self.max_seq_length,
                                                    short_seq_prob,
151
152
                                                    self.seed,
                                                    self.name)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
153
154

        # Vocab stuff.
155
156
157
158
159
160
161
        tokenizer = get_tokenizer()
        self.vocab_id_list = list(tokenizer.inv_vocab.keys())
        self.vocab_id_to_token_dict = tokenizer.inv_vocab
        self.cls_id = tokenizer.cls
        self.sep_id = tokenizer.sep
        self.mask_id = tokenizer.mask
        self.pad_id = tokenizer.pad
162
        self.build_sample_fn = build_training_sample
163

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
164
    def __len__(self):
165
        return self.samples_mapping.shape[0]
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
166
167

    def __getitem__(self, idx):
168
169
        start_idx, end_idx, seq_length = self.samples_mapping[idx]
        sample = [self.indexed_dataset[i] for i in range(start_idx, end_idx)]
170
171
172
        # Note that this rng state should be numpy and not python since
        # python randint is inclusive whereas the numpy one is exclusive.
        np_rng = np.random.RandomState(seed=(self.seed + idx))
173
174
175
176
177
178
179
        return self.build_sample_fn(sample, seq_length,
                                    self.max_seq_length,  # needed for padding
                                    self.vocab_id_list,
                                    self.vocab_id_to_token_dict,
                                    self.cls_id, self.sep_id,
                                    self.mask_id, self.pad_id,
                                    self.masked_lm_prob, np_rng)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
180

181

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
182
def get_indexed_dataset_(data_prefix, data_impl, skip_warmup):
183
184
185

    print_rank_0(' > building dataset index ...')

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
186
187
188
189
    start_time = time.time()
    indexed_dataset = make_indexed_dataset(data_prefix,
                                           data_impl,
                                           skip_warmup)
190
191
192
193
194
195
196
197
198
199
    assert indexed_dataset.sizes.shape[0] == indexed_dataset.doc_idx[-1]
    print_rank_0(' > finished creating indexed dataset in {:4f} '
                 'seconds'.format(time.time() - start_time))

    print_rank_0(' > indexed dataset stats:')
    print_rank_0('    number of documents: {}'.format(
        indexed_dataset.doc_idx.shape[0] - 1))
    print_rank_0('    number of sentences: {}'.format(
        indexed_dataset.sizes.shape[0]))

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
200
201
202
    return indexed_dataset


203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def get_train_valid_test_split_(splits_string, size):
    """ Get dataset splits from comma or '/' separated string list."""

    splits = []
    if splits_string.find(',') != -1:
        splits = [float(s) for s in splits_string.split(',')]
    elif splits_string.find('/') != -1:
        splits = [float(s) for s in splits_string.split('/')]
    else:
        splits = [float(splits_string)]
    while len(splits) < 3:
        splits.append(0.)
    splits = splits[:3]
    splits_sum = sum(splits)
    assert splits_sum > 0.0
Neel Kant's avatar
Neel Kant committed
218
    splits = [split / splits_sum for split in splits]
219
220
221
222
223
224
225
226
227
228
229
230
    splits_index = [0]
    for index, split in enumerate(splits):
        splits_index.append(splits_index[index] +
                            int(round(split * float(size))))
    diff = splits_index[-1] - size
    for index in range(1, len(splits_index)):
        splits_index[index] -= diff
    assert len(splits_index) == 4
    assert splits_index[-1] == size
    return splits_index


Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
231
232
233
234
235
236
def get_samples_mapping_(indexed_dataset,
                         data_prefix,
                         num_epochs,
                         max_num_samples,
                         max_seq_length,
                         short_seq_prob,
237
238
                         seed,
                         name):
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
239
    if not num_epochs:
240
        if not max_num_samples:
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
241
242
243
244
245
246
247
248
            raise ValueError("Need to specify either max_num_samples "
                             "or num_epochs")
        num_epochs = np.iinfo(np.int32).max - 1
    if not max_num_samples:
        max_num_samples = np.iinfo(np.int64).max - 1

    # Filename of the index mapping
    indexmap_filename = data_prefix
249
250
251
252
253
    indexmap_filename += '_{}_indexmap'.format(name)
    if num_epochs != (np.iinfo(np.int32).max - 1):
        indexmap_filename += '_{}ep'.format(num_epochs)
    if max_num_samples != (np.iinfo(np.int64).max - 1):
        indexmap_filename += '_{}mns'.format(max_num_samples)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
254
255
256
257
258
259
260
261
    indexmap_filename += '_{}msl'.format(max_seq_length)
    indexmap_filename += '_{:0.2f}ssp'.format(short_seq_prob)
    indexmap_filename += '_{}s'.format(seed)
    indexmap_filename += '.npy'

    # Build the indexed mapping if not exist.
    if torch.distributed.get_rank() == 0 and \
       not os.path.isfile(indexmap_filename):
262
        print(' > WARNING: could not find index map file {}, building '
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
263
              'the indices on rank 0 ...'.format(indexmap_filename))
264

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
265
266
267
268
269
270
        # Make sure the types match the helpers input types.
        assert indexed_dataset.doc_idx.dtype == np.int64
        assert indexed_dataset.sizes.dtype == np.int32

        # Build samples mapping
        verbose = torch.distributed.get_rank() == 0
271
        start_time = time.time()
272
273
        print_rank_0(' > building sapmles index mapping for {} ...'.format(
            name))
274
275
276
        # First compile and then import.
        from megatron.data.dataset_utils import compile_helper
        compile_helper()
Mohammad's avatar
Mohammad committed
277
        from megatron.data import helpers
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
278
279
280
281
282
        samples_mapping = helpers.build_mapping(
            indexed_dataset.doc_idx,
            indexed_dataset.sizes,
            num_epochs,
            max_num_samples,
Neel Kant's avatar
Neel Kant committed
283
            max_seq_length - 3,  # account for added tokens
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
284
285
286
            short_seq_prob,
            seed,
            verbose)
287
        print_rank_0(' > done building sapmles index maping')
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
288
        np.save(indexmap_filename, samples_mapping, allow_pickle=True)
289
290
        print_rank_0(' > saved the index mapping in {}'.format(
            indexmap_filename))
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
291
        # Make sure all the ranks have built the mapping
292
        print_rank_0(' > elasped time to build and save samples mapping '
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
293
294
                     '(seconds): {:4f}'.format(
                         time.time() - start_time))
295
296
297
298
299
300
301
    # This should be a barrier but nccl barrier assumes
    # device_index=rank which is not the case for model
    # parallel case
    counts = torch.cuda.LongTensor([1])
    torch.distributed.all_reduce(counts, group=mpu.get_data_parallel_group())
    assert counts[0].item() == torch.distributed.get_world_size(
        group=mpu.get_data_parallel_group())
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
302
303

    # Load indexed dataset.
304
    print_rank_0(' > loading indexed mapping from {}'.format(
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
305
306
307
        indexmap_filename))
    start_time = time.time()
    samples_mapping = np.load(indexmap_filename, allow_pickle=True)
308
    print_rank_0('    loaded indexed file in {:3.3f} seconds'.format(
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
309
        time.time() - start_time))
310
    print_rank_0('    total number of samples: {}'.format(
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
311
        samples_mapping.shape[0]))
312

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
313
    return samples_mapping