configure_data.py 9.01 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.

"""parses arguments and preps data loader"""

import copy
import torch

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
21
22
from megatron import data_utils
from megatron import mpu
Raul Puri's avatar
Raul Puri committed
23

Neel Kant's avatar
Neel Kant committed
24

Raul Puri's avatar
Raul Puri committed
25
26
27
28
29
30
31
class DataConfig:

    def __init__(self, defaults={}):
        super(DataConfig, self).__init__()
        self.defaults = defaults

    def apply(self, args):
32
33
        if torch.distributed.get_rank() == 0:
            print('configuring data')
Raul Puri's avatar
Raul Puri committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
        self.apply_defaults(args)
        return make_loaders(args)

    def set_defaults(self, **kwargs):
        for k, v in kwargs.items():
            self.defaults[k] = v

    def apply_defaults(self, args):
        for k, v in self.defaults.items():
            k = k.replace('-', '_')
            if not hasattr(args, k):
                setattr(args, k, v)


def make_data_loader(dataset, batch_size, args):
49
50
51

    shuffle = args.shuffle
    if shuffle:
Neel Kant's avatar
Neel Kant committed
52
        sampler = data_utils.samplers.RandomSampler(
53
            dataset, replacement=True, num_samples=batch_size * args.train_iters)
Raul Puri's avatar
Raul Puri committed
54
55
    else:
        sampler = torch.utils.data.SequentialSampler(dataset)
56
57
58
    world_size = torch.distributed.get_world_size(
        group=mpu.get_data_parallel_group())
    rank = torch.distributed.get_rank(group=mpu.get_data_parallel_group())
Raul Puri's avatar
Raul Puri committed
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
    distributed = world_size > 1
    drop_last = distributed

    if distributed:
        batch_sampler = data_utils.samplers.DistributedBatchSampler(sampler,
                                                                    batch_size,
                                                                    drop_last,
                                                                    rank,
                                                                    world_size)
    else:
        batch_sampler = torch.utils.data.BatchSampler(sampler,
                                                      batch_size,
                                                      drop_last)

    data_loader = torch.utils.data.DataLoader(dataset,
                                              batch_sampler=batch_sampler,
                                              num_workers=args.num_workers,
                                              pin_memory=True)

    return data_loader


def make_tfrecord_loaders(args):
    """Load train/val/test dataset from shuffled TFRecords"""

84
    import data_utils.tf_dl
Raul Puri's avatar
Raul Puri committed
85
86
87
88
    data_set_args = {'batch_size': args.batch_size,
                     'max_seq_len': args.seq_length,
                     'max_preds_per_seq': args.max_preds_per_seq,
                     'train': True,
Raul Puri's avatar
Raul Puri committed
89
90
91
92
                     'num_workers': max(args.num_workers, 1),
                     'seed': args.seed + args.rank + 1,
                     'threaded_dl': args.num_workers > 0
                     }
Raul Puri's avatar
Raul Puri committed
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
    train = data_utils.tf_dl.TFRecordDataLoader(args.train_data,
                                                **data_set_args)
    data_set_args['train'] = False
    if args.eval_seq_length is not None:
        data_set_args['max_seq_len'] = args.eval_seq_length
    if args.eval_max_preds_per_seq is not None:
        data_set_args['max_preds_per_seq'] = args.eval_max_preds_per_seq
    valid = None
    if args.valid_data is not None:
        valid = data_utils.tf_dl.TFRecordDataLoader(args.valid_data,
                                                    **data_set_args)
    test = None
    if args.test_data is not None:
        test = data_utils.tf_dl.TFRecordDataLoader(args.test_data,
                                                   **data_set_args)
    tokenizer = data_utils.make_tokenizer(args.tokenizer_type,
                                          train,
                                          args.tokenizer_path,
                                          args.vocab_size,
                                          args.tokenizer_model_type,
                                          cache_dir=args.cache_dir)

    return (train, valid, test), tokenizer


def make_loaders(args):
    """makes training/val/test"""

121
    if args.data_loader == 'tfrecords':
Raul Puri's avatar
Raul Puri committed
122
        return make_tfrecord_loaders(args)
123
124
125
    world_size = torch.distributed.get_world_size(
        group=mpu.get_data_parallel_group())
    batch_size = args.batch_size * world_size
Raul Puri's avatar
Raul Puri committed
126
127
    eval_batch_size = batch_size
    if args.eval_batch_size is not None:
128
        eval_batch_size = args.eval_batch_size * world_size
Raul Puri's avatar
Raul Puri committed
129
130
    seq_length = args.seq_length
    if seq_length < 0:
131
        seq_length = seq_length * world_size
Raul Puri's avatar
Raul Puri committed
132
133
    eval_seq_length = args.eval_seq_length
    if eval_seq_length is not None and eval_seq_length < 0:
134
        eval_seq_length = eval_seq_length * world_size
Raul Puri's avatar
Raul Puri committed
135
    split = get_split(args)
136
137
    if args.data_path is not None:
        args.train_data = args.data_path
Raul Puri's avatar
Raul Puri committed
138
139
140
    data_set_args = {
        'path': args.train_data,
        'seq_length': seq_length,
141
        'lazy': args.data_loader == 'lazy',
Raul Puri's avatar
Raul Puri committed
142
143
144
145
146
147
148
149
150
151
152
153
        'delim': args.delim,
        'text_key': args.text_key,
        'label_key': 'label',
        'non_binary_cols': None,
        'ds_type': args.data_set_type,
        'split': split,
        'loose': args.loose_json,
        'tokenizer_type': args.tokenizer_type,
        'tokenizer_model_path': args.tokenizer_path,
        'vocab_size': args.vocab_size,
        'model_type': args.tokenizer_model_type,
        'cache_dir': args.cache_dir,
Raul Puri's avatar
Raul Puri committed
154
        'max_preds_per_seq': args.max_preds_per_seq,
155
156
        'presplit_sentences': args.presplit_sentences,
        'parallel_group': mpu.get_data_parallel_group()}
Raul Puri's avatar
Raul Puri committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

    eval_set_args = copy.copy(data_set_args)
    eval_set_args['split'] = [1.]
    # if optional eval args were set then replace their
    # equivalent values in the arg dict
    if eval_seq_length:
        eval_set_args['seq_length'] = eval_seq_length
    if args.eval_max_preds_per_seq:
        eval_set_args['max_preds_per_seq'] = args.eval_max_preds_per_seq
    if args.eval_text_key is not None:
        eval_set_args['text_key'] = args.eval_text_key

    # make datasets splits and tokenizer
    train = None
    valid = None
    test = None

    if args.train_data is not None:
        train, tokenizer = data_utils.make_dataset(**data_set_args)
        if data_utils.should_split(split):
            train, valid, test = train
178
        eval_set_args['tokenizer'] = tokenizer
Raul Puri's avatar
Raul Puri committed
179
180
181
182

    # make training and val dataset if necessary
    if valid is None and args.valid_data is not None:
        eval_set_args['path'] = args.valid_data
183
184
        valid, tokenizer = data_utils.make_dataset(**eval_set_args)
        eval_set_args['tokenizer'] = tokenizer
Raul Puri's avatar
Raul Puri committed
185
186
    if test is None and args.test_data is not None:
        eval_set_args['path'] = args.test_data
187
        test, tokenizer = data_utils.make_dataset(**eval_set_args)
Raul Puri's avatar
Raul Puri committed
188
189
190
191

    # wrap datasets with data loader
    if train is not None and args.batch_size > 0:
        train = make_data_loader(train, batch_size, args)
192
193
194
        args.do_train = True
    else:
        args.do_train = False
Raul Puri's avatar
Raul Puri committed
195
196
197
    eval_batch_size = eval_batch_size if eval_batch_size != 0 else batch_size
    if valid is not None:
        valid = make_data_loader(valid, eval_batch_size, args)
198
199
200
        args.do_valid = True
    else:
        args.do_valid = False
Raul Puri's avatar
Raul Puri committed
201
202
    if test is not None:
        test = make_data_loader(test, eval_batch_size, args)
203
204
205
        args.do_test = True
    else:
        args.do_test = False
Raul Puri's avatar
Raul Puri committed
206
207
208

    return (train, valid, test), tokenizer

Neel Kant's avatar
Neel Kant committed
209

Raul Puri's avatar
Raul Puri committed
210
211
212
213
214
215
216
217
218
219
220
221
222
def get_split(args):
    """
    Get dataset splits from comma separated string list
    """
    splits = []
    if args.split.find(',') != -1:
        splits = [float(s) for s in args.split.split(',')]
    elif args.split.find('/') != -1:
        splits = [float(s) for s in args.split.split('/')]
    else:
        splits = [float(args.split)]
    split_total = sum(splits)
    if split_total < 1.:
Neel Kant's avatar
Neel Kant committed
223
        splits.append(1 - split_total)
Raul Puri's avatar
Raul Puri committed
224
225
226
227
228
229
230
231
    while len(splits) < 3:
        splits.append(0.)
    splits = splits[:3]
    if args.valid_data is not None:
        splits[1] = 0.
    if args.test_data is not None:
        splits[2] = 0.
    final_sum = sum(splits)
Neel Kant's avatar
Neel Kant committed
232
    return [s / final_sum for s in splits]
Raul Puri's avatar
Raul Puri committed
233
234


Neel Kant's avatar
Neel Kant committed
235
def configure_data():
Raul Puri's avatar
Raul Puri committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    """add cmdline flags for configuring datasets"""
    # These are options that are used by data_utils, but are either
    # deprecated or not meant to be exposed to the command line user.
    # These options are intneded to be set in code by specific scripts.
    defaults = {
        'world_size': 1,
        'rank': -1,
        'persist_state': 0,
        'lazy': False,
        'transpose': False,
        'data_set_type': 'supervised',
        'seq_length': 256,
        'eval_seq_length': 256,
        'samples_per_shard': 100
    }

    return DataConfig(defaults=defaults)