pretrain_bert.py 5.09 KB
Newer Older
Raul Puri's avatar
Raul Puri committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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 BERT"""

import torch
19
import torch.nn.functional as F
Raul Puri's avatar
Raul Puri committed
20
21

from configure_data import configure_data
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
22
from megatron import mpu
23
from megatron.model import BertModel
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
24
from megatron.utils import print_rank_0
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
25
from megatron.utils import reduce_losses
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
26
from megatron.utils import vocab_size_with_padding
27
28
from megatron.training import run

Raul Puri's avatar
Raul Puri committed
29

30
def model_provider(args):
Raul Puri's avatar
Raul Puri committed
31
32
    """Build the model."""

33
    print_rank_0('building BERT model ...')
Raul Puri's avatar
Raul Puri committed
34

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    model = BertModel(
        num_layers=args.num_layers,
        vocab_size=args.vocab_size,
        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,
        add_binary_head=True,
        layernorm_epsilon=args.layernorm_epsilon,
        num_tokentypes=args.tokentype_size,
        parallel_output=True)
Raul Puri's avatar
Raul Puri committed
50

51
    return model
Raul Puri's avatar
Raul Puri committed
52
53


54
def get_batch(data_iterator, timers):
55

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    # Items and their type.
    keys = ['text', 'types', 'is_random', 'mask', 'mask_labels', 'pad_mask']
    datatype = torch.int64

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

    # Unpack.
    tokens = data_b['text'].long()
    types = data_b['types'].long()
    next_sentence = data_b['is_random'].long()
    loss_mask = data_b['mask'].float()
    lm_labels = data_b['mask_labels'].long()
    padding_mask = data_b['pad_mask'].byte()
Raul Puri's avatar
Raul Puri committed
76
77
78
79

    return tokens, types, next_sentence, loss_mask, lm_labels, padding_mask


80
def forward_step(data_iterator, model, args, timers):
Raul Puri's avatar
Raul Puri committed
81
82
83
    """Forward step."""

    # Get the batch.
84
    timers('batch generator').start()
85
86
    tokens, types, next_sentence, loss_mask, lm_labels, padding_mask \
        = get_batch(data_iterator, timers)
87
    timers('batch generator').stop()
88

Raul Puri's avatar
Raul Puri committed
89
    # Forward model.
90
    lm_logits, nsp_logits = model(tokens, 1-padding_mask, tokentype_ids=types)
91

92
    nsp_loss = F.cross_entropy(nsp_logits.view(-1, 2).contiguous().float(),
93
94
95
                               next_sentence.view(-1).contiguous(),
                               ignore_index=-1)

96
97
    lm_loss_ = mpu.vocab_parallel_cross_entropy(lm_logits.contiguous().float(),
                                                lm_labels.contiguous())
Raul Puri's avatar
Raul Puri committed
98
    lm_loss = torch.sum(
99
        lm_loss_.view(-1) * loss_mask.reshape(-1)) / loss_mask.sum()
Raul Puri's avatar
Raul Puri committed
100
101
102

    loss = lm_loss + nsp_loss

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
103
    reduced_losses = reduce_losses([lm_loss, nsp_loss])
Raul Puri's avatar
Raul Puri committed
104

Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
105
    return loss, {'lm loss': reduced_losses[0], 'nsp loss': reduced_losses[1]}
106
107
108
109
110
111
112
113
114
115


def get_train_val_test_data(args):
    """Load the data on rank zero and boradcast number of tokens to all GPUS."""

    (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:
        data_config = configure_data()
116
117
        ds_type = 'BERT'
        data_config.set_defaults(data_set_type=ds_type, transpose=False)
118
        (train_data, val_data, test_data), tokenizer = data_config.apply(args)
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
119
        num_tokens = vocab_size_with_padding(tokenizer.num_tokens, args)
120
        # Need to broadcast num_tokens and num_type_tokens.
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
121
        token_counts = torch.cuda.LongTensor([num_tokens,
122
                                              tokenizer.num_type_tokens,
Mohammad Shoeybi's avatar
Mohammad Shoeybi committed
123
124
125
                                              int(args.do_train),
                                              int(args.do_valid),
                                              int(args.do_test)])
126
127
128
129
130
131
132
133
134
135
136
137
138
    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()
    num_type_tokens = 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()

139
140
    args.vocab_size = num_tokens
    args.tokentype_size = num_type_tokens
141

142
    return train_data, val_data, test_data
Raul Puri's avatar
Raul Puri committed
143
144
145


if __name__ == "__main__":
146
147
148

    run('Pretrain BERT model', get_train_val_test_data,
        model_provider, forward_step)