classification.py 4.73 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
16
17
18
19
#
# 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.

"""Classification model."""

import torch

20
from megatron import get_args, print_rank_last
21
from megatron import mpu
22
from megatron.model.enums import AttnMaskType
23
from megatron.model.bert_model import bert_extended_attention_mask, bert_position_ids
24
25
26
27
from megatron.model.language_model import get_language_model
from megatron.model.utils import get_linear_layer
from megatron.model.utils import init_method_normal
from megatron.model.utils import scaled_init_method_normal
28
from .module import MegatronModule
29
30


31
32
class Classification(MegatronModule):

33
34
    def __init__(self,
                 num_classes,
35
36
37
38
                 num_tokentypes=2,
                 pre_process=True,
                 post_process=True):
        super(Classification, self).__init__(share_word_embeddings=False)
Mohammad's avatar
Mohammad committed
39
        args = get_args()
40
41

        self.num_classes = num_classes
42
43
        self.pre_process = pre_process
        self.post_process = post_process
Mohammad's avatar
Mohammad committed
44
        init_method = init_method_normal(args.init_method_std)
45
46
47
48

        self.language_model, self._language_model_key = get_language_model(
            num_tokentypes=num_tokentypes,
            add_pooler=True,
49
            encoder_attn_mask_type=AttnMaskType.padding,
50
            init_method=init_method,
Mohammad's avatar
Mohammad committed
51
            scaled_init_method=scaled_init_method_normal(args.init_method_std,
52
53
54
                                                         args.num_layers),
            pre_process=self.pre_process,
            post_process=self.post_process)
55
56

        # Multi-choice head.
57
        if self.post_process:
58
59
60
61
62
            self.classification_dropout = torch.nn.Dropout(args.hidden_dropout)
            self.classification_head = get_linear_layer(args.hidden_size,
                                                        self.num_classes,
                                                        init_method)
            self._classification_head_key = 'classification_head'
63

64
    def set_input_tensor(self, input_tensor):
65
        """See megatron.model.transformer.set_input_tensor()"""
66
67
        self.language_model.set_input_tensor(input_tensor)

68
    def forward(self, model_input, attention_mask, tokentype_ids=None):
69

70
        extended_attention_mask = bert_extended_attention_mask(attention_mask)
71
72
73
74
75
76
77
78
79
        input_ids = model_input
        position_ids = bert_position_ids(input_ids)

        lm_output = self.language_model(
            input_ids,
            position_ids,
            extended_attention_mask,
            tokentype_ids=tokentype_ids
        )
80

81
        if self.post_process:
82
83
84
            _, pooled_output = lm_output
            classification_output = self.classification_dropout(pooled_output)
            classification_logits = self.classification_head(classification_output)
85

86
87
            # Reshape back to separate choices.
            classification_logits = classification_logits.view(-1, self.num_classes)
88

89
90
            return classification_logits
        return lm_output
91
92
93
94
95
96
97
98
99
100

    def state_dict_for_save_checkpoint(self, destination=None, prefix='',
                                       keep_vars=False):
        """For easy load when model is combined with other heads,
        add an extra key."""

        state_dict_ = {}
        state_dict_[self._language_model_key] \
            = self.language_model.state_dict_for_save_checkpoint(
                destination, prefix, keep_vars)
101
        if self.post_process:
102
103
104
            state_dict_[self._classification_head_key] \
                = self.classification_head.state_dict(
                    destination, prefix, keep_vars)
105
106
107
108
109
110
111
        return state_dict_

    def load_state_dict(self, state_dict, strict=True):
        """Customized load."""

        self.language_model.load_state_dict(
            state_dict[self._language_model_key], strict=strict)
112
        if self.post_process:
113
114
115
116
117
118
119
            if self._classification_head_key in state_dict:
                self.classification_head.load_state_dict(
                    state_dict[self._classification_head_key], strict=strict)
            else:
                print_rank_last('***WARNING*** could not find {} in the checkpoint, '
                                'initializing to random'.format(
                                    self._classification_head_key))