gpt_model.py 4.55 KB
Newer Older
liangjing's avatar
v1  
liangjing committed
1
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
2
3
4
5
6

"""GPT-2 model."""

import torch

xingjinliang's avatar
xingjinliang committed
7
from megatron.training import get_args
8
from megatron.core import tensor_parallel
9
from .module import MegatronModule
10

11
from .enums import AttnMaskType
12
13
14
15
from .language_model import parallel_lm_logits
from .language_model import get_language_model


16
def post_language_model_processing(lm_output, labels, logit_weights,
17
                                   parallel_output,
18
19
                                   fp16_lm_cross_entropy):

Vijay Korthikanti's avatar
Vijay Korthikanti committed
20
    # Output. Format [s b h]
21
22
23
24
25
26
    output = parallel_lm_logits(
        lm_output,
        logit_weights,
        parallel_output)

    if labels is None:
Vijay Korthikanti's avatar
Vijay Korthikanti committed
27
28
        # [s b h] => [b s h]
        return output.transpose(0,1).contiguous()
29
    else:
Vijay Korthikanti's avatar
Vijay Korthikanti committed
30
31
        # [b s] => [s b]
        labels = labels.transpose(0,1).contiguous()
32
33
        if fp16_lm_cross_entropy:
            assert output.dtype == torch.half
34
            loss = tensor_parallel.vocab_parallel_cross_entropy(output, labels)
35
        else:
36
            loss = tensor_parallel.vocab_parallel_cross_entropy(output.float(), labels)
Vijay Korthikanti's avatar
Vijay Korthikanti committed
37
38
39
        
        # [s b] => [b, s]
        loss = loss.transpose(0,1).contiguous()
40
41
42
        return loss


43
class GPTModel(MegatronModule):
44
45
    """GPT-2 Language model."""

46
    def __init__(self,
liangjing's avatar
v1  
liangjing committed
47
                 config,
48
49
50
51
                 num_tokentypes=0,
                 parallel_output=True,
                 pre_process=True,
                 post_process=True):
Mohammad's avatar
Mohammad committed
52
        args = get_args()
liangjing's avatar
v1  
liangjing committed
53
        super().__init__(config=config, share_embeddings_and_output_weights=not args.untie_embeddings_and_output_weights)
54
55

        self.parallel_output = parallel_output
56
57
        self.pre_process = pre_process
        self.post_process = post_process
mohammad's avatar
mohammad committed
58
        self.fp16_lm_cross_entropy = args.fp16_lm_cross_entropy
59
        self.untie_embeddings_and_output_weights = args.untie_embeddings_and_output_weights
60
61

        self.language_model, self._language_model_key = get_language_model(
liangjing's avatar
v1  
liangjing committed
62
            config=config,
63
64
            num_tokentypes=num_tokentypes,
            add_pooler=False,
65
            encoder_attn_mask_type=AttnMaskType.causal,
66
67
            pre_process=self.pre_process,
            post_process=self.post_process)
68
69
        
        if not args.untie_embeddings_and_output_weights:
liangjing's avatar
v1  
liangjing committed
70
            self.initialize_word_embeddings()
71

72
    def set_input_tensor(self, input_tensor):
xingjinliang's avatar
xingjinliang committed
73
        """See megatron.legacy.model.transformer.set_input_tensor()"""
74
75
        self.language_model.set_input_tensor(input_tensor)

Lawrence McAfee's avatar
Retro  
Lawrence McAfee committed
76
    def forward(self, input_ids, position_ids, attention_mask,
liangjing's avatar
v1  
liangjing committed
77
78
79
                retriever_input_ids=None,
                retriever_position_ids=None,
                retriever_attn_mask=None,
Lawrence McAfee's avatar
Retro  
Lawrence McAfee committed
80
                labels=None, tokentype_ids=None, inference_params=None):
81

82
83
84
85
        lm_output = self.language_model(
            input_ids,
            position_ids,
            attention_mask,
liangjing's avatar
v1  
liangjing committed
86
87
88
            retriever_input_ids=retriever_input_ids,
            retriever_position_ids=retriever_position_ids,
            retriever_attn_mask=retriever_attn_mask,
mshoeybi's avatar
mshoeybi committed
89
            inference_params=inference_params)
90

91
        if self.post_process:
92
93
            return post_language_model_processing(
                lm_output, labels,
liangjing's avatar
v1  
liangjing committed
94
                self.language_model.output_layer.weight if self.untie_embeddings_and_output_weights else self.shared_embedding_or_output_weight(),
95
96
97
98
                self.parallel_output,
                self.fp16_lm_cross_entropy)
        else:
            return lm_output
99

100
    def state_dict_for_save_checkpoint(self, prefix='', keep_vars=False):
101
102
103
104

        state_dict_ = {}
        state_dict_[self._language_model_key] \
            = self.language_model.state_dict_for_save_checkpoint(
105
                prefix=prefix, keep_vars=keep_vars)
106
        # Save word_embeddings.
107
        if self.post_process and not self.pre_process and not self.untie_embeddings_and_output_weights:
108
            state_dict_[self._word_embeddings_for_head_key] \
109
110
                = self.word_embeddings.state_dict(prefix=prefix,
                                                  keep_vars=keep_vars)
111
112
113
114
115
        return state_dict_

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

116
        # Load word_embeddings.
117
        if self.post_process and not self.pre_process and not self.untie_embeddings_and_output_weights:
118
119
            self.word_embeddings.load_state_dict(
                state_dict[self._word_embeddings_for_head_key], strict=strict)
120
121
122
        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)