gpt2_model.py 3.57 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.

"""GPT-2 model."""

import torch

Mohammad's avatar
Mohammad committed
20
from megatron import get_args
21
22
23
24
25
26
27
from megatron.module import MegatronModule

from .language_model import parallel_lm_logits
from .language_model import get_language_model
from .utils import init_method_normal
from .utils import scaled_init_method_normal

mohammad's avatar
testing  
mohammad committed
28
29
30
from megatron.utils import report_memory
from megatron import mpu

31
32

def gpt2_attention_mask_func(attention_scores, ltor_mask):
33
    attention_scores.masked_fill_(ltor_mask, -10000.0)
34
35
36
37
38
39
    return attention_scores


class GPT2Model(MegatronModule):
    """GPT-2 Language model."""

Mohammad's avatar
Mohammad committed
40
    def __init__(self, num_tokentypes=0, parallel_output=True):
41
        super(GPT2Model, self).__init__()
Mohammad's avatar
Mohammad committed
42
        args = get_args()
43
44
45
46

        self.parallel_output = parallel_output

        self.language_model, self._language_model_key = get_language_model(
Mohammad's avatar
Mohammad committed
47
            attention_mask_func=gpt2_attention_mask_func,
48
49
            num_tokentypes=num_tokentypes,
            add_pooler=False,
Mohammad's avatar
Mohammad committed
50
51
52
            init_method=init_method_normal(args.init_method_std),
            scaled_init_method=scaled_init_method_normal(args.init_method_std,
                                                         args.num_layers))
53

mohammad's avatar
testing  
mohammad committed
54
    def forward(self, input_ids, position_ids, attention_mask, labels,
55
56
                tokentype_ids=None, layer_past=None, get_key_value=False,
                forward_method_parallel_output=None):
57
58
59
60
61
62
63
64
65
66
67
68
69

        # Language model.
        lm_output = self.language_model(input_ids,
                                        position_ids,
                                        attention_mask,
                                        tokentype_ids=tokentype_ids,
                                        layer_past=layer_past,
                                        get_key_value=get_key_value)

        if get_key_value:
            lm_output, presents = lm_output

        # Output.
70
71
72
        parallel_output = self.parallel_output
        if forward_method_parallel_output is not None:
            parallel_output = forward_method_parallel_output
73
74
75
        output = parallel_lm_logits(
            lm_output,
            self.language_model.embedding.word_embeddings.weight,
76
            parallel_output)
77
78
79
80

        if get_key_value:
            output = [output, presents]

mohammad's avatar
testing  
mohammad committed
81
82
83
84
85
86
87
88
        #report_memory('AAA')

        losses = mpu.vocab_parallel_cross_entropy(output, labels)

        #report_memory('BBB')

        #return output
        return losses
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

    def state_dict_for_save_checkpoint(self, destination=None, prefix='',
                                       keep_vars=False):

        state_dict_ = {}
        state_dict_[self._language_model_key] \
            = self.language_model.state_dict_for_save_checkpoint(
                destination, prefix, keep_vars)
        return state_dict_

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

        if self._language_model_key in state_dict:
            state_dict = state_dict[self._language_model_key]
        self.language_model.load_state_dict(state_dict, strict=strict)