Shaltiel commited on
Commit
732043d
1 Parent(s): 1b8a347

Upload 2 files

Browse files
configuration_megatron_gpt.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementation in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Nemo Framework
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ MegatronGPT model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ class MegatronGPTConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`MegatronGPTModel`]. It is used to instantiate an
31
+ MegatronGPT model according to the specified arguments, defining the model architecture. Instantiating a configuration
32
+ with the defaults will yield a similar configuration to that of the MegatronGPT 1.4B parameter architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 50432):
39
+ Vocabulary size of the MegatronGPT model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`MegatronGPTModel`].
41
+ hidden_size (`int`, *optional*, defaults to 6144):
42
+ Dimension of the encoder layers and the pooler layer.
43
+ num_hidden_layers (`int`, *optional*, defaults to 44):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 64):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ intermediate_size (`int`, *optional*, defaults to 24576):
48
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
49
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
50
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
51
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
52
+ bias (`bool`, *optional*, defaults to True)
53
+ Whether or not to include a bias in every linear layer
54
+ rotary_pct (`float`, *optional*, defaults to 0.25):
55
+ percentage of hidden dimensions to allocate to rotary embeddings
56
+ rotary_emb_base (`int`, *optional*, defaults to 10000)
57
+ base for computing rotary embeddings frequency
58
+ attention_dropout (`float`, *optional*, defaults to 0.0):
59
+ The dropout ratio probability of the attention score.
60
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio of (1) the word embeddings, (2) the post-attention hidden states, and (3) the post-mlp
62
+ hidden states.
63
+ classifier_dropout (`float`, *optional*, defaults to 0.1):
64
+ Argument used when doing token classification, used in the model [`MegatronGPTForTokenClassification`].
65
+ The dropout ratio for the hidden layer.
66
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
67
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
68
+ just in case (e.g., 512 or 1024 or 2048).
69
+ normalize_attention_scores (`bool`, *optional*, defaults to `True`)
70
+ Whether to scale the output Q * K^T by 1 / sqrt(hidden_size_per_head).
71
+ initializer_range (`float`, *optional*, defaults to 1e-5):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
74
+ The epsilon used by the layer normalization layers.
75
+ normalization (`string`, *optional*, defaults to `layernorm1p`)
76
+ The type of normalization to use for the LayerNorm layers, either `layernorm` or `layernorm1p`
77
+ use_cache (`bool`, *optional*, defaults to `True`):
78
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
79
+ relevant if `config.is_decoder=True`.
80
+ self_attention_relative_position_bias (`bool`, *optional*, defaults to `True`):
81
+ Whether to calculate and apply the relative position bias within the attention function.
82
+ If this is False, then model.generate will require you to calculate the triangular attention
83
+ mask and pass it through in the attention mask.
84
+ rope_scaling (`Dict`, *optional*):
85
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports three scaling
86
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
87
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
88
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
89
+ these scaling strategies behave:
90
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
91
+ experimental feature, subject to breaking API changes in future versions.
92
+
93
+ """
94
+ model_type = "megatron_gpt"
95
+
96
+ def __init__(
97
+ self,
98
+ vocab_size=56064,
99
+ hidden_size=2048,
100
+ num_hidden_layers=24,
101
+ num_attention_heads=16,
102
+ intermediate_size=5440,
103
+ hidden_act="fast-swiglu",
104
+ bias=True,
105
+ rotary_pct=0.5,
106
+ rotary_emb_base=10000,
107
+ attention_dropout=0.0,
108
+ hidden_dropout=0.0,
109
+ classifier_dropout=0.0,
110
+ normalize_attention_scores=True,
111
+ max_position_embeddings=2048,
112
+ initializer_range=0.01,
113
+ layer_norm_eps=1e-5,
114
+ normalization='layernorm1p',
115
+ use_cache=True,
116
+ self_attention_relative_position_bias=True,
117
+ bos_token_id=0,
118
+ eos_token_id=2,
119
+ tie_word_embeddings=False,
120
+ rope_scaling=None,
121
+ **kwargs,
122
+ ):
123
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
124
+ self.vocab_size = vocab_size
125
+ self.max_position_embeddings = max_position_embeddings
126
+ self.hidden_size = hidden_size
127
+ self.num_hidden_layers = num_hidden_layers
128
+ self.num_attention_heads = num_attention_heads
129
+ self.intermediate_size = intermediate_size
130
+ self.hidden_act = hidden_act
131
+ self.bias = bias
132
+ self.rotary_pct = rotary_pct
133
+ self.rotary_emb_base = rotary_emb_base
134
+ self.attention_dropout = attention_dropout
135
+ self.hidden_dropout = hidden_dropout
136
+ self.classifier_dropout = classifier_dropout
137
+ self.normalize_attention_scores = normalize_attention_scores
138
+ self.initializer_range = initializer_range
139
+ self.layer_norm_eps = layer_norm_eps
140
+ self.normalization = normalization
141
+ self.use_cache = use_cache
142
+ self.self_attention_relative_position_bias = self_attention_relative_position_bias
143
+ self.tie_word_embeddings = tie_word_embeddings
144
+ self.rope_scaling = rope_scaling
145
+ self._rope_scaling_validation()
146
+
147
+ if self.hidden_size % self.num_attention_heads != 0:
148
+ raise ValueError(
149
+ "The hidden size is not divisble by the number of attention heads! Make sure to update them!"
150
+ )
151
+
152
+ # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
153
+ def _rope_scaling_validation(self):
154
+ """
155
+ Validate the `rope_scaling` configuration.
156
+ """
157
+ if self.rope_scaling is None:
158
+ return
159
+
160
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
161
+ raise ValueError(
162
+ "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
163
+ f"got {self.rope_scaling}"
164
+ )
165
+ rope_scaling_type = self.rope_scaling.get("type", None)
166
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
167
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
168
+ raise ValueError(
169
+ f"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
170
+ )
171
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
172
+ raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
modeling_megatron_gpt.py ADDED
@@ -0,0 +1,1146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementation in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Nemo Framework
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ """ PyTorch MegatronGPT model."""
22
+
23
+ from typing import Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.file_utils import (
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ replace_return_docstrings,
35
+ )
36
+ from transformers.modeling_outputs import (
37
+ BaseModelOutputWithPast,
38
+ CausalLMOutputWithPast,
39
+ QuestionAnsweringModelOutput,
40
+ SequenceClassifierOutputWithPast,
41
+ TokenClassifierOutput,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.utils import logging
45
+ # try to load using a relative path, but if it fails try loading it directly
46
+ try:
47
+ from .configuration_megatron_gpt import MegatronGPTConfig
48
+ except:
49
+ from configuration_megatron_gpt import MegatronGPTConfig
50
+
51
+
52
+ def get_activation(act):
53
+ if act in ["gelu", "geglu", "fast-geglu"]:
54
+ act = 'gelu'
55
+ elif act in ["reglu", "fast-reglu"]:
56
+ act = 'relu'
57
+ elif act in ["swiglu", "fast-swiglu"]:
58
+ act = 'silu'
59
+ return ACT2FN[act]
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CONFIG_FOR_DOC = "MegatronGPTConfig"
64
+
65
+ class MegatronGPTPreTrainedModel(PreTrainedModel):
66
+ """
67
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
68
+ models.
69
+ """
70
+
71
+ config_class = MegatronGPTConfig
72
+ base_model_prefix = "megatron_gpt"
73
+ supports_gradient_checkpointing = True
74
+ _no_split_modules = ["MegatronGPTLayer"]
75
+ _skip_keys_device_placement = "past_key_values"
76
+
77
+ def _init_weights(self, module):
78
+ """Initialize the weights"""
79
+ if isinstance(module, nn.Linear):
80
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
81
+ if module.bias is not None:
82
+ module.bias.data.zero_()
83
+ elif isinstance(module, nn.Embedding):
84
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
85
+ if module.padding_idx is not None:
86
+ module.weight.data[module.padding_idx].zero_()
87
+ elif isinstance(module, nn.LayerNorm):
88
+ module.bias.data.zero_()
89
+ module.weight.data.fill_(1.0)
90
+
91
+ def _set_gradient_checkpointing(self, module, value=False):
92
+ if isinstance(module, MegatronGPTModel):
93
+ module.gradient_checkpointing = value
94
+
95
+
96
+ class MegatronGPTAttention(nn.Module):
97
+ def __init__(self, config):
98
+ super().__init__()
99
+ self.config = config
100
+ self.self_attention_relative_position_bias = config.self_attention_relative_position_bias
101
+ self.num_attention_heads = config.num_attention_heads
102
+ self.hidden_size = config.hidden_size
103
+ if self.hidden_size % self.num_attention_heads != 0:
104
+ raise ValueError(
105
+ "The hidden size is not divisble by the number of attention heads! Make sure to update them"
106
+ )
107
+ self.head_size = self.hidden_size // self.num_attention_heads
108
+ self.rotary_ndims = int(self.head_size * config.rotary_pct)
109
+ self._init_bias(config.max_position_embeddings)
110
+
111
+ self.register_buffer("masked_bias", torch.tensor(-1e9), persistent=False)
112
+ self._init_rope()
113
+
114
+ self.register_buffer(
115
+ "norm_factor",
116
+ torch.sqrt(torch.tensor(self.head_size if config.normalize_attention_scores else 1.0, dtype=torch.float32)).to(torch.get_default_dtype()),
117
+ persistent=False,
118
+ )
119
+ self.query_key_value = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=config.bias)
120
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=config.bias)
121
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
122
+
123
+ def _init_bias(self, max_positions, device=None):
124
+ self.register_buffer(
125
+ "bias",
126
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
127
+ 1, 1, max_positions, max_positions
128
+ ),
129
+ persistent=False,
130
+ )
131
+ if device is not None:
132
+ self.bias = self.bias.to(device)
133
+
134
+ def _init_rope(self):
135
+ if self.config.rope_scaling is None:
136
+ self.rotary_emb = MegatronGPTRotaryEmbedding(
137
+ self.rotary_ndims, self.config.max_position_embeddings, base=self.config.rotary_emb_base
138
+ )
139
+ else:
140
+ scaling_type = self.config.rope_scaling["type"]
141
+ scaling_factor = self.config.rope_scaling["factor"]
142
+ if scaling_type == "linear":
143
+ self.rotary_emb = MegatronGPTLinearScalingRotaryEmbedding(
144
+ self.rotary_ndims,
145
+ self.config.max_position_embeddings,
146
+ base=self.config.rotary_emb_base,
147
+ scaling_factor=scaling_factor,
148
+ )
149
+ elif scaling_type == "dynamic":
150
+ self.rotary_emb = MegatronGPTDynamicNTKScalingRotaryEmbedding(
151
+ self.rotary_ndims,
152
+ self.config.max_position_embeddings,
153
+ base=self.config.rotary_emb_base,
154
+ scaling_factor=scaling_factor,
155
+ )
156
+ else:
157
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
158
+
159
+ def forward(
160
+ self,
161
+ hidden_states: torch.FloatTensor,
162
+ attention_mask: torch.FloatTensor,
163
+ position_ids: torch.LongTensor,
164
+ head_mask: Optional[torch.FloatTensor] = None,
165
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
166
+ use_cache: Optional[bool] = False,
167
+ output_attentions: Optional[bool] = False,
168
+ ):
169
+ has_layer_past = layer_past is not None
170
+
171
+ # Compute QKV
172
+ # Attention heads [batch, seq_len, hidden_size]
173
+ # --> [batch, seq_len, (np * 3 * head_size)]
174
+ qkv = self.query_key_value(hidden_states)
175
+
176
+ # [batch, seq_len, (num_heads * 3 * head_size)]
177
+ # --> [batch, seq_len, num_heads, 3 * head_size]
178
+ new_qkv_shape = qkv.size()[:-1] + (self.num_attention_heads, 3 * self.head_size)
179
+ qkv = qkv.view(*new_qkv_shape)
180
+
181
+ # [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size]
182
+ query = qkv[..., : self.head_size].permute(0, 2, 1, 3)
183
+ key = qkv[..., self.head_size : 2 * self.head_size].permute(0, 2, 1, 3)
184
+ value = qkv[..., 2 * self.head_size :].permute(0, 2, 1, 3)
185
+
186
+ # Compute rotary embeddings on rotary_ndims
187
+ query_rot = query[..., : self.rotary_ndims]
188
+ query_pass = query[..., self.rotary_ndims :]
189
+ key_rot = key[..., : self.rotary_ndims]
190
+ key_pass = key[..., self.rotary_ndims :]
191
+
192
+ # Compute token offset for rotary embeddings (when decoding)
193
+ seq_len = key.shape[-2]
194
+ if has_layer_past:
195
+ seq_len += layer_past[0].shape[-2]
196
+ cos, sin = self.rotary_emb(value, seq_len=seq_len)
197
+ query, key = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
198
+ query = torch.cat((query, query_pass), dim=-1)
199
+ key = torch.cat((key, key_pass), dim=-1)
200
+
201
+ # Cache QKV values
202
+ if has_layer_past:
203
+ past_key = layer_past[0]
204
+ past_value = layer_past[1]
205
+ key = torch.cat((past_key, key), dim=-2)
206
+ value = torch.cat((past_value, value), dim=-2)
207
+ present = (key, value) if use_cache else None
208
+
209
+ # Compute attention
210
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
211
+
212
+ # Reshape outputs
213
+ attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_size)
214
+ attn_output = self.dense(attn_output)
215
+
216
+ outputs = (attn_output, present)
217
+ if output_attentions:
218
+ outputs += (attn_weights,)
219
+
220
+ return outputs
221
+
222
+ @classmethod
223
+ def _split_heads(cls, tensor, num_attention_heads, attn_head_size):
224
+ """
225
+ Splits hidden dim into attn_head_size and num_attention_heads
226
+ """
227
+ # tensor: [bs, seq_len, hidden_size]
228
+ new_shape = tensor.size()[:-1] + (num_attention_heads, attn_head_size)
229
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
230
+ tensor = tensor.view(new_shape)
231
+ # -> [bs, num_attention_heads, seq_len, attn_head_size]
232
+ tensor = tensor.permute(0, 2, 1, 3)
233
+ return tensor
234
+
235
+ @classmethod
236
+ def _merge_heads(cls, tensor, num_attention_heads, attn_head_size):
237
+ """
238
+ Merges attn_head_size dim and num_attn_heads dim into hidden dim
239
+ """
240
+ # tensor [bs, num_attention_heads, seq_len, attn_head_size]
241
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
242
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
243
+ tensor = tensor.view(tensor.size(0), tensor.size(1), num_attention_heads * attn_head_size)
244
+ # -> [bs, seq_len, hidden_size]
245
+ return tensor
246
+
247
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
248
+ # q, k, v: [bs, num_attention_heads, seq_len, attn_head_size]
249
+ # compute causal mask from causal mask buffer
250
+ batch_size, num_attention_heads, query_length, attn_head_size = query.size()
251
+ key_length = key.size(-2)
252
+
253
+ # dynamically increase the causal mask with the key length, if needed.
254
+ if key_length > self.bias.shape[-1]:
255
+ self._init_bias(key_length, device=key.device)
256
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
257
+
258
+ query = query.view(batch_size * num_attention_heads, query_length, attn_head_size)
259
+ key = key.view(batch_size * num_attention_heads, key_length, attn_head_size)
260
+ attn_scores = torch.zeros(
261
+ batch_size * num_attention_heads,
262
+ query_length,
263
+ key_length,
264
+ dtype=query.dtype,
265
+ device=key.device,
266
+ )
267
+ attn_scores = torch.baddbmm(
268
+ attn_scores,
269
+ query,
270
+ key.transpose(1, 2),
271
+ beta=0.0,
272
+ alpha=(torch.tensor(1.0, dtype=self.norm_factor.dtype, device=self.norm_factor.device) / self.norm_factor),
273
+ )
274
+ attn_scores = attn_scores.view(batch_size, num_attention_heads, query_length, key_length)
275
+
276
+ if self.self_attention_relative_position_bias:
277
+ mask_value = torch.finfo(attn_scores.dtype).min
278
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
279
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
280
+ mask_value = torch.tensor(mask_value, dtype=attn_scores.dtype).to(attn_scores.device)
281
+ attn_scores = torch.where(causal_mask, attn_scores, mask_value)
282
+
283
+ if attention_mask is not None:
284
+ # Apply the attention mask
285
+ attn_scores = attn_scores + attention_mask
286
+
287
+ attn_weights = nn.functional.softmax(attn_scores, dim=-1)
288
+ attn_weights = attn_weights.to(value.dtype)
289
+
290
+ # Mask heads if we want to
291
+ if head_mask is not None:
292
+ attn_weights = attn_weights * head_mask
293
+
294
+ attn_weights = self.attention_dropout(attn_weights)
295
+
296
+ attn_output = torch.matmul(attn_weights, value)
297
+ return attn_output, attn_weights
298
+
299
+
300
+ def attention_mask_func(attention_scores, ltor_mask):
301
+ attention_scores.masked_fill_(~ltor_mask, torch.finfo(attention_scores.dtype).min)
302
+ return attention_scores
303
+
304
+
305
+ class MegatronGPTRotaryEmbedding(torch.nn.Module):
306
+ def __init__(self, dim, max_position_embeddings, base=10000, device=None):
307
+ super().__init__()
308
+
309
+ self.dim = dim
310
+ self.max_position_embeddings = max_position_embeddings
311
+ self.base = base
312
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
313
+ self.register_buffer("inv_freq", inv_freq)
314
+
315
+ # Build here to make `torch.jit.trace` work.
316
+ self._set_cos_sin_cache(seq_len=max_position_embeddings, device=self.inv_freq.device)
317
+
318
+ def _set_cos_sin_cache(self, seq_len, device):
319
+ self.max_seq_len_cached = seq_len
320
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
321
+
322
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
323
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
324
+ emb = torch.cat((freqs, freqs), dim=-1)
325
+ self.cos_cached = emb.cos()[None, None, :, :]
326
+ self.sin_cached = emb.sin()[None, None, :, :]
327
+
328
+ def forward(self, x, seq_len=None):
329
+ # x: [bs, num_attention_heads, seq_len, head_size]
330
+ if seq_len > self.max_seq_len_cached:
331
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device)
332
+ return self.cos_cached[:seq_len, ...].to(x.device), self.sin_cached[:seq_len, ...].to(x.device)
333
+
334
+
335
+ class MegatronGPTLinearScalingRotaryEmbedding(MegatronGPTRotaryEmbedding):
336
+ """MegatronGPTRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
337
+
338
+ def __init__(self, dim, max_position_embeddings, base=10000, device=None, scaling_factor=1.0):
339
+ self.scaling_factor = scaling_factor
340
+ super().__init__(dim, max_position_embeddings, base, device)
341
+
342
+ def _set_cos_sin_cache(self, seq_len, device):
343
+ self.max_seq_len_cached = seq_len
344
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
345
+ t = t / self.scaling_factor
346
+
347
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
348
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
349
+ emb = torch.cat((freqs, freqs), dim=-1)
350
+ self.cos_cached = emb.cos()[None, None, :, :]
351
+ self.sin_cached = emb.sin()[None, None, :, :]
352
+
353
+
354
+ class MegatronGPTDynamicNTKScalingRotaryEmbedding(MegatronGPTRotaryEmbedding):
355
+ """MegatronGPTRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
356
+
357
+ def __init__(self, dim, max_position_embeddings, base=10000, device=None, scaling_factor=1.0):
358
+ self.scaling_factor = scaling_factor
359
+ super().__init__(dim, max_position_embeddings, base, device)
360
+
361
+ def _set_cos_sin_cache(self, seq_len, device):
362
+ self.max_seq_len_cached = seq_len
363
+
364
+ if seq_len > self.max_position_embeddings:
365
+ base = self.base * (
366
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
367
+ ) ** (self.dim / (self.dim - 2))
368
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
369
+ self.register_buffer("inv_freq", inv_freq)
370
+
371
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
372
+
373
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
374
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
375
+ emb = torch.cat((freqs, freqs), dim=-1)
376
+ self.cos_cached = emb.cos()[None, None, :, :]
377
+ self.sin_cached = emb.sin()[None, None, :, :]
378
+
379
+
380
+ def rotate_half(x):
381
+ """Rotates half the hidden dims of the input."""
382
+ x1 = x[..., : x.shape[-1] // 2]
383
+ x2 = x[..., x.shape[-1] // 2 :]
384
+ return torch.cat((-x2, x1), dim=-1)
385
+
386
+
387
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
388
+ gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1]
389
+ gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3])
390
+ cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
391
+ sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
392
+ q_embed = (q * cos) + (rotate_half(q) * sin)
393
+ k_embed = (k * cos) + (rotate_half(k) * sin)
394
+ return q_embed, k_embed
395
+
396
+
397
+ class MegatronGPTMLP(nn.Module):
398
+ def __init__(self, config):
399
+ super().__init__()
400
+ self.fast_glu_activation = config.hidden_act in ['fast-geglu', 'fast-swiglu', 'fast-reglu']
401
+ self.glu_activation_family = self.fast_glu_activation or config.hidden_act in ['geglu','reglu','swiglu']
402
+
403
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size * (2 if self.fast_glu_activation else 1), bias=config.bias)
404
+ if config.hidden_act in ['geglu', 'reglu', 'swiglu']:
405
+ self.dense_h_to_4h_2 = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.bias)
406
+
407
+ self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.bias)
408
+ self.act = get_activation(config.hidden_act)
409
+
410
+ def forward(self, hidden_states):
411
+ intermediate_states = self.dense_h_to_4h(hidden_states)
412
+ if self.glu_activation_family:
413
+ if self.fast_glu_activation:
414
+ intermediate_states, intermediate_states_2 = torch.chunk(intermediate_states, 2, dim=-1)
415
+ else:
416
+ intermediate_states_2 = self.dense_h_to_4h_2(hidden_states)
417
+
418
+ hidden_states = self.act(intermediate_states) * intermediate_states_2
419
+ else:
420
+ hidden_states = self.act(intermediate_states)
421
+ hidden_states = self.dense_4h_to_h(hidden_states)
422
+ return hidden_states
423
+
424
+
425
+ class MegatronGPTLayer(nn.Module):
426
+ def __init__(self, config, layer_idx):
427
+ super().__init__()
428
+ self.input_layernorm = MegatronGPTLPLayerNorm(config.normalization, config.hidden_size, eps=config.layer_norm_eps)
429
+ self.post_attention_layernorm = MegatronGPTLPLayerNorm(config.normalization, config.hidden_size, eps=config.layer_norm_eps)
430
+ self.post_attention_dropout = nn.Dropout(config.hidden_dropout)
431
+ self.post_mlp_dropout = nn.Dropout(config.hidden_dropout)
432
+ self.self_attention = MegatronGPTAttention(config)
433
+ self.mlp = MegatronGPTMLP(config)
434
+ self.layer_idx = layer_idx
435
+
436
+ def forward(
437
+ self,
438
+ hidden_states: Optional[torch.FloatTensor],
439
+ attention_mask: Optional[torch.FloatTensor] = None,
440
+ position_ids: Optional[torch.LongTensor] = None,
441
+ head_mask: Optional[torch.FloatTensor] = None,
442
+ use_cache: Optional[bool] = False,
443
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
444
+ output_attentions: Optional[bool] = False,
445
+ ):
446
+ attention_layer_outputs = self.self_attention(
447
+ self.input_layernorm(hidden_states),
448
+ attention_mask=attention_mask,
449
+ position_ids=position_ids,
450
+ layer_past=layer_past,
451
+ head_mask=head_mask,
452
+ use_cache=use_cache,
453
+ output_attentions=output_attentions,
454
+ )
455
+ attn_output = attention_layer_outputs[0] # output_attn: attn_output, present, (attn_weights)
456
+ attn_output = self.post_attention_dropout(attn_output)
457
+
458
+ # pseudocode:
459
+ # x = x + attn(ln1(x))
460
+ # x = x + mlp(ln2(x))
461
+ attn_output = attn_output + hidden_states
462
+ mlp_output = self.mlp(self.post_attention_layernorm(attn_output))
463
+ mlp_output = self.post_mlp_dropout(mlp_output)
464
+ hidden_states = mlp_output + attn_output
465
+
466
+ outputs = attention_layer_outputs[1:]
467
+ if use_cache:
468
+ outputs = (hidden_states,) + outputs # hidden_states, present, (attn_weights)
469
+ else:
470
+ outputs = (hidden_states,) + outputs[1:] # hidden_states, (attn_weights)
471
+
472
+ return outputs
473
+
474
+ class MegatronGPTLPLayerNorm(torch.nn.LayerNorm):
475
+ def __init__(self, normalization, normalized_shape, eps=1e-05, elementwise_affine=True, device=None, dtype=None):
476
+ super().__init__(
477
+ normalized_shape=normalized_shape,
478
+ eps=eps,
479
+ elementwise_affine=elementwise_affine,
480
+ device=device,
481
+ dtype=dtype,
482
+ )
483
+ assert normalization in ['layernorm', 'layernorm1p']
484
+ self.normalization = normalization
485
+
486
+ def forward(self, x):
487
+ weight_bias = 1 if self.normalization == 'layernorm1p' else 0
488
+ return torch.nn.functional.layer_norm(
489
+ x, self.normalized_shape, self.weight + weight_bias, self.bias, self.eps
490
+ )
491
+
492
+
493
+
494
+ MEGATRON_GPT_START_DOCSTRING = r"""
495
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
496
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
497
+ behavior.
498
+
499
+ Parameters:
500
+ config ([`~MegatronGPTConfig`]): Model configuration class with all the parameters of the model.
501
+ Initializing with a config file does not load the weights associated with the model, only the
502
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
503
+ """
504
+
505
+ MEGATRON_GPT_INPUTS_DOCSTRING = r"""
506
+ Args:
507
+ input_ids (`torch.LongTensor` of shape `({0})`):
508
+ Indices of input sequence tokens in the vocabulary.
509
+
510
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
511
+ [`PreTrainedTokenizer.__call__`] for details.
512
+
513
+ [What are input IDs?](../glossary#input-ids)
514
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
515
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
516
+
517
+ - 1 for tokens that are **not masked**,
518
+ - 0 for tokens that are **masked**.
519
+
520
+ [What are attention masks?](../glossary#attention-mask)
521
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
522
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
523
+ config.n_positions - 1]`.
524
+
525
+ [What are position IDs?](../glossary#position-ids)
526
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
527
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
528
+
529
+ - 1 indicates the head is **not masked**,
530
+ - 0 indicates the head is **masked**.
531
+
532
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
533
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
534
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
535
+ model's internal embedding lookup matrix.
536
+ output_attentions (`bool`, *optional*):
537
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
538
+ tensors for more detail.
539
+ output_hidden_states (`bool`, *optional*):
540
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
541
+ more detail.
542
+ return_dict (`bool`, *optional*):
543
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
544
+ """
545
+
546
+
547
+ @add_start_docstrings(
548
+ "The bare MegatronGPT Model transformer outputting raw hidden-states without any specific head on top.",
549
+ MEGATRON_GPT_START_DOCSTRING,
550
+ )
551
+ class MegatronGPTModel(MegatronGPTPreTrainedModel):
552
+ def __init__(self, config):
553
+ super().__init__(config)
554
+ self.config = config
555
+
556
+ self.embed_in = nn.Embedding(config.vocab_size, config.hidden_size)
557
+ self.emb_dropout = nn.Dropout(config.hidden_dropout)
558
+ self.layers = nn.ModuleList([MegatronGPTLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
559
+ self.final_layernorm = MegatronGPTLPLayerNorm(config.normalization, config.hidden_size, eps=config.layer_norm_eps)
560
+
561
+ self.gradient_checkpointing = False
562
+
563
+ # Initialize weights and apply final processing
564
+ self.post_init()
565
+
566
+ def get_input_embeddings(self):
567
+ return self.embed_in
568
+
569
+ def set_input_embeddings(self, value):
570
+ self.embed_in = value
571
+
572
+ @add_start_docstrings_to_model_forward(MEGATRON_GPT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
573
+ def forward(
574
+ self,
575
+ input_ids: Optional[torch.LongTensor] = None,
576
+ attention_mask: Optional[torch.FloatTensor] = None,
577
+ position_ids: Optional[torch.LongTensor] = None,
578
+ head_mask: Optional[torch.FloatTensor] = None,
579
+ inputs_embeds: Optional[torch.FloatTensor] = None,
580
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
581
+ use_cache: Optional[bool] = None,
582
+ output_attentions: Optional[bool] = None,
583
+ output_hidden_states: Optional[bool] = None,
584
+ return_dict: Optional[bool] = None,
585
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
586
+ r"""
587
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
588
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
589
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
590
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
591
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
592
+ use_cache (`bool`, *optional*):
593
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
594
+ `past_key_values`).
595
+ """
596
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
597
+ output_hidden_states = (
598
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
599
+ )
600
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
601
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
602
+
603
+ if input_ids is not None and inputs_embeds is not None:
604
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
605
+ elif input_ids is not None:
606
+ input_shape = input_ids.size()
607
+ elif inputs_embeds is not None:
608
+ input_shape = inputs_embeds.size()[:-1]
609
+ else:
610
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
611
+
612
+ batch_size, seq_length = input_shape
613
+
614
+ if past_key_values is None:
615
+ past_length = 0
616
+ past_key_values = tuple([None] * self.config.num_hidden_layers)
617
+ else:
618
+ past_length = past_key_values[0][0].size(-2)
619
+
620
+ if position_ids is None:
621
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
622
+ position_ids = torch.arange(past_length, seq_length + past_length, dtype=torch.long, device=device)
623
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
624
+ else:
625
+ position_ids = position_ids.view(-1, seq_length).long()
626
+
627
+ # Attention mask.
628
+ if attention_mask is not None:
629
+ assert batch_size > 0, "batch_size has to be defined and > 0"
630
+ attention_mask = attention_mask.view(batch_size, -1)
631
+ # We create a 3D attention mask from a 2D tensor mask.
632
+ # Sizes are [batch_size, 1, 1, to_seq_length]
633
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
634
+ # this attention mask is more simple than the triangular masking of causal attention
635
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
636
+ attention_mask = attention_mask[:, None, None, :]
637
+
638
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
639
+ # masked positions, this operation will create a tensor which is 0.0 for
640
+ # positions we want to attend and the dtype's smallest value for masked positions.
641
+ # Since we are adding it to the raw scores before the softmax, this is
642
+ # effectively the same as removing these entirely.
643
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
644
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
645
+
646
+ # Prepare head mask if needed
647
+ # 1.0 in head_mask indicate we keep the head
648
+ # attention_probs has shape bsz x n_heads x N x N
649
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
650
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
651
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
652
+
653
+ if inputs_embeds is None:
654
+ inputs_embeds = self.embed_in(input_ids)
655
+
656
+ hidden_states = self.emb_dropout(inputs_embeds)
657
+
658
+ if self.gradient_checkpointing and self.training:
659
+ if use_cache:
660
+ logger.warning(
661
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
662
+ )
663
+ use_cache = False
664
+
665
+ presents = () if use_cache else None
666
+ all_attentions = () if output_attentions else None
667
+ all_hidden_states = () if output_hidden_states else None
668
+ for i, (layer, layer_past) in enumerate(zip(self.layers, past_key_values)):
669
+ if output_hidden_states:
670
+ all_hidden_states = all_hidden_states + (hidden_states,)
671
+
672
+ if self.gradient_checkpointing and self.training:
673
+
674
+ def create_custom_forward(module):
675
+ def custom_forward(*inputs):
676
+ # None for layer_past
677
+ return module(*inputs, use_cache, None, output_attentions)
678
+
679
+ return custom_forward
680
+
681
+ outputs = torch.utils.checkpoint.checkpoint(
682
+ create_custom_forward(layer),
683
+ hidden_states,
684
+ attention_mask,
685
+ position_ids,
686
+ head_mask[i],
687
+ )
688
+ else:
689
+ outputs = layer(
690
+ hidden_states,
691
+ attention_mask=attention_mask,
692
+ position_ids=position_ids,
693
+ head_mask=head_mask[i],
694
+ layer_past=layer_past,
695
+ use_cache=use_cache,
696
+ output_attentions=output_attentions,
697
+ )
698
+ hidden_states = outputs[0]
699
+ if use_cache is True:
700
+ presents = presents + (outputs[1],)
701
+ if output_attentions:
702
+ all_attentions = all_attentions + (outputs[2 if use_cache else 1],)
703
+
704
+ hidden_states = self.final_layernorm(hidden_states)
705
+ # Add last hidden state
706
+ if output_hidden_states:
707
+ all_hidden_states = all_hidden_states + (hidden_states,)
708
+
709
+ if not return_dict:
710
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_attentions] if v is not None)
711
+
712
+ return BaseModelOutputWithPast(
713
+ last_hidden_state=hidden_states,
714
+ past_key_values=presents,
715
+ hidden_states=all_hidden_states,
716
+ attentions=all_attentions,
717
+ )
718
+
719
+
720
+ @add_start_docstrings(
721
+ """MegatronGPT Model with a `language modeling` head on top for CLM fine-tuning.""", MEGATRON_GPT_START_DOCSTRING
722
+ )
723
+ class MegatronGPTForCausalLM(MegatronGPTPreTrainedModel):
724
+ _tied_weights_keys = ["embed_out.weight"]
725
+
726
+ def __init__(self, config):
727
+ super().__init__(config)
728
+
729
+ self.megatron_gpt = MegatronGPTModel(config)
730
+ self.embed_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
731
+
732
+ # Initialize weights and apply final processing
733
+ self.post_init()
734
+
735
+ def get_output_embeddings(self):
736
+ return self.embed_out
737
+
738
+ def set_output_embeddings(self, new_embeddings):
739
+ self.embed_out = new_embeddings
740
+
741
+ @add_start_docstrings_to_model_forward(MEGATRON_GPT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
742
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
743
+ def forward(
744
+ self,
745
+ input_ids: Optional[torch.LongTensor] = None,
746
+ attention_mask: Optional[torch.FloatTensor] = None,
747
+ position_ids: Optional[torch.LongTensor] = None,
748
+ inputs_embeds: Optional[torch.FloatTensor] = None,
749
+ head_mask: Optional[torch.FloatTensor] = None,
750
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
751
+ labels: Optional[torch.LongTensor] = None,
752
+ use_cache: Optional[bool] = None,
753
+ output_attentions: Optional[bool] = None,
754
+ output_hidden_states: Optional[bool] = None,
755
+ return_dict: Optional[bool] = None,
756
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
757
+ r"""
758
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
759
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
760
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
761
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional tensors are
762
+ only required when the model is used as a decoder in a Sequence to Sequence model.
763
+
764
+ Contains pre-computed hidden-states (key and values in the self-attention blocks that can be used (see
765
+ `past_key_values` input) to speed up sequential decoding.
766
+
767
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
768
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
769
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
770
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
771
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
772
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
773
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
774
+ use_cache (`bool`, *optional*):
775
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
776
+ `past_key_values`).
777
+
778
+ Returns:
779
+ """
780
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
781
+
782
+ outputs = self.megatron_gpt(
783
+ input_ids,
784
+ attention_mask=attention_mask,
785
+ position_ids=position_ids,
786
+ head_mask=head_mask,
787
+ inputs_embeds=inputs_embeds,
788
+ past_key_values=past_key_values,
789
+ use_cache=use_cache,
790
+ output_attentions=output_attentions,
791
+ output_hidden_states=output_hidden_states,
792
+ return_dict=return_dict,
793
+ )
794
+
795
+ hidden_states = outputs[0]
796
+ lm_logits = self.embed_out(hidden_states)
797
+
798
+ lm_loss = None
799
+ if labels is not None:
800
+ # move labels to correct device to enable model parallelism
801
+ labels = labels.to(lm_logits.device)
802
+ # we are doing next-token prediction; shift prediction scores and input ids by one
803
+ shift_logits = lm_logits[:, :-1, :].contiguous()
804
+ labels = labels[:, 1:].contiguous()
805
+ loss_fct = CrossEntropyLoss()
806
+ lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), labels.view(-1))
807
+
808
+ if not return_dict:
809
+ output = (lm_logits,) + outputs[1:]
810
+ return ((lm_loss,) + output) if lm_loss is not None else output
811
+
812
+ return CausalLMOutputWithPast(
813
+ loss=lm_loss,
814
+ logits=lm_logits,
815
+ past_key_values=outputs.past_key_values,
816
+ hidden_states=outputs.hidden_states,
817
+ attentions=outputs.attentions,
818
+ )
819
+
820
+ def prepare_inputs_for_generation(
821
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
822
+ ):
823
+ input_shape = input_ids.shape
824
+
825
+ # cut decoder_input_ids if past is used
826
+ if past_key_values and past_key_values[0] is not None:
827
+ input_ids = input_ids[:, -1:]
828
+
829
+ position_ids = kwargs.get("position_ids", None)
830
+ if attention_mask is not None and position_ids is None:
831
+ # create position_ids on the fly for batch generation
832
+ position_ids = attention_mask.long().cumsum(-1) - 1
833
+ position_ids.masked_fill_(attention_mask == 0, 1)
834
+ if past_key_values:
835
+ position_ids = position_ids[:, -1].unsqueeze(-1)
836
+
837
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
838
+ if attention_mask is None:
839
+ attention_mask = input_ids.new_ones(input_shape)
840
+
841
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
842
+ if inputs_embeds is not None and past_key_values is None:
843
+ model_inputs = {"inputs_embeds": inputs_embeds}
844
+ else:
845
+ model_inputs = {"input_ids": input_ids}
846
+
847
+ model_inputs.update(
848
+ {
849
+ "attention_mask": attention_mask,
850
+ "past_key_values": past_key_values,
851
+ "position_ids": position_ids,
852
+ }
853
+ )
854
+
855
+ return model_inputs
856
+
857
+ def _reorder_cache(self, past_key_values, beam_idx):
858
+ reordered_past = ()
859
+ for layer_past in past_key_values:
860
+ reordered_past += (
861
+ tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2]) + layer_past[2:],
862
+ )
863
+ return reordered_past
864
+
865
+
866
+ @add_start_docstrings(
867
+ """
868
+ The MegatronGPT Model transformer with a sequence classification head on top (linear layer).
869
+
870
+ [`MegatronGPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models
871
+ (e.g. GPT-1) do.
872
+
873
+ Since it does classification on the last token, it requires to know the position of the last token. If a
874
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
875
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
876
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
877
+ each row of the batch).
878
+ """,
879
+ MEGATRON_GPT_START_DOCSTRING,
880
+ )
881
+ class MegatronGPTForSequenceClassification(MegatronGPTPreTrainedModel):
882
+ def __init__(self, config):
883
+ super().__init__(config)
884
+ self.num_labels = config.num_labels
885
+ self.megatron_gpt = MegatronGPTModel(config)
886
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
887
+
888
+ # Initialize weights and apply final processing
889
+ self.post_init()
890
+
891
+ @add_start_docstrings_to_model_forward(MEGATRON_GPT_INPUTS_DOCSTRING)
892
+ def forward(
893
+ self,
894
+ input_ids: Optional[torch.LongTensor] = None,
895
+ attention_mask: Optional[torch.FloatTensor] = None,
896
+ position_ids: Optional[torch.LongTensor] = None,
897
+ inputs_embeds: Optional[torch.FloatTensor] = None,
898
+ head_mask: Optional[torch.FloatTensor] = None,
899
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
900
+ labels: Optional[torch.LongTensor] = None,
901
+ use_cache: Optional[bool] = None,
902
+ output_attentions: Optional[bool] = None,
903
+ output_hidden_states: Optional[bool] = None,
904
+ return_dict: Optional[bool] = None,
905
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
906
+ r"""
907
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
908
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
909
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
910
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
911
+ """
912
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
913
+
914
+ outputs = self.megatron_gpt(
915
+ input_ids,
916
+ attention_mask=attention_mask,
917
+ position_ids=position_ids,
918
+ head_mask=head_mask,
919
+ inputs_embeds=inputs_embeds,
920
+ past_key_values=past_key_values,
921
+ use_cache=use_cache,
922
+ output_attentions=output_attentions,
923
+ output_hidden_states=output_hidden_states,
924
+ return_dict=return_dict,
925
+ )
926
+ hidden_states = outputs[0]
927
+ logits = self.score(hidden_states)
928
+
929
+ if input_ids is not None:
930
+ batch_size, sequence_length = input_ids.shape[:2]
931
+ else:
932
+ batch_size, sequence_length = inputs_embeds.shape[:2]
933
+
934
+ if self.config.pad_token_id is None and batch_size != 1:
935
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
936
+ if self.config.pad_token_id is None:
937
+ sequence_lengths = -1
938
+ else:
939
+ if input_ids is not None:
940
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
941
+ else:
942
+ sequence_lengths = -1
943
+ logger.warning(
944
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
945
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
946
+ )
947
+
948
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
949
+
950
+ loss = None
951
+ if labels is not None:
952
+ labels = labels.to(logits.device)
953
+ if self.config.problem_type is None:
954
+ if self.num_labels == 1:
955
+ self.config.problem_type = "regression"
956
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
957
+ self.config.problem_type = "single_label_classification"
958
+ else:
959
+ self.config.problem_type = "multi_label_classification"
960
+
961
+ if self.config.problem_type == "regression":
962
+ loss_fct = MSELoss()
963
+ if self.num_labels == 1:
964
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
965
+ else:
966
+ loss = loss_fct(pooled_logits, labels)
967
+ elif self.config.problem_type == "single_label_classification":
968
+ loss_fct = CrossEntropyLoss()
969
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
970
+ elif self.config.problem_type == "multi_label_classification":
971
+ loss_fct = BCEWithLogitsLoss()
972
+ loss = loss_fct(pooled_logits, labels)
973
+ if not return_dict:
974
+ output = (pooled_logits,) + outputs[1:]
975
+ return ((loss,) + output) if loss is not None else output
976
+
977
+ return SequenceClassifierOutputWithPast(
978
+ loss=loss,
979
+ logits=pooled_logits,
980
+ past_key_values=outputs.past_key_values,
981
+ hidden_states=outputs.hidden_states,
982
+ attentions=outputs.attentions,
983
+ )
984
+
985
+
986
+ class MegatronGPTForTokenClassification(MegatronGPTPreTrainedModel):
987
+ def __init__(self, config):
988
+ super().__init__(config)
989
+ self.num_labels = config.num_labels
990
+
991
+ self.megatron_gpt = MegatronGPTModel(config)
992
+ self.dropout = nn.Dropout(config.classifier_dropout)
993
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
994
+
995
+ # Initialize weights and apply final processing
996
+ self.post_init()
997
+
998
+ @add_start_docstrings_to_model_forward(MEGATRON_GPT_INPUTS_DOCSTRING)
999
+ def forward(
1000
+ self,
1001
+ input_ids: Optional[torch.LongTensor] = None,
1002
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1003
+ attention_mask: Optional[torch.FloatTensor] = None,
1004
+ token_type_ids: Optional[torch.LongTensor] = None,
1005
+ position_ids: Optional[torch.LongTensor] = None,
1006
+ head_mask: Optional[torch.FloatTensor] = None,
1007
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1008
+ labels: Optional[torch.LongTensor] = None,
1009
+ use_cache: Optional[bool] = None,
1010
+ output_attentions: Optional[bool] = None,
1011
+ output_hidden_states: Optional[bool] = None,
1012
+ return_dict: Optional[bool] = None,
1013
+ ) -> Union[Tuple, TokenClassifierOutput]:
1014
+ r"""
1015
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1016
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1017
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1018
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1019
+ """
1020
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1021
+
1022
+ outputs = self.megatron_gpt(
1023
+ input_ids,
1024
+ past_key_values=past_key_values,
1025
+ attention_mask=attention_mask,
1026
+ position_ids=position_ids,
1027
+ head_mask=head_mask,
1028
+ inputs_embeds=inputs_embeds,
1029
+ use_cache=use_cache,
1030
+ output_attentions=output_attentions,
1031
+ output_hidden_states=output_hidden_states,
1032
+ return_dict=return_dict,
1033
+ )
1034
+
1035
+ hidden_states = outputs[0]
1036
+ hidden_states = self.dropout(hidden_states)
1037
+ logits = self.classifier(hidden_states)
1038
+
1039
+ loss = None
1040
+ if labels is not None:
1041
+ labels = labels.to(logits.device)
1042
+ loss_fct = CrossEntropyLoss()
1043
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1044
+
1045
+ if not return_dict:
1046
+ output = (logits,) + outputs[2:]
1047
+ return ((loss,) + output) if loss is not None else output
1048
+
1049
+ return TokenClassifierOutput(
1050
+ loss=loss,
1051
+ logits=logits,
1052
+ hidden_states=outputs.hidden_states,
1053
+ attentions=outputs.attentions,
1054
+ )
1055
+
1056
+
1057
+ @add_start_docstrings(
1058
+ """
1059
+ The Megatron-GPT Model transformer with a span classification head on top for extractive question-answering tasks like
1060
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1061
+ """,
1062
+ MEGATRON_GPT_START_DOCSTRING,
1063
+ )
1064
+ class MegatronGPTForQuestionAnswering(MegatronGPTPreTrainedModel):
1065
+ def __init__(self, config):
1066
+ super().__init__(config)
1067
+ self.num_labels = config.num_labels
1068
+ self.megatron_gpt = MegatronGPTModel(config)
1069
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1070
+
1071
+ # Initialize weights and apply final processing
1072
+ self.post_init()
1073
+
1074
+ @add_start_docstrings_to_model_forward(MEGATRON_GPT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1075
+ def forward(
1076
+ self,
1077
+ input_ids: Optional[torch.LongTensor] = None,
1078
+ attention_mask: Optional[torch.FloatTensor] = None,
1079
+ token_type_ids: Optional[torch.LongTensor] = None,
1080
+ position_ids: Optional[torch.LongTensor] = None,
1081
+ head_mask: Optional[torch.FloatTensor] = None,
1082
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1083
+ start_positions: Optional[torch.LongTensor] = None,
1084
+ end_positions: Optional[torch.LongTensor] = None,
1085
+ output_attentions: Optional[bool] = None,
1086
+ output_hidden_states: Optional[bool] = None,
1087
+ return_dict: Optional[bool] = None,
1088
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1089
+ r"""
1090
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1091
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1092
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1093
+ are not taken into account for computing the loss.
1094
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1095
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1096
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1097
+ are not taken into account for computing the loss.
1098
+ """
1099
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1100
+
1101
+ outputs = self.megatron_gpt(
1102
+ input_ids,
1103
+ attention_mask=attention_mask,
1104
+ position_ids=position_ids,
1105
+ head_mask=head_mask,
1106
+ inputs_embeds=inputs_embeds,
1107
+ output_attentions=output_attentions,
1108
+ output_hidden_states=output_hidden_states,
1109
+ return_dict=return_dict,
1110
+ )
1111
+
1112
+ sequence_output = outputs[0]
1113
+
1114
+ logits = self.qa_outputs(sequence_output)
1115
+ start_logits, end_logits = logits.split(1, dim=-1)
1116
+ start_logits = start_logits.squeeze(-1).contiguous()
1117
+ end_logits = end_logits.squeeze(-1).contiguous()
1118
+
1119
+ total_loss = None
1120
+ if start_positions is not None and end_positions is not None:
1121
+ # If we are on multi-GPU, split add a dimension
1122
+ if len(start_positions.size()) > 1:
1123
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1124
+ if len(end_positions.size()) > 1:
1125
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1126
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1127
+ ignored_index = start_logits.size(1)
1128
+ start_positions = start_positions.clamp(0, ignored_index)
1129
+ end_positions = end_positions.clamp(0, ignored_index)
1130
+
1131
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1132
+ start_loss = loss_fct(start_logits, start_positions)
1133
+ end_loss = loss_fct(end_logits, end_positions)
1134
+ total_loss = (start_loss + end_loss) / 2
1135
+
1136
+ if not return_dict:
1137
+ output = (start_logits, end_logits) + outputs[2:]
1138
+ return ((total_loss,) + output) if total_loss is not None else output
1139
+
1140
+ return QuestionAnsweringModelOutput(
1141
+ loss=total_loss,
1142
+ start_logits=start_logits,
1143
+ end_logits=end_logits,
1144
+ hidden_states=outputs.hidden_states,
1145
+ attentions=outputs.attentions,
1146
+ )