training.py 38.6 KB
Newer Older
1
# coding=utf-8
Mohammad's avatar
Mohammad committed
2
# Copyright (c) 2020, NVIDIA CORPORATION.  All rights reserved.
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's avatar
Mohammad committed
16
"""Pretrain utilities."""
17
18
19

from datetime import datetime
import math
Mohammad's avatar
Mohammad committed
20
import sys
21
22
23
24
import time
# The earliest we can measure the start time.
_TRAIN_START_TIME = time.time()

25
26
27
import torch
from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP

Neel Kant's avatar
Neel Kant committed
28
from megatron import get_args
29
from megatron import get_signal_handler
Mohammad's avatar
Mohammad committed
30
31
from megatron import get_timers
from megatron import get_tensorboard_writer
32
from megatron import get_current_global_batch_size
mohammad's avatar
mohammad committed
33
from megatron import get_num_microbatches
mohammad's avatar
mohammad committed
34
from megatron import is_last_rank
mohammad's avatar
mohammad committed
35
from megatron import update_num_microbatches
36
from megatron import mpu
Neel Kant's avatar
Neel Kant committed
37
from megatron import print_rank_0
38
from megatron import print_rank_last
Mohammad's avatar
Mohammad committed
39
40
from megatron.checkpointing import load_checkpoint
from megatron.checkpointing import save_checkpoint
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
41
from megatron.model import Float16Module
42
from megatron.model import ModelType
mohammad's avatar
mohammad committed
43
from megatron.optimizer import get_megatron_optimizer
Mohammad's avatar
Mohammad committed
44
from megatron.initialize import initialize_megatron
45
from megatron.initialize import write_args_to_tensorboard
46
47
48
from megatron.learning_rates import AnnealingLR
from megatron.model import DistributedDataParallel as LocalDDP
from megatron.utils import check_adlr_autoresume_termination
49
from megatron.utils import unwrap_model
Vijay Korthikanti's avatar
Vijay Korthikanti committed
50
from megatron.data.data_samplers import build_pretraining_data_loader
mohammad's avatar
mohammad committed
51
from megatron.utils import calc_params_l2_norm
52
from megatron.schedules import get_forward_backward_func
53
from megatron.utils import report_memory
54
55


Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
56

57
58
59
60
61
62
63
def print_datetime(string):
    """Note that this call will sync across all ranks."""
    torch.distributed.barrier()
    time_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print_rank_0('[' + string + '] datetime: {} '.format(time_str))


64
def pretrain(train_valid_test_dataset_provider,
65
             model_provider,
66
             model_type,
67
68
             forward_step_func,
             extra_args_provider=None,
Vijay Korthikanti's avatar
Vijay Korthikanti committed
69
             args_defaults={}):
70
71
72
    """Main training program.

    This function will run the followings in the order provided:
Mohammad's avatar
Mohammad committed
73
74
        1) initialize Megatron.
        2) setup model, optimizer and lr schedule using the model_provider.
75
        3) call train_val_test_data_provider to get train/val/test datasets.
Mohammad's avatar
Mohammad committed
76
        4) train the modle using the forward_step_func.
77
78

    Arguments:
79
80
81
        train_valid_test_dataset_provider: a function that takes the size of
            train/valid/test dataset and returns `train, valid, test` datasets.
        model_provider: a function that returns a vanilla version of the
Mohammad's avatar
Mohammad committed
82
            model. By vanilla we mean a simple model on cpu with no fp16 or ddp.
83
        model_type: an enum that specifies the type of model being trained.
Mohammad's avatar
Mohammad committed
84
85
86
87
88
89
90
91
92
        forward_step_func: a function that takes a `data iterator` and `model`,
            and returns a `loss` scalar with a dictionary with key:values being
            the info we would like to monitor during training, for example
            `lm-loss: value`. We also require that this function add
            `batch generator` to the timers class.
        extra_args_provider: a function that takes a parser and adds arguments
            to it. It is used for programs to add their own arguments.
        args_defaults: a dictionary from argument-name to argument-value. It
            to set already parse arguments.
93
94
    """

95
    # Initalize and get arguments, timers, and Tensorboard writer.
96
97
    initialize_megatron(extra_args_provider=extra_args_provider,
                        args_defaults=args_defaults)
98

99
100
101
102
    # Adjust the startup time so it reflects the largest value.
    # This will be closer to what scheduler will see (outside of
    # image ... launches.
    global _TRAIN_START_TIME
103
    start_time_tensor = torch.cuda.DoubleTensor([_TRAIN_START_TIME])
104
105
106
    torch.distributed.all_reduce(start_time_tensor,
                                 op=torch.distributed.ReduceOp.MIN)
    _TRAIN_START_TIME = start_time_tensor.item()
mshoeybi's avatar
mshoeybi committed
107
    print_rank_0('time to initialize megatron (seconds): {:.3f}'.format(
108
109
110
        time.time() - _TRAIN_START_TIME))
    print_datetime('after megatron is initialized')

111
    args = get_args()
Mohammad's avatar
Mohammad committed
112
    timers = get_timers()
113
114

    # Model, optimizer, and learning rate.
115
    timers('model-and-optimizer-setup').start()
116
117
    model, optimizer, lr_scheduler = setup_model_and_optimizer(model_provider,
                                                               model_type)
118
    timers('model-and-optimizer-setup').stop()
119
120
    print_datetime('after model, optimizer, and learning rate '
                   'scheduler are built')
121
122

    # Data stuff.
123
124
    timers('train/valid/test-data-iterators-setup').start()
    if args.virtual_pipeline_model_parallel_size is not None:
125
        all_data_iterators = [
126
127
128
            build_train_valid_test_data_iterators(train_valid_test_dataset_provider)
            for _ in range(len(model))
        ]
129
130
131
        train_data_iterator = [data_iterators[0] for data_iterators in all_data_iterators]
        valid_data_iterator = [data_iterators[1] for data_iterators in all_data_iterators]
        test_data_iterator = [data_iterators[2] for data_iterators in all_data_iterators]
132
133
134
135
136
    else:
        train_data_iterator, valid_data_iterator, test_data_iterator \
            = build_train_valid_test_data_iterators(
                train_valid_test_dataset_provider)
    timers('train/valid/test-data-iterators-setup').stop()
mshoeybi's avatar
mshoeybi committed
137
    print_datetime('after dataloaders are built')
Mohammad's avatar
Mohammad committed
138
139

    # Print setup timing.
140
141
    print_rank_0('done with setup ...')
    timers.log(['model-and-optimizer-setup', 'train/valid/test-data-iterators-setup'])
Mohammad's avatar
Mohammad committed
142
    print_rank_0('training ...')
143
144

    iteration = 0
145
    if args.do_train and args.train_iters > 0:
mohammad's avatar
mohammad committed
146
147
148
        iteration = train(forward_step_func,
                          model, optimizer, lr_scheduler,
                          train_data_iterator, valid_data_iterator)
149
    print_datetime('after training is done')
Mohammad's avatar
Mohammad committed
150

151
152
153
    if args.do_valid:
        prefix = 'the end of training for val data'
        evaluate_and_print_results(prefix, forward_step_func,
154
                                   valid_data_iterator, model,
Mohammad's avatar
Mohammad committed
155
                                   iteration, False)
156
157

    if args.save and iteration != 0:
158
        save_checkpoint(iteration, model, optimizer, lr_scheduler)
159
160
161
162
163
164

    if args.do_test:
        # Run on test data.
        prefix = 'the end of training for test data'
        evaluate_and_print_results(prefix, forward_step_func,
                                   test_data_iterator, model,
Mohammad's avatar
Mohammad committed
165
                                   0, True)
166

167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def update_train_iters(args):

    # For iteration-based training, we don't need to do anything
    if args.train_iters:
        return

    # Constant batch size with sample-based training.
    if args.rampup_batch_size is None:
        args.train_iters = args.train_samples // args.global_batch_size

    else:
        # Sample based training with rampup batch size.
        iterations = 0
        consumed_samples = 0
        # Rampup phase.
        while consumed_samples <= int(args.rampup_batch_size[2]):
183
184
            update_num_microbatches(consumed_samples, consistency_check=False)
            consumed_samples += get_current_global_batch_size()
185
186
            iterations += 1
        # Reset
187
        update_num_microbatches(0, consistency_check=False)
188
189
190
191
192
193
194
195
        # Constant phase
        # Note that we throw away any partial last batch.
        iterations += (args.train_samples - consumed_samples) // \
                      args.global_batch_size
        args.train_iters = iterations

    print_rank_0('setting training iterations to {}'.format(args.train_iters))

196

197
def get_model(model_provider_func, model_type=ModelType.encoder_or_decoder, wrap_with_ddp=True):
198
    """Build the model."""
Mohammad's avatar
Mohammad committed
199
    args = get_args()
200
    args.model_type = model_type
201

202
    # Build model.
203
204
    if mpu.get_pipeline_model_parallel_world_size() > 1 and \
       args.virtual_pipeline_model_parallel_size is not None:
205
206
        assert model_type != ModelType.encoder_and_decoder, \
            "Interleaved schedule not supported for model with both encoder and decoder"
207
208
209
        model = []
        for i in range(args.virtual_pipeline_model_parallel_size):
            mpu.set_virtual_pipeline_model_parallel_rank(i)
210
211
212
            # Set pre_process and post_process only after virtual rank is set.
            pre_process = mpu.is_pipeline_first_stage()
            post_process = mpu.is_pipeline_last_stage()
213
            this_model = model_provider_func(
214
215
216
                pre_process=pre_process,
                post_process=post_process
            )
217
            this_model.model_type = model_type
218
            model.append(this_model)
219
    else:
220
221
        pre_process = mpu.is_pipeline_first_stage()
        post_process = mpu.is_pipeline_last_stage()
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
        add_encoder = True
        add_decoder = True
        if model_type == ModelType.encoder_and_decoder:
            if mpu.get_pipeline_model_parallel_world_size() > 1:
                assert args.pipeline_model_parallel_split_rank is not None, \
                    "Split rank needs to be specified for model with both encoder and decoder"
                rank = mpu.get_pipeline_model_parallel_rank()
                split_rank = args.pipeline_model_parallel_split_rank
                world_size = mpu.get_pipeline_model_parallel_world_size()
                pre_process = rank == 0 or rank == split_rank
                post_process = (rank == (split_rank - 1)) or (
                        rank == (world_size - 1))
                add_encoder = mpu.is_pipeline_stage_before_split()
                add_decoder = mpu.is_pipeline_stage_after_split()
            model = model_provider_func(
                pre_process=pre_process,
                post_process=post_process,
                add_encoder=add_encoder,
                add_decoder=add_decoder)
        else:
            model = model_provider_func(
                pre_process=pre_process,
                post_process=post_process
            )
        model.model_type = model_type
247

248
249
    if not isinstance(model, list):
        model = [model]
250

251
    # Set tensor model parallel attributes if not set.
mohammad's avatar
mohammad committed
252
253
254
    # Only parameters that are already tensor model parallel have these
    # attributes set for them. We should make sure the default attributes
    # are set for all params so the optimizer can use them.
255
256
257
    for model_module in model:
        for param in model_module.parameters():
            mpu.set_defaults_if_not_set_tensor_model_parallel_attributes(param)
258

259
260
    # Print number of parameters.
    if mpu.get_data_parallel_rank() == 0:
261
        print(' > number of parameters on (tensor, pipeline) '
262
              'model parallel rank ({}, {}): {}'.format(
263
264
            mpu.get_tensor_model_parallel_rank(),
            mpu.get_pipeline_model_parallel_rank(),
265
266
            sum([sum([p.nelement() for p in model_module.parameters()])
                 for model_module in model])), flush=True)
267
268

    # GPU allocation.
269
270
    for model_module in model:
        model_module.cuda(torch.cuda.current_device())
271
272

    # Fp16 conversion.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
273
274
    if args.fp16 or args.bf16:
        model = [Float16Module(model_module, args) for model_module in model]
275

276
277
278
279
280
281
    if wrap_with_ddp:
        if args.DDP_impl == 'torch':
            i = torch.cuda.current_device()
            model = [torchDDP(model_module, device_ids=[i], output_device=i,
                              process_group=mpu.get_data_parallel_group())
                     for model_module in model]
282

283
284
285
286
287
        elif args.DDP_impl == 'local':
            model = [LocalDDP(model_module,
                              args.accumulate_allreduce_grads_in_fp32,
                              args.use_contiguous_buffers_in_local_ddp)
                     for model_module in model]
288
289
290
291
            # broad cast params from data parallel src rank to other data parallel ranks
            if args.data_parallel_random_init:
                for model_module in model:
                    model_module.broadcast_params()
292
293
294
        else:
            raise NotImplementedError('Unknown DDP implementation specified: '
                                      '{}. Exiting.'.format(args.DDP_impl))
295

296
    return model
297
298


Mohammad's avatar
Mohammad committed
299
def get_learning_rate_scheduler(optimizer):
300
    """Build the learning rate scheduler."""
Mohammad's avatar
Mohammad committed
301
    args = get_args()
302

303
304
305
306
307
    # Iteration-based training.
    if args.train_iters:
        if args.lr_decay_iters is None:
            args.lr_decay_iters = args.train_iters
        decay_steps = args.lr_decay_iters * args.global_batch_size
308
309
        if args.lr_warmup_fraction is not None:
            warmup_steps = args.lr_warmup_fraction * decay_steps
310
311
        else:
            warmup_steps = args.lr_warmup_iters * args.global_batch_size
312
313
314
315
316
    # Sample-based training.
    elif args.train_samples:
        # We need to set training iters for later use. Technically
        # we need to adjust the training samples too (due to last
        # batch being incomplete) but we leave it as is for now.
317
        update_train_iters(args)
318
319
320
        if args.lr_decay_samples is None:
            args.lr_decay_samples = args.train_samples
        decay_steps = args.lr_decay_samples
321
322
        if args.lr_warmup_fraction is not None:
            warmup_steps = args.lr_warmup_fraction * decay_steps
323
324
        else:
            warmup_steps = args.lr_warmup_samples
325
    else:
326
327
328
        raise Exception(
            'either train-iters or train-samples should be provided.')

329
330
    lr_scheduler = AnnealingLR(
        optimizer,
331
        max_lr=args.lr,
332
        min_lr=args.min_lr,
333
334
        warmup_steps=warmup_steps,
        decay_steps=decay_steps,
335
        decay_style=args.lr_decay_style,
336
337
338
339
340
341
        use_checkpoint_lr_scheduler=args.use_checkpoint_lr_scheduler,
        override_lr_scheduler=args.override_lr_scheduler)

    return lr_scheduler


342
def setup_model_and_optimizer(model_provider_func, model_type):
343
    """Setup model and optimizer."""
Mohammad's avatar
Mohammad committed
344
    args = get_args()
345

346
    model = get_model(model_provider_func, model_type)
347

348
    unwrapped_model = unwrap_model(model,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
349
                                   (torchDDP, LocalDDP, Float16Module))
350
351
    optimizer = get_megatron_optimizer(unwrapped_model)

Mohammad's avatar
Mohammad committed
352
    lr_scheduler = get_learning_rate_scheduler(optimizer)
353
354

    if args.load is not None:
355
356
357
358
        timers = get_timers()
        # Extra barrier is added to make sure all ranks report the
        # max time.
        torch.distributed.barrier()
359
        timers('load-checkpoint').start()
360
        args.iteration = load_checkpoint(model, optimizer, lr_scheduler)
361
        torch.distributed.barrier()
362
363
        timers('load-checkpoint').stop()
        timers.log(['load-checkpoint'])
364
365
366
    else:
        args.iteration = 0

mohammad's avatar
mohammad committed
367
    # We only support local DDP with multiple micro-batches.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
368
    if len(model) > 1 or mpu.get_pipeline_model_parallel_world_size() > 1:
mohammad's avatar
mohammad committed
369
370
        assert args.DDP_impl == 'local'

Neel Kant's avatar
Neel Kant committed
371
    # get model without FP16 and/or TorchDDP wrappers
Mostofa Patwary's avatar
Mostofa Patwary committed
372
373
    if args.iteration == 0 and len(unwrapped_model) == 1 \
        and hasattr(unwrapped_model[0], 'init_state_dict_from_bert'):
Mostofa Patwary's avatar
Mostofa Patwary committed
374
        print_rank_0("Initializing ICT from pretrained BERT model")
Mostofa Patwary's avatar
Mostofa Patwary committed
375
        unwrapped_model[0].init_state_dict_from_bert()
Mostofa Patwary's avatar
Mostofa Patwary committed
376
377
        if args.fp16:
            optimizer.reload_model_params()
Neel Kant's avatar
Neel Kant committed
378

379
380
381
    return model, optimizer, lr_scheduler


382
383
384
385
386
387
388
def train_step(forward_step_func, data_iterator,
               model, optimizer, lr_scheduler):
    """Single training step."""
    args = get_args()
    timers = get_timers()

    # Set grad to zero.
389
    if args.DDP_impl == 'local' and args.use_contiguous_buffers_in_local_ddp:
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
390
391
        for partition in model:
            partition.zero_grad_buffer()
392
    optimizer.zero_grad()
393

394
    forward_backward_func = get_forward_backward_func()
395
396
397
    losses_reduced = forward_backward_func(
        forward_step_func, data_iterator, model,
        optimizer, timers, forward_only=False)
398

399
    # Empty unused memory
Lawrence McAfee's avatar
Lawrence McAfee committed
400
    if args.empty_unused_memory_level >= 1:
401
402
        torch.cuda.empty_cache()

403
404
    # All-reduce if needed.
    if args.DDP_impl == 'local':
405
        timers('backward-params-all-reduce').start()
406
        for model_module in model:
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
407
            model_module.allreduce_gradients()
408
        timers('backward-params-all-reduce').stop()
409

410
411
412
413
    # All-reduce word_embeddings' grad across first and last stages to ensure
    # that word_embeddings parameters stay in sync.
    # This should only run for models that support pipelined model parallelism
    # (BERT and GPT-2).
414
    timers('backward-embedding-all-reduce').start()
415
    if mpu.is_rank_in_embedding_group(ignore_virtual=True) and \
416
            mpu.get_pipeline_model_parallel_world_size() > 1:
417
418
419
420
        if mpu.is_pipeline_first_stage(ignore_virtual=True):
            unwrapped_model = model[0]
        elif mpu.is_pipeline_last_stage(ignore_virtual=True):
            unwrapped_model = model[-1]
421
422
        else:  # We do not support the interleaved schedule for T5 yet.
            unwrapped_model = model[0]
423
        unwrapped_model = unwrap_model(
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
424
            unwrapped_model, (torchDDP, LocalDDP, Float16Module))
425

426
427
        if unwrapped_model.share_word_embeddings:
            word_embeddings_weight = unwrapped_model.word_embeddings_weight()
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
428
429
430
431
432
            if args.DDP_impl == 'local':
                grad = word_embeddings_weight.main_grad
            else:
                grad = word_embeddings_weight.grad
            torch.distributed.all_reduce(grad, group=mpu.get_embedding_group())
Vijay Korthikanti's avatar
Vijay Korthikanti committed
433

Vijay Korthikanti's avatar
Vijay Korthikanti committed
434
435
436
    # All-reduce position_embeddings grad across first (encoder) and split (decoder) 
    # stages to ensure that position embeddings parameters stay in sync.
    # This should only run for T5 models with pipeline parallelism
Vijay Korthikanti's avatar
Vijay Korthikanti committed
437
438
439
440
441
442
    if mpu.is_rank_in_position_embedding_group() and \
            mpu.get_pipeline_model_parallel_world_size() > 1 and \
            args.pipeline_model_parallel_split_rank is not None:
        unwrapped_model = model[0]
        unwrapped_model = unwrap_model(
            unwrapped_model, (torchDDP, LocalDDP, Float16Module))
Vijay Korthikanti's avatar
Vijay Korthikanti committed
443
444
        assert args.DDP_impl == 'local', \
            'T5 model is only supported with local DDP mode'
Vijay Korthikanti's avatar
Vijay Korthikanti committed
445
446
        grad = unwrapped_model.language_model.embedding.position_embeddings.weight.main_grad
        torch.distributed.all_reduce(grad, group=mpu.get_position_embedding_group())
447
    timers('backward-embedding-all-reduce').stop()
448

449
450
    # Update parameters.
    timers('optimizer').start()
451
    update_successful, grad_norm, num_zeros_in_grad = optimizer.step()
452
453
454
    timers('optimizer').stop()

    # Update learning rate.
455
    if update_successful:
456
457
458
459
        increment = get_num_microbatches() * \
                    args.micro_batch_size * \
                    args.data_parallel_size
        lr_scheduler.step(increment=increment)
mohammad's avatar
mohammad committed
460
        skipped_iter = 0
461
462
463
    else:
        skipped_iter = 1

464
    # Empty unused memory
Lawrence McAfee's avatar
Lawrence McAfee committed
465
    if args.empty_unused_memory_level >= 2:
466
467
        torch.cuda.empty_cache()

468
    if mpu.is_pipeline_last_stage(ignore_virtual=True):
469
470
471
472
        # Average loss across microbatches.
        loss_reduced = {}
        for key in losses_reduced[0]:
            losses_reduced_for_key = [x[key] for x in losses_reduced]
473
            loss_reduced[key] = sum(losses_reduced_for_key) / len(losses_reduced_for_key)
474
475
        return loss_reduced, skipped_iter, grad_norm, num_zeros_in_grad
    return {}, skipped_iter, grad_norm, num_zeros_in_grad
476
477


Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
478
def training_log(loss_dict, total_loss_dict, learning_rate, iteration,
mohammad's avatar
mohammad committed
479
                 loss_scale, report_memory_flag, skipped_iter,
480
                 grad_norm, params_norm, num_zeros_in_grad):
Mohammad's avatar
Mohammad committed
481
482
483
484
    """Log training information such as losses, timing, ...."""
    args = get_args()
    timers = get_timers()
    writer = get_tensorboard_writer()
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
485

mohammad's avatar
mohammad committed
486
487
    # Advanced, skipped, and Nan iterations.
    advanced_iters_key = 'advanced iterations'
mohammad's avatar
mohammad committed
488
    skipped_iters_key = 'skipped iterations'
mohammad's avatar
mohammad committed
489
490
491
492
493
494
495
496
497
    nan_iters_key = 'nan iterations'
    # Advanced iterations.
    if not skipped_iter:
        total_loss_dict[advanced_iters_key] = total_loss_dict.get(
            advanced_iters_key, 0) + 1
    else:
        if advanced_iters_key not in total_loss_dict:
            total_loss_dict[advanced_iters_key] = 0
    # Skipped iterations.
mohammad's avatar
mohammad committed
498
499
    total_loss_dict[skipped_iters_key] = total_loss_dict.get(
        skipped_iters_key, 0) + skipped_iter
mohammad's avatar
mohammad committed
500
    # Update losses and set nan iterations
mohammad's avatar
mohammad committed
501
    got_nan = False
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
502
    for key in loss_dict:
mohammad's avatar
mohammad committed
503
        if not skipped_iter:
504
505
            total_loss_dict[key] = total_loss_dict.get(
                key, torch.cuda.FloatTensor([0.0])) + loss_dict[key]
mohammad's avatar
mohammad committed
506
507
508
509
510
        else:
            value = loss_dict[key].float().sum().item()
            is_nan = value == float('inf') or \
                     value == -float('inf') or \
                     value != value
mohammad's avatar
mohammad committed
511
            got_nan = got_nan or is_nan
mohammad's avatar
mohammad committed
512
513
    total_loss_dict[nan_iters_key] = total_loss_dict.get(
        nan_iters_key, 0) + int(got_nan)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
514
515
516

    # Logging.
    timers_to_log = []
Neel Kant's avatar
Neel Kant committed
517

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
518
519
520
    def add_to_logging(name):
        if name in timers.timers:
            timers_to_log.append(name)
521
522
523
    add_to_logging('forward-compute')
    add_to_logging('forward-recv')
    add_to_logging('forward-send')
524
    add_to_logging('forward-backward-send-forward-backward-recv')
525
526
527
    add_to_logging('backward-compute')
    add_to_logging('backward-recv')
    add_to_logging('backward-send')
Deepak Narayanan's avatar
Deepak Narayanan committed
528
    add_to_logging('backward-send-forward-recv')
529
    add_to_logging('backward-send-backward-recv')
530
    add_to_logging('backward-params-all-reduce')
531
    add_to_logging('backward-embedding-all-reduce')
532
    add_to_logging('optimizer-copy-to-main-grad')
mohammad's avatar
mohammad committed
533
    add_to_logging('optimizer-unscale-and-check-inf')
534
535
    add_to_logging('optimizer-clip-main-grad')
    add_to_logging('optimizer-copy-main-to-model-params')
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
536
    add_to_logging('optimizer')
mohammad's avatar
mohammad committed
537
    add_to_logging('batch-generator')
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
538

mohammad's avatar
mohammad committed
539
    # Calculate batch size.
mshoeybi's avatar
mshoeybi committed
540
541
542
    batch_size = args.micro_batch_size * args.data_parallel_size * \
        get_num_microbatches()

mohammad's avatar
mohammad committed
543
544
545
    total_iterations = total_loss_dict[advanced_iters_key] + \
                       total_loss_dict[skipped_iters_key]

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
546
    # Tensorboard values.
547
548
549
550
551
552
553
554
555
556
    if writer and (iteration % args.tensorboard_log_interval == 0 ) and \
       is_last_rank():
        if args.log_learning_rate_to_tensorboard:
            writer.add_scalar('learning-rate', learning_rate, iteration)
            writer.add_scalar('learning-rate vs samples', learning_rate,
                              args.consumed_train_samples)
        if args.log_batch_size_to_tensorboard:
            writer.add_scalar('batch-size', batch_size, iteration)
            writer.add_scalar('batch-size vs samples', batch_size,
                              args.consumed_train_samples)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
557
        for key in loss_dict:
mohammad's avatar
mohammad committed
558
559
            writer.add_scalar(key , loss_dict[key], iteration)
            writer.add_scalar(key + ' vs samples', loss_dict[key],
560
                              args.consumed_train_samples)
561
562
563
564
        if args.log_loss_scale_to_tensorboard:
            writer.add_scalar('loss-scale', loss_scale, iteration)
            writer.add_scalar('loss-scale vs samples', loss_scale,
                              args.consumed_train_samples)
565
566
567
568
        if args.log_world_size_to_tensorboard:
            writer.add_scalar('world-size', args.world_size, iteration)
            writer.add_scalar('world-size vs samples', args.world_size,
                              args.consumed_train_samples)
569
570
571
572
        if grad_norm is not None:
            writer.add_scalar('grad-norm', grad_norm, iteration)
            writer.add_scalar('grad-norm vs samples', grad_norm,
                              args.consumed_train_samples)
573
574
575
        if num_zeros_in_grad is not None:
            writer.add_scalar('num-zeros', num_zeros_in_grad, iteration)
            writer.add_scalar('num-zeros vs samples', num_zeros_in_grad,
Rewon Child's avatar
Rewon Child committed
576
                              args.consumed_train_samples)
mohammad's avatar
mohammad committed
577
578
579
580
        if params_norm is not None:
            writer.add_scalar('params-norm', params_norm, iteration)
            writer.add_scalar('params-norm vs samples', params_norm,
                              args.consumed_train_samples)
581
582
583
        if args.log_timers_to_tensorboard:
            timers.write(timers_to_log, writer, iteration,
                         normalizer=total_iterations)
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
        if args.log_memory_to_tensorboard:
            mem_stats = torch.cuda.memory_stats()
            writer.add_scalar(
                "mem-reserved-bytes",
                mem_stats["reserved_bytes.all.current"],
                iteration,
            )
            writer.add_scalar(
                "mem-allocated-bytes",
                mem_stats["allocated_bytes.all.current"],
                iteration,
            )
            writer.add_scalar(
                "mem-allocated-count",
                mem_stats["allocation.all.current"],
                iteration,
            )
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
601
602

    if iteration % args.log_interval == 0:
603
        elapsed_time = timers('interval-time').elapsed()
mohammad's avatar
mohammad committed
604
        elapsed_time_per_iteration = elapsed_time / total_iterations
mshoeybi's avatar
mshoeybi committed
605
        if writer:
606
607
608
            if args.log_timers_to_tensorboard:
                writer.add_scalar('iteration-time',
                                  elapsed_time_per_iteration, iteration)
609
610
        log_string = ' iteration {:8d}/{:8d} |'.format(
            iteration, args.train_iters)
mshoeybi's avatar
mshoeybi committed
611
        log_string += ' consumed samples: {:12d} |'.format(
612
            args.consumed_train_samples)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
613
        log_string += ' elapsed time per iteration (ms): {:.1f} |'.format(
mohammad's avatar
mohammad committed
614
            elapsed_time_per_iteration * 1000.0)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
615
        log_string += ' learning rate: {:.3E} |'.format(learning_rate)
mohammad's avatar
mohammad committed
616
        log_string += ' global batch size: {:5d} |'.format(batch_size)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
617
        for key in total_loss_dict:
mohammad's avatar
mohammad committed
618
619
620
621
            if key not in [advanced_iters_key, skipped_iters_key,
                           nan_iters_key]:
                avg = total_loss_dict[key].item() / \
                      float(max(1, total_loss_dict[advanced_iters_key]))
622
623
624
                if avg > 0.0:
                    log_string += ' {}: {:.6E} |'.format(key, avg)
                total_loss_dict[key] = torch.cuda.FloatTensor([0.0])
625
        log_string += ' loss scale: {:.1f} |'.format(loss_scale)
626
627
        if grad_norm is not None:
            log_string += ' grad norm: {:.3f} |'.format(grad_norm)
628
629
        if num_zeros_in_grad is not None:
            log_string += ' num zeros: {:.1f} |'.format(num_zeros_in_grad)
mohammad's avatar
mohammad committed
630
631
        if params_norm is not None:
            log_string += ' params norm: {:.3f} |'.format(params_norm)
mohammad's avatar
mohammad committed
632
633
        log_string += ' number of skipped iterations: {:3d} |'.format(
            total_loss_dict[skipped_iters_key])
mohammad's avatar
mohammad committed
634
        log_string += ' number of nan iterations: {:3d} |'.format(
mohammad's avatar
mohammad committed
635
636
            total_loss_dict[nan_iters_key])
        total_loss_dict[advanced_iters_key] = 0
mohammad's avatar
mohammad committed
637
        total_loss_dict[skipped_iters_key] = 0
mohammad's avatar
mohammad committed
638
        total_loss_dict[nan_iters_key] = 0
639
        print_rank_last(log_string)
640
641
642
        if report_memory_flag and learning_rate > 0.:
            # Report memory after optimizer state has been initialized.
            report_memory('(after {} iterations)'.format(iteration))
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
643
644
645
646
647
648
            report_memory_flag = False
        timers.log(timers_to_log, normalizer=args.log_interval)

    return report_memory_flag


649
650
651
652
653
def save_checkpoint_and_time(iteration, model, optimizer, lr_scheduler):
    timers = get_timers()
    # Extra barrier is added to make sure
    # all ranks report the max time.
    torch.distributed.barrier()
654
    timers('save-checkpoint').start()
655
656
    save_checkpoint(iteration, model, optimizer, lr_scheduler)
    torch.distributed.barrier()
657
658
    timers('save-checkpoint').stop()
    timers.log(['save-checkpoint'])
659
660


661
def train(forward_step_func, model, optimizer, lr_scheduler,
662
          train_data_iterator, valid_data_iterator):
663
    """Train the model function."""
Mohammad's avatar
Mohammad committed
664
665
    args = get_args()
    timers = get_timers()
666

667
668
669
    # Write args to tensorboard
    write_args_to_tensorboard()

670
    # Turn on training mode which enables dropout.
671
672
    for model_module in model:
        model_module.train()
673
674
675
676
677
678
679

    # Tracking loss.
    total_loss_dict = {}

    # Iterations.
    iteration = args.iteration

680
    timers('interval-time').start()
681
    print_datetime('before the start of training step')
682
683
    report_memory_flag = True
    while iteration < args.train_iters:
mohammad's avatar
mohammad committed
684
        update_num_microbatches(args.consumed_train_samples)
685
686
687
688
689
690
        loss_dict, skipped_iter, grad_norm, num_zeros_in_grad = \
            train_step(forward_step_func,
                       train_data_iterator,
                       model,
                       optimizer,
                       lr_scheduler)
691
        iteration += 1
692
        args.consumed_train_samples += mpu.get_data_parallel_world_size() * \
693
                                       args.micro_batch_size * \
mohammad's avatar
mohammad committed
694
                                       get_num_microbatches()
695
696

        # Logging.
697
        loss_scale = optimizer.get_loss_scale().item()
698
699
700
        params_norm = None
        if args.log_params_norm:
            params_norm = calc_params_l2_norm(model)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
701
702
        report_memory_flag = training_log(loss_dict, total_loss_dict,
                                          optimizer.param_groups[0]['lr'],
Mohammad's avatar
Mohammad committed
703
                                          iteration, loss_scale,
704
                                          report_memory_flag, skipped_iter,
705
                                          grad_norm, params_norm, num_zeros_in_grad)
706
707

        # Autoresume
708
709
        if args.adlr_autoresume and \
           (iteration % args.adlr_autoresume_interval == 0):
710
            check_adlr_autoresume_termination(iteration, model, optimizer,
711
                                              lr_scheduler)
712
713
714
715
716
717

        # Evaluation
        if args.eval_interval and iteration % args.eval_interval == 0 and \
           args.do_valid:
            prefix = 'iteration {}'.format(iteration)
            evaluate_and_print_results(prefix, forward_step_func,
718
                                       valid_data_iterator, model,
Mohammad's avatar
Mohammad committed
719
                                       iteration, False)
720

721
722
        # Checkpointing
        saved_checkpoint = False
723
724
725
726
727
728
729
730
        if args.exit_signal_handler:
            signal_handler = get_signal_handler()
            if any(signal_handler.signals_received()):
                save_checkpoint_and_time(iteration, model, optimizer,
                                         lr_scheduler)
                print_datetime('exiting program after receiving SIGTERM.')
                sys.exit()

731
732
733
734
735
736
        if args.save and args.save_interval and \
           iteration % args.save_interval == 0:
            save_checkpoint_and_time(iteration, model, optimizer,
                                     lr_scheduler)
            saved_checkpoint = True

737
738
739
740
741
742
743
744
745
746
747
748
        # Exiting based on duration
        if args.exit_duration_in_mins:
            train_time = (time.time() - _TRAIN_START_TIME) / 60.0
            done_cuda = torch.cuda.IntTensor(
                [train_time > args.exit_duration_in_mins])
            torch.distributed.all_reduce(
                done_cuda, op=torch.distributed.ReduceOp.MAX)
            done = done_cuda.item()
            if done:
                if not saved_checkpoint:
                    save_checkpoint_and_time(iteration, model, optimizer,
                                             lr_scheduler)
749
                print_datetime('exiting program after {} minutes'.format(train_time))
750
751
                sys.exit()

752
        # Exiting based on iterations
753
        if args.exit_interval and iteration % args.exit_interval == 0:
754
755
756
            if not saved_checkpoint:
                save_checkpoint_and_time(iteration, model, optimizer,
                                         lr_scheduler)
757
            torch.distributed.barrier()
758
            print_datetime('exiting program at iteration {}'.format(iteration))
Mohammad's avatar
Mohammad committed
759
            sys.exit()
760

761

mohammad's avatar
mohammad committed
762
    return iteration
763
764


Mohammad's avatar
Mohammad committed
765
def evaluate(forward_step_func, data_iterator, model, verbose=False):
766
    """Evaluation."""
Mohammad's avatar
Mohammad committed
767
    args = get_args()
768
769

    # Turn on evaluation mode which disables dropout.
770
771
    for model_module in model:
        model_module.eval()
772
773
774
775
776
777
778
779
780
781

    total_loss_dict = {}

    with torch.no_grad():
        iteration = 0
        while iteration < args.eval_iters:
            iteration += 1
            if verbose and iteration % args.log_interval == 0:
                print_rank_0('Evaluating iter {}/{}'.format(iteration,
                                                            args.eval_iters))
782

783
            forward_backward_func = get_forward_backward_func()
784
785
786
787
            loss_dicts = forward_backward_func(
                forward_step_func, data_iterator, model, optimizer=None,
                timers=None, forward_only=True)

788
            # Empty unused memory
Lawrence McAfee's avatar
Lawrence McAfee committed
789
            if args.empty_unused_memory_level >= 1:
790
791
                torch.cuda.empty_cache()

792
793
794
            if mpu.is_pipeline_last_stage(ignore_virtual=True):
                # Reduce across processes.
                for loss_dict in loss_dicts:
795
                    for key in loss_dict:
796
797
                        total_loss_dict[key] = total_loss_dict.get(
                            key, torch.cuda.FloatTensor([0.0])) + loss_dict[key]
798

799
            args.consumed_valid_samples += mpu.get_data_parallel_world_size() \
800
                                           * args.micro_batch_size \
mohammad's avatar
mohammad committed
801
                                           * get_num_microbatches()
802
    # Move model back to the train mode.
803
804
    for model_module in model:
        model_module.train()
805
806

    for key in total_loss_dict:
mohammad's avatar
mohammad committed
807
        total_loss_dict[key] /= args.eval_iters * get_num_microbatches()
808
809
810
811
812

    return total_loss_dict

def evaluate_and_print_results(prefix, forward_step_func,
                               data_iterator, model,
Mohammad's avatar
Mohammad committed
813
                               iteration, verbose=False):
814
    """Helper function to evaluate and dump results on screen."""
815
    args = get_args()
Mohammad's avatar
Mohammad committed
816
817
818
    writer = get_tensorboard_writer()

    total_loss_dict = evaluate(forward_step_func, data_iterator, model, verbose)
819
820
821
822
823
    string = ' validation loss at {} | '.format(prefix)
    for key in total_loss_dict:
        string += '{} value: {:.6E} | '.format(key, total_loss_dict[key].item())
        ppl = math.exp(min(20, total_loss_dict[key].item()))
        string += '{} PPL: {:.6E} | '.format(key, ppl)
mshoeybi's avatar
mshoeybi committed
824
        if writer:
mohammad's avatar
mohammad committed
825
            writer.add_scalar('{} validation'.format(key),
826
827
                              total_loss_dict[key].item(),
                              iteration)
mohammad's avatar
mohammad committed
828
            writer.add_scalar('{} validation vs samples'.format(key),
829
830
                              total_loss_dict[key].item(),
                              args.consumed_train_samples)
831
            if args.log_validation_ppl_to_tensorboard:
mohammad's avatar
mohammad committed
832
                writer.add_scalar('{} validation ppl'.format(key), ppl,
833
                                  iteration)
mohammad's avatar
mohammad committed
834
                writer.add_scalar('{} validation ppl vs samples'.format(key),
835
                                  ppl, args.consumed_train_samples)
836
837

    length = len(string) + 1
838
839
840
    print_rank_last('-' * length)
    print_rank_last(string)
    print_rank_last('-' * length)
841
842


Vijay Korthikanti's avatar
Vijay Korthikanti committed
843
def cyclic_iter(iter):
844
    while True:
Vijay Korthikanti's avatar
Vijay Korthikanti committed
845
        for x in iter:
846
847
            yield x

848
849
850
def build_train_valid_test_data_iterators(
        build_train_valid_test_datasets_provider):
    """XXX"""
Mohammad's avatar
Mohammad committed
851
    args = get_args()
852

853
854
855
    (train_dataloader, valid_dataloader, test_dataloader) = (None, None, None)

    print_rank_0('> building train, validation, and test datasets ...')
856
857
858

    # Backward compatibility, assume fixed batch size.
    if args.iteration > 0 and args.consumed_train_samples == 0:
859
860
        assert args.train_samples is None, \
            'only backward compatiblity support for iteration-based training'
mohammad's avatar
mohammad committed
861
        args.consumed_train_samples = args.iteration * args.global_batch_size
862
    if args.iteration > 0 and args.consumed_valid_samples == 0:
863
864
865
        if args.train_samples is None:
            args.consumed_valid_samples = (args.iteration // args.eval_interval) * \
                args.eval_iters * args.global_batch_size
866

867
    # Data loader only on rank 0 of each model parallel group.
868
    if mpu.get_tensor_model_parallel_rank() == 0:
869
870

        # Number of train/valid/test samples.
871
872
873
874
875
876
        if args.train_samples:
            train_samples = args.train_samples
        else:
            train_samples = args.train_iters * args.global_batch_size
        eval_iters = (args.train_iters // args.eval_interval + 1) * \
                     args.eval_iters
877
        test_iters = args.eval_iters
878
        train_val_test_num_samples = [train_samples,
mohammad's avatar
mohammad committed
879
880
                                      eval_iters * args.global_batch_size,
                                      test_iters * args.global_batch_size]
881
882
883
884
885
886
887
888
889
890
        print_rank_0(' > datasets target sizes (minimum size):')
        print_rank_0('    train:      {}'.format(train_val_test_num_samples[0]))
        print_rank_0('    validation: {}'.format(train_val_test_num_samples[1]))
        print_rank_0('    test:       {}'.format(train_val_test_num_samples[2]))

        # Build the datasets.
        train_ds, valid_ds, test_ds = build_train_valid_test_datasets_provider(
            train_val_test_num_samples)

        # Build dataloders.
891
892
893
894
895
        train_dataloader = build_pretraining_data_loader(
            train_ds, args.consumed_train_samples)
        valid_dataloader = build_pretraining_data_loader(
            valid_ds, args.consumed_valid_samples)
        test_dataloader = build_pretraining_data_loader(test_ds, 0)
896
897
898
899
900
901
902
903
904
905
906
907
908

        # Flags to know if we need to do training/validation/testing.
        do_train = train_dataloader is not None and args.train_iters > 0
        do_valid = valid_dataloader is not None and args.eval_iters > 0
        do_test = test_dataloader is not None and args.eval_iters > 0
        # Need to broadcast num_tokens and num_type_tokens.
        flags = torch.cuda.LongTensor(
            [int(do_train), int(do_valid), int(do_test)])
    else:
        flags = torch.cuda.LongTensor([0, 0, 0])

    # Broadcast num tokens.
    torch.distributed.broadcast(flags,
909
910
                                mpu.get_tensor_model_parallel_src_rank(),
                                group=mpu.get_tensor_model_parallel_group())
911
912
913
914
    args.do_train = flags[0].item()
    args.do_valid = flags[1].item()
    args.do_test = flags[2].item()

Vijay Korthikanti's avatar
Vijay Korthikanti committed
915

916
    # Build iterators.
Vijay Korthikanti's avatar
Vijay Korthikanti committed
917
918
919
    dl_type = args.dataloader_type
    assert dl_type in ['single', 'cyclic']

920
    if train_dataloader is not None:
Vijay Korthikanti's avatar
Vijay Korthikanti committed
921
922
        train_data_iterator = iter(train_dataloader) if dl_type == 'single' \
                              else iter(cyclic_iter(train_dataloader))
923
924
925
    else:
        train_data_iterator = None

926
    if valid_dataloader is not None:
Vijay Korthikanti's avatar
Vijay Korthikanti committed
927
928
        valid_data_iterator = iter(valid_dataloader) if dl_type == 'single' \
                              else iter(cyclic_iter(valid_dataloader))
929
    else:
930
        valid_data_iterator = None
931

932
    if test_dataloader is not None:
Vijay Korthikanti's avatar
Vijay Korthikanti committed
933
934
        test_data_iterator = iter(test_dataloader) if dl_type == 'single' \
                             else iter(cyclic_iter(test_dataloader))
935
936
937
    else:
        test_data_iterator = None

938
    return train_data_iterator, valid_data_iterator, test_data_iterator