pretrain_bert_ict.py 5.99 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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 for Inverse Cloze Task"""

import torch
import torch.nn.functional as F

from configure_data import configure_data
from megatron import mpu
23
from megatron.model import ICTBertModel
24
25
26
27
28
from megatron.utils import print_rank_0
from megatron.utils import reduce_losses
from megatron.utils import vocab_size_with_padding
from megatron.training import run

Neel Kant's avatar
Neel Kant committed
29
num_batches = 0
30
31
32
33

def model_provider(args):
    """Build the model."""

34
    print_rank_0('building BERT models ...')
35

36
    model = ICTBertModel(
37
38
39
40
41
42
43
44
45
        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,
46
        ict_head_size=128,
47
48
49
50
51
52
53
54
55
56
57
58
59
        checkpoint_num_layers=args.checkpoint_num_layers,
        layernorm_epsilon=args.layernorm_epsilon,
        num_tokentypes=args.tokentype_size,
        parallel_output=True,
        apply_query_key_layer_scaling=args.apply_query_key_layer_scaling,
        attention_softmax_in_fp32=args.attention_softmax_in_fp32)

    return model


def get_batch(data_iterator, timers):

    # Items and their type.
60
61
    keys = ['input_text', 'input_types', 'input_pad_mask',
            'context_text', 'context_types', 'context_pad_mask']
62
63
64
65
    datatype = torch.int64

    # Broadcast data.
    timers('data loader').start()
66
    if data_iterator is None:
67
        data = None
68
69
70
    else:
        data = next(data_iterator)

71
72
73
74
    timers('data loader').stop()
    data_b = mpu.broadcast_data(keys, data, datatype)

    # Unpack.
75
76
77
78
79
80
    input_tokens = data_b['input_text'].long()
    input_types = data_b['input_types'].long()
    input_pad_mask = data_b['input_pad_mask'].long()
    context_tokens = data_b['context_text'].long()
    context_types = data_b['context_types'].long()
    context_pad_mask = data_b['context_pad_mask'].long()
81

82
83
    return input_tokens, input_types, input_pad_mask,\
           context_tokens, context_types, context_pad_mask
84
85
86
87
88
89
90


def forward_step(data_iterator, model, args, timers):
    """Forward step."""

    # Get the batch.
    timers('batch generator').start()
91
92
    input_tokens, input_types, input_pad_mask,\
    context_tokens, context_types, context_pad_mask = get_batch(data_iterator, timers)
93
94
95
    timers('batch generator').stop()

    # Forward model.
96
97
98
    # TODO: important to make sure that everything, including padding mask is as expected here.
    retrieval_scores = model(input_tokens, input_pad_mask, input_types,
                             context_tokens, context_pad_mask, context_types).float()
99

100
101
102
    softmaxed = F.softmax(retrieval_scores, dim=1)
    top5_vals, top5_indices = torch.topk(softmaxed, k=5, sorted=True)
    batch_size = softmaxed.shape[0]
103

104
105
106
107
108
109
110
111
112
    top1_acc = torch.cuda.FloatTensor([sum([int(top5_indices[i, 0] == i) for i in range(batch_size)]) / batch_size])
    top5_acc = torch.cuda.FloatTensor([sum([int(i in top5_indices[i]) for i in range(batch_size)]) / batch_size])

    retrieval_loss = F.cross_entropy(softmaxed, torch.arange(batch_size).cuda())
    reduced_losses = reduce_losses([retrieval_loss, top1_acc, top5_acc])

    return retrieval_loss, {'retrieval loss': reduced_losses[0],
                            'top1_acc': reduced_losses[1],
                            'top5_acc': reduced_losses[2]}
113
114
115
116
117
118
119
120
121
122
123
124
125


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:
        if (args.data_loader == 'raw'
                or args.data_loader == 'lazy'
                or args.data_loader == 'tfrecords'):
            data_config = configure_data()
126
            ds_type = 'BERT_ict'
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
            data_config.set_defaults(data_set_type=ds_type, transpose=False)
            (train_data, val_data, test_data), tokenizer = data_config.apply(args)
            num_tokens = vocab_size_with_padding(tokenizer.num_tokens, args)
            # Need to broadcast num_tokens and num_type_tokens.
            token_counts = torch.cuda.LongTensor([num_tokens,
                                                  tokenizer.num_type_tokens,
                                                  int(args.do_train),
                                                  int(args.do_valid),
                                                  int(args.do_test)])
        else:
            print("Unsupported data loader for BERT.")
            exit(1)
    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()

    args.vocab_size = num_tokens
    args.tokentype_size = num_type_tokens

    return train_data, val_data, test_data


if __name__ == "__main__":

160
    run('Pretrain ICT BERT model', get_train_val_test_data,
161
        model_provider, forward_step)