pretrain_gpt2.py 5.42 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# coding=utf-8
# Copyright (c) 2019, NVIDIA CORPORATION.  All rights reserved.
#
# 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.

"""Pretrain GPT2"""

import torch

Mohammad's avatar
Mohammad committed
20
from gpt2_data_loader import make_gpt2_dataloaders
Mohammad's avatar
Mohammad committed
21
22
from megatron import get_args
from megatron import get_timers
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
23
from megatron import mpu
Mohammad's avatar
Mohammad committed
24
from megatron import print_rank_0
25
from megatron.model import GPT2Model
Mohammad's avatar
Mohammad committed
26
from megatron.training import pretrain
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
27
from megatron.utils import get_ltor_masks_and_position_ids
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
28
from megatron.utils import reduce_losses
Mohammad's avatar
Mohammad committed
29
import os
30

Mohammad's avatar
Mohammad committed
31
def model_provider():
32
    """Build the model."""
Mohammad's avatar
Mohammad committed
33
    args = get_args()
34
35
36

    print_rank_0('building GPT2 model ...')
    model = GPT2Model(num_layers=args.num_layers,
Mohammad's avatar
Mohammad committed
37
                      vocab_size=args.padded_vocab_size,
38
39
40
41
42
43
44
45
                      hidden_size=args.hidden_size,
                      num_attention_heads=args.num_attention_heads,
                      embedding_dropout_prob=args.hidden_dropout,
                      attention_dropout_prob=args.attention_dropout,
                      output_dropout_prob=args.hidden_dropout,
                      max_sequence_length=args.max_position_embeddings,
                      checkpoint_activations=args.checkpoint_activations,
                      checkpoint_num_layers=args.checkpoint_num_layers,
46
                      layernorm_epsilon=args.layernorm_epsilon,
47
48
49
                      parallel_output=True,
                      apply_query_key_layer_scaling=args.apply_query_key_layer_scaling,
                      attention_softmax_in_fp32=args.attention_softmax_in_fp32)
50
51
52
53

    return model


Mohammad's avatar
Mohammad committed
54
def get_batch(data_iterator):
55
    """Generate a batch"""
Mohammad's avatar
Mohammad committed
56
    args = get_args()
57

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    # Items and their type.
    keys = ['text']
    datatype = torch.int64

    # Broadcast data.
    if data_iterator is not None:
        data = next(data_iterator)
    else:
        data = None
    data_b = mpu.broadcast_data(keys, data, datatype)

    # Unpack.
    tokens_ = data_b['text'].long()
    labels = tokens_[:, 1:].contiguous()
    tokens = tokens_[:, :-1].contiguous()

    # Get the masks and postition ids.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
75
    attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids(
76
77
78
        tokens,
        args.eod_token,
        args.reset_position_ids,
79
80
        args.reset_attention_mask,
        args.eod_mask_loss)
81
82
83
84
85
86
87
    # Convert
    if args.fp16:
        attention_mask = attention_mask.half()

    return tokens, labels, loss_mask, attention_mask, position_ids


Mohammad's avatar
Mohammad committed
88
def forward_step(data_iterator, model):
89
    """Forward step."""
Mohammad's avatar
Mohammad committed
90
91
    args = get_args()
    timers = get_timers()
92
93
94
95

    # Get the batch.
    timers('batch generator').start()
    tokens, labels, loss_mask, attention_mask, position_ids = get_batch(
Mohammad's avatar
Mohammad committed
96
        data_iterator)
97
98
99
100
101
102
103
104
105
    timers('batch generator').stop()

    # Forward model.
    output = model(tokens, position_ids, attention_mask)
    losses = mpu.vocab_parallel_cross_entropy(output.contiguous().float(),
                                              labels)
    loss_mask = loss_mask.view(-1)
    loss = torch.sum(losses.view(-1) * loss_mask) / loss_mask.sum()

106
    # Reduce loss for logging.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
107
    reduced_loss = reduce_losses([loss])
108

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
109
    return loss, {'lm loss': reduced_loss[0]}
110
111


Mohammad's avatar
Mohammad committed
112
def get_train_val_test_data():
113
    """Load the data on rank zero and boradcast number of tokens to all GPUS."""
Mohammad's avatar
Mohammad committed
114
115
    args = get_args()
    
116
117
118
119
    (train_data, val_data, test_data) = (None, None, None)

    # Data loader only on rank 0 of each model parallel group.
    if mpu.get_model_parallel_rank() == 0:
Mohammad's avatar
Mohammad committed
120
121
122
123
124
125
126
127

        args.cache_dir = 'cache'
        args.train_data = os.path.join(args.data_path, 'train')
        args.valid_data = os.path.join(args.data_path, 'valid')
        args.test_data = os.path.join(args.data_path, 'test')
        (train_data, val_data, test_data), num_tokens, \
            eod_token = make_gpt2_dataloaders(args)

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
128
        # pad.
Mohammad's avatar
Mohammad committed
129
130
        from megatron.tokenizer.tokenizer import _vocab_size_with_padding
        num_tokens = _vocab_size_with_padding(num_tokens, args)
131
        print_rank_0('> found end-of-document token: {}'.format(eod_token))
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
132
133
134
135
        token_counts = torch.cuda.LongTensor([num_tokens, eod_token,
                                              int(args.do_train),
                                              int(args.do_valid),
                                              int(args.do_test)])
136
137
138
139
140
141
142
143
144
145
146
147
148
    else:
        token_counts = torch.cuda.LongTensor([0, 0, 0, 0, 0])

    # Broadcast num tokens.
    torch.distributed.broadcast(token_counts,
                                mpu.get_model_parallel_src_rank(),
                                group=mpu.get_model_parallel_group())
    num_tokens = token_counts[0].item()
    eod_token = token_counts[1].item()
    args.do_train = token_counts[2].item()
    args.do_valid = token_counts[3].item()
    args.do_test = token_counts[4].item()

149
    args.eod_token = eod_token
150

151
    return train_data, val_data, test_data
152
153
154


if __name__ == "__main__":
155

Mohammad's avatar
Mohammad committed
156
157
    pretrain(get_train_val_test_data, model_provider, forward_step,
             args_defaults={'tokenizer_type': 'GPT2BPETokenizer'})