TiwakalNationPH commited on
Commit
06c8dfb
·
verified ·
1 Parent(s): bb56873

Upload 6 files

Browse files
__init__.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available
17
+ from ...utils import OptionalDependencyNotAvailable
18
+
19
+
20
+ _import_structure = {"configuration_gpt_neox": ["GPTNeoXConfig"]}
21
+
22
+ try:
23
+ if not is_tokenizers_available():
24
+ raise OptionalDependencyNotAvailable()
25
+ except OptionalDependencyNotAvailable:
26
+ pass
27
+ else:
28
+ _import_structure["tokenization_gpt_neox_fast"] = ["GPTNeoXTokenizerFast"]
29
+
30
+ try:
31
+ if not is_torch_available():
32
+ raise OptionalDependencyNotAvailable()
33
+ except OptionalDependencyNotAvailable:
34
+ pass
35
+ else:
36
+ _import_structure["modeling_gpt_neox"] = [
37
+ "GPTNeoXForCausalLM",
38
+ "GPTNeoXForQuestionAnswering",
39
+ "GPTNeoXForSequenceClassification",
40
+ "GPTNeoXForTokenClassification",
41
+ "GPTNeoXLayer",
42
+ "GPTNeoXModel",
43
+ "GPTNeoXPreTrainedModel",
44
+ ]
45
+
46
+
47
+ if TYPE_CHECKING:
48
+ from .configuration_gpt_neox import GPTNeoXConfig
49
+
50
+ try:
51
+ if not is_tokenizers_available():
52
+ raise OptionalDependencyNotAvailable()
53
+ except OptionalDependencyNotAvailable:
54
+ pass
55
+ else:
56
+ from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast
57
+
58
+ try:
59
+ if not is_torch_available():
60
+ raise OptionalDependencyNotAvailable()
61
+ except OptionalDependencyNotAvailable:
62
+ pass
63
+ else:
64
+ from .modeling_gpt_neox import (
65
+ GPTNeoXForCausalLM,
66
+ GPTNeoXForQuestionAnswering,
67
+ GPTNeoXForSequenceClassification,
68
+ GPTNeoXForTokenClassification,
69
+ GPTNeoXLayer,
70
+ GPTNeoXModel,
71
+ GPTNeoXPreTrainedModel,
72
+ )
73
+
74
+
75
+ else:
76
+ import sys
77
+
78
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "OlmoForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "clip_qkv": 8.0,
8
+ "eos_token_id": 50279,
9
+ "hidden_act": "silu",
10
+ "hidden_size": 4096,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 11008,
13
+ "max_position_embeddings": 4096,
14
+ "model_type": "olmo",
15
+ "num_attention_heads": 32,
16
+ "num_hidden_layers": 32,
17
+ "num_key_value_heads": 32,
18
+ "pad_token_id": 1,
19
+ "rope_scaling": null,
20
+ "rope_theta": 10000.0,
21
+ "tie_word_embeddings": false,
22
+ "torch_dtype": "float32",
23
+ "transformers_version": "4.40.2",
24
+ "use_cache": true,
25
+ "vocab_size": 50304
26
+ }
configuration_gpt_neox.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """GPTNeoX model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...modeling_rope_utils import rope_config_validation
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class GPTNeoXConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`GPTNeoXModel`]. It is used to instantiate an
28
+ GPTNeoX model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the GPTNeoX
30
+ [EleutherAI/gpt-neox-20b](https://huggingface.co/EleutherAI/gpt-neox-20b) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 50432):
38
+ Vocabulary size of the GPTNeoX model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`GPTNeoXModel`].
40
+ hidden_size (`int`, *optional*, defaults to 6144):
41
+ Dimension of the encoder layers and the pooler layer.
42
+ num_hidden_layers (`int`, *optional*, defaults to 44):
43
+ Number of hidden layers in the Transformer encoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 64):
45
+ Number of attention heads for each attention layer in the Transformer encoder.
46
+ intermediate_size (`int`, *optional*, defaults to 24576):
47
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
48
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
49
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
50
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
51
+ rotary_pct (`float`, *optional*, defaults to 0.25):
52
+ percentage of hidden dimensions to allocate to rotary embeddings
53
+ rotary_emb_base (`int`, *optional*, defaults to 10000)
54
+ base for computing rotary embeddings frequency
55
+ attention_dropout (`float`, *optional*, defaults to 0.0):
56
+ The dropout ratio probability of the attention score.
57
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
58
+ The dropout ratio of (1) the word embeddings, (2) the post-attention hidden states, and (3) the post-mlp
59
+ hidden states.
60
+ classifier_dropout (`float`, *optional*, defaults to 0.1):
61
+ Argument used when doing token classification, used in the model [`GPTNeoXForTokenClassification`].
62
+
63
+ The dropout ratio for the hidden layer.
64
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
65
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
66
+ just in case (e.g., 512 or 1024 or 2048).
67
+ initializer_range (`float`, *optional*, defaults to 1e-5):
68
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
69
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
70
+ The epsilon used by the layer normalization layers.
71
+ use_cache (`bool`, *optional*, defaults to `True`):
72
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
73
+ relevant if `config.is_decoder=True`.
74
+ use_parallel_residual (`bool`, *optional*, defaults to `True`):
75
+ Whether to use a "parallel" formulation in each Transformer layer, which can provide a slight training
76
+ speedup at large scales (e.g. 20B).
77
+ rope_scaling (`Dict`, *optional*):
78
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
79
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
80
+ accordingly.
81
+ Expected contents:
82
+ `rope_type` (`str`):
83
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
84
+ 'llama3'], with 'default' being the original RoPE implementation.
85
+ `factor` (`float`, *optional*):
86
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
87
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
88
+ original maximum pre-trained length.
89
+ `original_max_position_embeddings` (`int`, *optional*):
90
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
91
+ pretraining.
92
+ `attention_factor` (`float`, *optional*):
93
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
94
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
95
+ `factor` field to infer the suggested value.
96
+ `beta_fast` (`float`, *optional*):
97
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
98
+ ramp function. If unspecified, it defaults to 32.
99
+ `beta_slow` (`float`, *optional*):
100
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
101
+ ramp function. If unspecified, it defaults to 1.
102
+ `short_factor` (`List[float]`, *optional*):
103
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
104
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
105
+ size divided by the number of attention heads divided by 2
106
+ `long_factor` (`List[float]`, *optional*):
107
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
108
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
109
+ size divided by the number of attention heads divided by 2
110
+ `low_freq_factor` (`float`, *optional*):
111
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
112
+ `high_freq_factor` (`float`, *optional*):
113
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
114
+ attention_bias (`bool`, *optional*, defaults to `True`):
115
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
116
+
117
+ Example:
118
+
119
+ ```python
120
+ >>> from transformers import GPTNeoXConfig, GPTNeoXModel
121
+
122
+ >>> # Initializing a GPTNeoX gpt-neox-20b style configuration
123
+ >>> configuration = GPTNeoXConfig()
124
+
125
+ >>> # Initializing a model (with random weights) from the gpt-neox-20b style configuration
126
+ >>> model = GPTNeoXModel(configuration) # doctest: +SKIP
127
+
128
+ >>> # Accessing the model configuration
129
+ >>> configuration = model.config # doctest: +SKIP
130
+ ```"""
131
+
132
+ model_type = "gpt_neox"
133
+ keys_to_ignore_at_inference = ["past_key_values"]
134
+
135
+ def __init__(
136
+ self,
137
+ vocab_size=50432,
138
+ hidden_size=6144,
139
+ num_hidden_layers=44,
140
+ num_attention_heads=64,
141
+ intermediate_size=24576,
142
+ hidden_act="gelu",
143
+ rotary_pct=0.25,
144
+ rotary_emb_base=10000,
145
+ attention_dropout=0.0,
146
+ hidden_dropout=0.0,
147
+ classifier_dropout=0.1,
148
+ max_position_embeddings=2048,
149
+ initializer_range=0.02,
150
+ layer_norm_eps=1e-5,
151
+ use_cache=True,
152
+ bos_token_id=0,
153
+ eos_token_id=2,
154
+ tie_word_embeddings=False,
155
+ use_parallel_residual=True,
156
+ rope_scaling=None,
157
+ attention_bias=True,
158
+ **kwargs,
159
+ ):
160
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
161
+ self.vocab_size = vocab_size
162
+ self.max_position_embeddings = max_position_embeddings
163
+ self.hidden_size = hidden_size
164
+ self.num_hidden_layers = num_hidden_layers
165
+ self.num_attention_heads = num_attention_heads
166
+ self.intermediate_size = intermediate_size
167
+ self.hidden_act = hidden_act
168
+ self.rotary_pct = rotary_pct
169
+ self.partial_rotary_factor = rotary_pct
170
+ self.rotary_emb_base = rotary_emb_base
171
+ self.rope_theta = rotary_emb_base
172
+ self.attention_dropout = attention_dropout
173
+ self.hidden_dropout = hidden_dropout
174
+ self.classifier_dropout = classifier_dropout
175
+ self.initializer_range = initializer_range
176
+ self.layer_norm_eps = layer_norm_eps
177
+ self.use_cache = use_cache
178
+ self.tie_word_embeddings = tie_word_embeddings
179
+ self.use_parallel_residual = use_parallel_residual
180
+ self.rope_scaling = rope_scaling
181
+ self.attention_bias = attention_bias
182
+ # Validate the correctness of rotary position embeddings parameters
183
+ # BC: if there is a 'type' field, move it to 'rope_type'.
184
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
185
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
186
+ rope_config_validation(self)
187
+
188
+ if self.hidden_size % self.num_attention_heads != 0:
189
+ raise ValueError(
190
+ "The hidden size is not divisble by the number of attention heads! Make sure to update them!"
191
+ )
model.safetensors.index.json ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 27552382976
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00006-of-00006.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00006.safetensors",
8
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
9
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
10
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
11
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
13
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
14
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
15
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
16
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
17
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
18
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
19
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
20
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
21
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
22
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
23
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
24
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
25
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
26
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
27
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
28
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
29
+ "model.layers.11.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
30
+ "model.layers.11.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
31
+ "model.layers.11.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
32
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
33
+ "model.layers.11.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
34
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
35
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
36
+ "model.layers.12.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
37
+ "model.layers.12.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
38
+ "model.layers.12.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
39
+ "model.layers.12.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
40
+ "model.layers.12.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
41
+ "model.layers.12.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
42
+ "model.layers.12.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
43
+ "model.layers.13.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
44
+ "model.layers.13.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
45
+ "model.layers.13.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
46
+ "model.layers.13.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
47
+ "model.layers.13.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
48
+ "model.layers.13.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
49
+ "model.layers.13.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
50
+ "model.layers.14.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
51
+ "model.layers.14.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
52
+ "model.layers.14.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
53
+ "model.layers.14.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
54
+ "model.layers.14.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
55
+ "model.layers.14.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
56
+ "model.layers.14.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
57
+ "model.layers.15.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
58
+ "model.layers.15.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
59
+ "model.layers.15.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
60
+ "model.layers.15.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
61
+ "model.layers.15.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
62
+ "model.layers.15.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
63
+ "model.layers.15.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
64
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
65
+ "model.layers.16.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
66
+ "model.layers.16.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
67
+ "model.layers.16.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
68
+ "model.layers.16.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
69
+ "model.layers.16.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
70
+ "model.layers.16.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
71
+ "model.layers.17.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
72
+ "model.layers.17.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
73
+ "model.layers.17.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
74
+ "model.layers.17.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
75
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
76
+ "model.layers.17.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
77
+ "model.layers.17.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
78
+ "model.layers.18.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
79
+ "model.layers.18.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
80
+ "model.layers.18.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
81
+ "model.layers.18.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
82
+ "model.layers.18.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
83
+ "model.layers.18.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
84
+ "model.layers.18.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
85
+ "model.layers.19.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
86
+ "model.layers.19.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
87
+ "model.layers.19.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
88
+ "model.layers.19.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
89
+ "model.layers.19.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
90
+ "model.layers.19.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
91
+ "model.layers.19.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
92
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
93
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
94
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
95
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
96
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
97
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
98
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
99
+ "model.layers.20.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
100
+ "model.layers.20.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
101
+ "model.layers.20.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
102
+ "model.layers.20.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
103
+ "model.layers.20.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
104
+ "model.layers.20.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
105
+ "model.layers.20.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
106
+ "model.layers.21.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
107
+ "model.layers.21.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
108
+ "model.layers.21.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
109
+ "model.layers.21.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
110
+ "model.layers.21.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
111
+ "model.layers.21.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
112
+ "model.layers.21.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
113
+ "model.layers.22.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
114
+ "model.layers.22.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
115
+ "model.layers.22.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
116
+ "model.layers.22.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
117
+ "model.layers.22.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
118
+ "model.layers.22.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
119
+ "model.layers.22.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
120
+ "model.layers.23.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
121
+ "model.layers.23.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
122
+ "model.layers.23.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
123
+ "model.layers.23.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
124
+ "model.layers.23.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
125
+ "model.layers.23.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
126
+ "model.layers.23.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
127
+ "model.layers.24.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
128
+ "model.layers.24.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
129
+ "model.layers.24.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
130
+ "model.layers.24.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
131
+ "model.layers.24.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
132
+ "model.layers.24.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
133
+ "model.layers.24.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
134
+ "model.layers.25.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
135
+ "model.layers.25.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
136
+ "model.layers.25.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
137
+ "model.layers.25.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
138
+ "model.layers.25.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
139
+ "model.layers.25.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
140
+ "model.layers.25.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
141
+ "model.layers.26.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
142
+ "model.layers.26.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
143
+ "model.layers.26.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
144
+ "model.layers.26.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
145
+ "model.layers.26.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
146
+ "model.layers.26.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
147
+ "model.layers.26.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
148
+ "model.layers.27.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
149
+ "model.layers.27.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
150
+ "model.layers.27.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
151
+ "model.layers.27.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
152
+ "model.layers.27.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
153
+ "model.layers.27.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
154
+ "model.layers.27.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
155
+ "model.layers.28.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
156
+ "model.layers.28.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
157
+ "model.layers.28.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
158
+ "model.layers.28.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
159
+ "model.layers.28.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
160
+ "model.layers.28.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
161
+ "model.layers.28.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
162
+ "model.layers.29.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
163
+ "model.layers.29.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
164
+ "model.layers.29.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
165
+ "model.layers.29.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
166
+ "model.layers.29.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
167
+ "model.layers.29.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
168
+ "model.layers.29.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
169
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
170
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
171
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
172
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
173
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
174
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
175
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
176
+ "model.layers.30.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
177
+ "model.layers.30.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
178
+ "model.layers.30.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
179
+ "model.layers.30.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
180
+ "model.layers.30.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
181
+ "model.layers.30.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
182
+ "model.layers.30.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
183
+ "model.layers.31.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
184
+ "model.layers.31.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
185
+ "model.layers.31.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
186
+ "model.layers.31.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
187
+ "model.layers.31.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
188
+ "model.layers.31.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
189
+ "model.layers.31.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
190
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
191
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
192
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
193
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
194
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
195
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
196
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
197
+ "model.layers.5.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
198
+ "model.layers.5.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
199
+ "model.layers.5.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
200
+ "model.layers.5.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
201
+ "model.layers.5.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
202
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
203
+ "model.layers.5.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
204
+ "model.layers.6.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
205
+ "model.layers.6.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
206
+ "model.layers.6.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
207
+ "model.layers.6.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
208
+ "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
209
+ "model.layers.6.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
210
+ "model.layers.6.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
211
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
212
+ "model.layers.7.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
213
+ "model.layers.7.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
214
+ "model.layers.7.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
215
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
216
+ "model.layers.7.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
217
+ "model.layers.7.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
218
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
219
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
220
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
221
+ "model.layers.8.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
222
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
223
+ "model.layers.8.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
224
+ "model.layers.8.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
225
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
226
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
227
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
228
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
229
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
230
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
231
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00006.safetensors"
232
+ }
233
+ }
modeling_gpt_neox.py ADDED
@@ -0,0 +1,1528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch GPTNeoX model."""
16
+
17
+ from typing import Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.utils.checkpoint
21
+ from packaging import version
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache, DynamicCache, StaticCache
27
+ from ...file_utils import (
28
+ add_code_sample_docstrings,
29
+ add_start_docstrings,
30
+ add_start_docstrings_to_model_forward,
31
+ replace_return_docstrings,
32
+ )
33
+ from ...generation import GenerationMixin
34
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
35
+ from ...modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ QuestionAnsweringModelOutput,
39
+ SequenceClassifierOutputWithPast,
40
+ TokenClassifierOutput,
41
+ )
42
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
43
+ from ...modeling_utils import PreTrainedModel
44
+ from ...utils import (
45
+ get_torch_version,
46
+ is_flash_attn_2_available,
47
+ is_flash_attn_greater_or_equal_2_10,
48
+ logging,
49
+ )
50
+ from .configuration_gpt_neox import GPTNeoXConfig
51
+
52
+
53
+ if is_flash_attn_2_available():
54
+ from ...modeling_flash_attention_utils import _flash_attention_forward
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ _CHECKPOINT_FOR_DOC = "trl-internal-testing/tiny-random-GPTNeoXForCausalLM"
59
+ _REAL_CHECKPOINT_FOR_DOC = "EleutherAI/gpt-neox-20b"
60
+ _CONFIG_FOR_DOC = "GPTNeoXConfig"
61
+
62
+
63
+ class GPTNeoXPreTrainedModel(PreTrainedModel):
64
+ """
65
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
66
+ models.
67
+ """
68
+
69
+ config_class = GPTNeoXConfig
70
+ base_model_prefix = "gpt_neox"
71
+ supports_gradient_checkpointing = True
72
+ _no_split_modules = ["GPTNeoXLayer"]
73
+ _skip_keys_device_placement = "past_key_values"
74
+ _supports_flash_attn_2 = True
75
+ _supports_cache_class = True
76
+ _supports_quantized_cache = True
77
+ _supports_static_cache = True
78
+ _supports_sdpa = True
79
+
80
+ def _init_weights(self, module):
81
+ """Initialize the weights"""
82
+ if isinstance(module, nn.Linear):
83
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
84
+ if module.bias is not None:
85
+ module.bias.data.zero_()
86
+ elif isinstance(module, nn.Embedding):
87
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
88
+ if module.padding_idx is not None:
89
+ module.weight.data[module.padding_idx].zero_()
90
+ elif isinstance(module, nn.LayerNorm):
91
+ module.bias.data.zero_()
92
+ module.weight.data.fill_(1.0)
93
+
94
+
95
+ class GPTNeoXAttention(nn.Module):
96
+ def __init__(self, config, layer_idx=None):
97
+ super().__init__()
98
+ self.config = config
99
+ self.num_attention_heads = config.num_attention_heads
100
+ self.hidden_size = config.hidden_size
101
+ if self.hidden_size % self.num_attention_heads != 0:
102
+ raise ValueError(
103
+ "The hidden size is not divisble by the number of attention heads! Make sure to update them"
104
+ )
105
+ self.head_size = self.hidden_size // self.num_attention_heads
106
+ self.rotary_ndims = int(self.head_size * config.rotary_pct)
107
+ self.rope_theta = config.rotary_emb_base
108
+ self._init_bias(config.max_position_embeddings)
109
+
110
+ self.register_buffer("masked_bias", torch.tensor(-1e9), persistent=False)
111
+ self.rotary_emb = GPTNeoXRotaryEmbedding(config=self.config)
112
+
113
+ if layer_idx is None:
114
+ logger.warning_once(
115
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
116
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
117
+ "when creating this class."
118
+ )
119
+ self.norm_factor = self.head_size**-0.5
120
+ self.query_key_value = nn.Linear(config.hidden_size, 3 * config.hidden_size, bias=config.attention_bias)
121
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attention_bias)
122
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
123
+ self.is_causal = True
124
+ self.layer_idx = layer_idx
125
+
126
+ def _init_bias(self, max_positions, device=None):
127
+ self.register_buffer(
128
+ "bias",
129
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
130
+ 1, 1, max_positions, max_positions
131
+ ),
132
+ persistent=False,
133
+ )
134
+ if device is not None:
135
+ self.bias = self.bias.to(device)
136
+
137
+ def forward(
138
+ self,
139
+ hidden_states: torch.FloatTensor,
140
+ attention_mask: torch.FloatTensor,
141
+ position_ids: torch.LongTensor,
142
+ head_mask: Optional[torch.FloatTensor] = None,
143
+ layer_past: Optional[Cache] = None,
144
+ use_cache: Optional[bool] = False,
145
+ output_attentions: Optional[bool] = False,
146
+ padding_mask: Optional[torch.Tensor] = None,
147
+ cache_position: Optional[torch.LongTensor] = None,
148
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
149
+ ):
150
+ # Apply attention-specific projections and rope
151
+ query, key, value, present = self._attn_projections_and_rope(
152
+ hidden_states=hidden_states,
153
+ position_ids=position_ids,
154
+ layer_past=layer_past,
155
+ use_cache=use_cache,
156
+ position_embeddings=position_embeddings,
157
+ )
158
+
159
+ # Compute attention
160
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
161
+
162
+ # Reshape outputs
163
+ attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_size)
164
+ attn_output = self.dense(attn_output)
165
+
166
+ outputs = (attn_output, present)
167
+ if output_attentions:
168
+ outputs += (attn_weights,)
169
+
170
+ return outputs
171
+
172
+ @classmethod
173
+ def _split_heads(cls, tensor, num_attention_heads, attn_head_size):
174
+ """
175
+ Splits hidden dim into attn_head_size and num_attention_heads
176
+ """
177
+ # tensor: [bs, seq_len, hidden_size]
178
+ new_shape = tensor.size()[:-1] + (num_attention_heads, attn_head_size)
179
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
180
+ tensor = tensor.view(new_shape)
181
+ # -> [bs, num_attention_heads, seq_len, attn_head_size]
182
+ tensor = tensor.permute(0, 2, 1, 3)
183
+ return tensor
184
+
185
+ @classmethod
186
+ def _merge_heads(cls, tensor, num_attention_heads, attn_head_size):
187
+ """
188
+ Merges attn_head_size dim and num_attn_heads dim into hidden dim
189
+ """
190
+ # tensor [bs, num_attention_heads, seq_len, attn_head_size]
191
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
192
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
193
+ tensor = tensor.view(tensor.size(0), tensor.size(1), num_attention_heads * attn_head_size)
194
+ # -> [bs, seq_len, hidden_size]
195
+ return tensor
196
+
197
+ def _attn_projections_and_rope(
198
+ self,
199
+ hidden_states: torch.FloatTensor,
200
+ position_ids: torch.LongTensor,
201
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
202
+ use_cache: Optional[bool] = False,
203
+ cache_position: Optional[torch.LongTensor] = None,
204
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
205
+ ):
206
+ # Compute QKV
207
+ # Attention heads [batch, seq_len, hidden_size]
208
+ # --> [batch, seq_len, (np * 3 * head_size)]
209
+ qkv = self.query_key_value(hidden_states)
210
+
211
+ # [batch, seq_len, (num_heads * 3 * head_size)]
212
+ # --> [batch, seq_len, num_heads, 3 * head_size]
213
+ new_qkv_shape = qkv.size()[:-1] + (self.num_attention_heads, 3 * self.head_size)
214
+ qkv = qkv.view(*new_qkv_shape)
215
+
216
+ # [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size]
217
+ query = qkv[..., : self.head_size].permute(0, 2, 1, 3)
218
+ key = qkv[..., self.head_size : 2 * self.head_size].permute(0, 2, 1, 3)
219
+ value = qkv[..., 2 * self.head_size :].permute(0, 2, 1, 3)
220
+
221
+ # Compute rotary embeddings on rotary_ndims
222
+ query_rot = query[..., : self.rotary_ndims]
223
+ query_pass = query[..., self.rotary_ndims :]
224
+ key_rot = key[..., : self.rotary_ndims]
225
+ key_pass = key[..., self.rotary_ndims :]
226
+
227
+ if position_embeddings is None:
228
+ logger.warning_once(
229
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
230
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
231
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
232
+ "removed and `position_embeddings` will be mandatory."
233
+ )
234
+ cos, sin = self.rotary_emb(value, position_ids)
235
+ else:
236
+ cos, sin = position_embeddings
237
+ query, key = apply_rotary_pos_emb(query_rot, key_rot, cos, sin)
238
+ query = torch.cat((query, query_pass), dim=-1)
239
+ key = torch.cat((key, key_pass), dim=-1)
240
+
241
+ # Cache QKV values
242
+ if layer_past is not None:
243
+ cache_kwargs = {
244
+ "sin": sin,
245
+ "cos": cos,
246
+ "partial_rotation_size": self.rotary_ndims,
247
+ "cache_position": cache_position,
248
+ }
249
+ key, value = layer_past.update(key, value, self.layer_idx, cache_kwargs)
250
+
251
+ return query, key, value, layer_past
252
+
253
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
254
+ # q, k, v: [bs, num_attention_heads, seq_len, attn_head_size]
255
+ # compute causal mask from causal mask buffer
256
+ batch_size, num_attention_heads, query_length, attn_head_size = query.size()
257
+ key_length = key.size(-2)
258
+
259
+ # dynamically increase the causal mask with the key length, if needed.
260
+ if key_length > self.bias.shape[-1]:
261
+ self._init_bias(key_length, device=key.device)
262
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
263
+
264
+ query = query.view(batch_size * num_attention_heads, query_length, attn_head_size)
265
+ key = key.view(batch_size * num_attention_heads, key_length, attn_head_size)
266
+ attn_scores = torch.zeros(
267
+ batch_size * num_attention_heads,
268
+ query_length,
269
+ key_length,
270
+ dtype=query.dtype,
271
+ device=key.device,
272
+ )
273
+ attn_scores = torch.baddbmm(
274
+ attn_scores,
275
+ query,
276
+ key.transpose(1, 2),
277
+ beta=1.0,
278
+ alpha=self.norm_factor,
279
+ )
280
+ attn_scores = attn_scores.view(batch_size, num_attention_heads, query_length, key_length)
281
+
282
+ mask_value = torch.finfo(attn_scores.dtype).min
283
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
284
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
285
+ mask_value = torch.tensor(mask_value, dtype=attn_scores.dtype).to(attn_scores.device)
286
+ attn_scores = torch.where(causal_mask, attn_scores, mask_value)
287
+
288
+ if attention_mask is not None: # no matter the length, we just slice it
289
+ causal_mask = attention_mask[:, :, :, : key.shape[-2]]
290
+ attn_scores = attn_scores + causal_mask
291
+
292
+ attn_weights = nn.functional.softmax(attn_scores, dim=-1)
293
+ attn_weights = attn_weights.to(value.dtype)
294
+
295
+ # Mask heads if we want to
296
+ if head_mask is not None:
297
+ attn_weights = attn_weights * head_mask
298
+
299
+ attn_weights = self.attention_dropout(attn_weights)
300
+
301
+ attn_output = torch.matmul(attn_weights, value)
302
+ return attn_output, attn_weights
303
+
304
+
305
+ class GPTNeoXFlashAttention2(GPTNeoXAttention):
306
+ """
307
+ GPTNeoX flash attention module. This module inherits from `GPTNeoXAttention` as the weights of the module stays
308
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
309
+ flash attention and deal with padding tokens in case the input contains any of them.
310
+ """
311
+
312
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
313
+ def __init__(self, *args, **kwargs):
314
+ super().__init__(*args, **kwargs)
315
+
316
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
317
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
318
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
319
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
320
+
321
+ def forward(
322
+ self,
323
+ hidden_states: torch.FloatTensor,
324
+ attention_mask: torch.FloatTensor,
325
+ position_ids: torch.LongTensor,
326
+ head_mask: Optional[torch.FloatTensor] = None,
327
+ layer_past: Optional[Cache] = None,
328
+ use_cache: Optional[bool] = False,
329
+ output_attentions: Optional[bool] = False,
330
+ cache_position: Optional[torch.LongTensor] = None,
331
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
332
+ ):
333
+ # Apply attention-specific projections and rope
334
+ query, key, value, present = self._attn_projections_and_rope(
335
+ hidden_states=hidden_states,
336
+ position_ids=position_ids,
337
+ layer_past=layer_past,
338
+ use_cache=use_cache,
339
+ cache_position=cache_position,
340
+ position_embeddings=position_embeddings,
341
+ )
342
+
343
+ query_length = query.shape[-2]
344
+
345
+ # GPT-neo-X casts query and key in fp32 to apply rotary embedding in full precision
346
+ target_dtype = value.dtype
347
+ if query.dtype != target_dtype:
348
+ query = query.to(target_dtype)
349
+ if key.dtype != target_dtype:
350
+ key = key.to(target_dtype)
351
+
352
+ # Permute to get the expected shape for Flash Attention
353
+ query = query.permute(0, 2, 1, 3)
354
+ key = key.permute(0, 2, 1, 3)
355
+ value = value.permute(0, 2, 1, 3)
356
+
357
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
358
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
359
+ # cast them back in float16 / bfloat16 just to be sure everything works as expected.
360
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
361
+ input_dtype = query.dtype
362
+ if input_dtype == torch.float32:
363
+ if torch.is_autocast_enabled():
364
+ target_dtype = torch.get_autocast_gpu_dtype()
365
+ # Handle the case where the model is quantized
366
+ elif hasattr(self.config, "_pre_quantization_dtype"):
367
+ target_dtype = self.config._pre_quantization_dtype
368
+ else:
369
+ target_dtype = self.query_key_value.weight.dtype
370
+
371
+ logger.warning_once(
372
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
373
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
374
+ f" {target_dtype}."
375
+ )
376
+
377
+ query = query.to(target_dtype)
378
+ key = key.to(target_dtype)
379
+ value = value.to(target_dtype)
380
+
381
+ attention_dropout = self.config.attention_dropout if self.training else 0.0
382
+
383
+ # Compute attention
384
+ attn_weights = _flash_attention_forward(
385
+ query,
386
+ key,
387
+ value,
388
+ attention_mask,
389
+ query_length,
390
+ dropout=attention_dropout,
391
+ softmax_scale=self.norm_factor,
392
+ is_causal=self.is_causal,
393
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
394
+ )
395
+
396
+ # Reshape outputs
397
+ attn_output = attn_weights.reshape(
398
+ attn_weights.shape[0], attn_weights.shape[1], self.num_attention_heads * self.head_size
399
+ )
400
+ attn_output = self.dense(attn_output)
401
+
402
+ outputs = (attn_output, layer_past)
403
+ if output_attentions:
404
+ outputs += (attn_weights,)
405
+
406
+ return outputs
407
+
408
+
409
+ class GPTNeoXSdpaAttention(GPTNeoXAttention):
410
+ """
411
+ GPTNeoX attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
412
+ `GPTNeoXAttention` as the weights of the module stays untouched. The only changes are on the forward pass
413
+ to adapt to the SDPA API.
414
+ """
415
+
416
+ def __init__(self, config, layer_idx=None):
417
+ super().__init__(config, layer_idx=layer_idx)
418
+
419
+ # SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
420
+ # attn_mask, so we need to call `.contiguous()`. This was fixed in torch==2.2.0.
421
+ # Reference: https://github.com/pytorch/pytorch/issues/112577
422
+ self.require_contiguous_qkv = version.parse(get_torch_version()) < version.parse("2.2.0")
423
+
424
+ def forward(
425
+ self,
426
+ hidden_states: torch.FloatTensor,
427
+ attention_mask: torch.FloatTensor,
428
+ position_ids: torch.LongTensor,
429
+ head_mask: Optional[torch.FloatTensor] = None,
430
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
431
+ use_cache: Optional[bool] = False,
432
+ output_attentions: Optional[bool] = False,
433
+ cache_position: Optional[torch.LongTensor] = None,
434
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
435
+ ):
436
+ if output_attentions or head_mask is not None:
437
+ logger.warning_once(
438
+ "`GPTNeoXSdpaAttention` is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
439
+ "`output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but "
440
+ "specifying the manual implementation will be required from Transformers version v5.0.0 onwards. "
441
+ 'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
442
+ )
443
+ return super().forward(
444
+ hidden_states=hidden_states,
445
+ attention_mask=attention_mask,
446
+ position_ids=position_ids,
447
+ head_mask=head_mask,
448
+ layer_past=layer_past,
449
+ use_cache=use_cache,
450
+ output_attentions=output_attentions,
451
+ cache_position=cache_position,
452
+ )
453
+
454
+ bsz, q_len, _ = hidden_states.size()
455
+
456
+ # Apply attention-specific projections and rope
457
+ query, key, value, present = self._attn_projections_and_rope(
458
+ hidden_states=hidden_states,
459
+ position_ids=position_ids,
460
+ layer_past=layer_past,
461
+ use_cache=use_cache,
462
+ cache_position=cache_position,
463
+ position_embeddings=position_embeddings,
464
+ )
465
+
466
+ causal_mask = attention_mask
467
+ if attention_mask is not None:
468
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
469
+
470
+ # GPT-neo-X casts query and key in fp32 to apply rotary embedding in full precision
471
+ target_dtype = value.dtype
472
+ if query.dtype != target_dtype:
473
+ query = query.to(target_dtype)
474
+ if key.dtype != target_dtype:
475
+ key = key.to(target_dtype)
476
+
477
+ # Avoid torch==2.1.2 specific bug for the memory-efficient backend in SDPA
478
+ if self.require_contiguous_qkv and query.device.type == "cuda" and attention_mask is not None:
479
+ query = query.contiguous()
480
+ key = key.contiguous()
481
+ value = value.contiguous()
482
+
483
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
484
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
485
+ is_causal = True if causal_mask is None and q_len > 1 else False
486
+
487
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
488
+ query=query,
489
+ key=key,
490
+ value=value,
491
+ attn_mask=causal_mask,
492
+ dropout_p=self.attention_dropout.p if self.training else 0.0,
493
+ is_causal=is_causal,
494
+ )
495
+
496
+ # Reshape outputs
497
+ attn_output = attn_output.transpose(1, 2).contiguous()
498
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
499
+
500
+ attn_output = self.dense(attn_output)
501
+
502
+ return attn_output, present, None
503
+
504
+
505
+ def attention_mask_func(attention_scores, ltor_mask):
506
+ attention_scores.masked_fill_(~ltor_mask, torch.finfo(attention_scores.dtype).min)
507
+ return attention_scores
508
+
509
+
510
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->GPTNeoX
511
+ class GPTNeoXRotaryEmbedding(nn.Module):
512
+ def __init__(
513
+ self,
514
+ dim=None,
515
+ max_position_embeddings=2048,
516
+ base=10000,
517
+ device=None,
518
+ scaling_factor=1.0,
519
+ rope_type="default",
520
+ config: Optional[GPTNeoXConfig] = None,
521
+ ):
522
+ super().__init__()
523
+ # TODO (joao): remove the `if` below, only used for BC
524
+ self.rope_kwargs = {}
525
+ if config is None:
526
+ logger.warning_once(
527
+ "`GPTNeoXRotaryEmbedding` can now be fully parameterized by passing the model config through the "
528
+ "`config` argument. All other arguments will be removed in v4.46"
529
+ )
530
+ self.rope_kwargs = {
531
+ "rope_type": rope_type,
532
+ "factor": scaling_factor,
533
+ "dim": dim,
534
+ "base": base,
535
+ "max_position_embeddings": max_position_embeddings,
536
+ }
537
+ self.rope_type = rope_type
538
+ self.max_seq_len_cached = max_position_embeddings
539
+ self.original_max_seq_len = max_position_embeddings
540
+ else:
541
+ # BC: "rope_type" was originally "type"
542
+ if config.rope_scaling is not None:
543
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
544
+ else:
545
+ self.rope_type = "default"
546
+ self.max_seq_len_cached = config.max_position_embeddings
547
+ self.original_max_seq_len = config.max_position_embeddings
548
+
549
+ self.config = config
550
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
551
+
552
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
553
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
554
+ self.original_inv_freq = self.inv_freq
555
+
556
+ def _dynamic_frequency_update(self, position_ids, device):
557
+ """
558
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
559
+ 1 - growing beyond the cached sequence length (allow scaling)
560
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
561
+ """
562
+ seq_len = torch.max(position_ids) + 1
563
+ if seq_len > self.max_seq_len_cached: # growth
564
+ inv_freq, self.attention_scaling = self.rope_init_fn(
565
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
566
+ )
567
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
568
+ self.max_seq_len_cached = seq_len
569
+
570
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
571
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
572
+ self.max_seq_len_cached = self.original_max_seq_len
573
+
574
+ @torch.no_grad()
575
+ def forward(self, x, position_ids):
576
+ if "dynamic" in self.rope_type:
577
+ self._dynamic_frequency_update(position_ids, device=x.device)
578
+
579
+ # Core RoPE block
580
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
581
+ position_ids_expanded = position_ids[:, None, :].float()
582
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
583
+ device_type = x.device.type
584
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
585
+ with torch.autocast(device_type=device_type, enabled=False):
586
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
587
+ emb = torch.cat((freqs, freqs), dim=-1)
588
+ cos = emb.cos()
589
+ sin = emb.sin()
590
+
591
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
592
+ cos = cos * self.attention_scaling
593
+ sin = sin * self.attention_scaling
594
+
595
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
596
+
597
+
598
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->GPTNeoX
599
+ class GPTNeoXLinearScalingRotaryEmbedding(GPTNeoXRotaryEmbedding):
600
+ """GPTNeoXRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
601
+
602
+ def __init__(self, *args, **kwargs):
603
+ logger.warning_once(
604
+ "`GPTNeoXLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
605
+ "`GPTNeoXRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
606
+ )
607
+ kwargs["rope_type"] = "linear"
608
+ super().__init__(*args, **kwargs)
609
+
610
+
611
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->GPTNeoX
612
+ class GPTNeoXDynamicNTKScalingRotaryEmbedding(GPTNeoXRotaryEmbedding):
613
+ """GPTNeoXRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
614
+
615
+ def __init__(self, *args, **kwargs):
616
+ logger.warning_once(
617
+ "`GPTNeoXDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
618
+ "`GPTNeoXRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
619
+ "__init__)."
620
+ )
621
+ kwargs["rope_type"] = "dynamic"
622
+ super().__init__(*args, **kwargs)
623
+
624
+
625
+ def rotate_half(x):
626
+ """Rotates half the hidden dims of the input."""
627
+ x1 = x[..., : x.shape[-1] // 2]
628
+ x2 = x[..., x.shape[-1] // 2 :]
629
+ return torch.cat((-x2, x1), dim=-1)
630
+
631
+
632
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
633
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
634
+ """Applies Rotary Position Embedding to the query and key tensors.
635
+
636
+ Args:
637
+ q (`torch.Tensor`): The query tensor.
638
+ k (`torch.Tensor`): The key tensor.
639
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
640
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
641
+ position_ids (`torch.Tensor`, *optional*):
642
+ Deprecated and unused.
643
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
644
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
645
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
646
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
647
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
648
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
649
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
650
+ Returns:
651
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
652
+ """
653
+ cos = cos.unsqueeze(unsqueeze_dim)
654
+ sin = sin.unsqueeze(unsqueeze_dim)
655
+ q_embed = (q * cos) + (rotate_half(q) * sin)
656
+ k_embed = (k * cos) + (rotate_half(k) * sin)
657
+ return q_embed, k_embed
658
+
659
+
660
+ class GPTNeoXMLP(nn.Module):
661
+ def __init__(self, config):
662
+ super().__init__()
663
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size)
664
+ self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size)
665
+ self.act = ACT2FN[config.hidden_act]
666
+
667
+ def forward(self, hidden_states):
668
+ hidden_states = self.dense_h_to_4h(hidden_states)
669
+ hidden_states = self.act(hidden_states)
670
+ hidden_states = self.dense_4h_to_h(hidden_states)
671
+ return hidden_states
672
+
673
+
674
+ GPT_NEOX_ATTENTION_CLASSES = {
675
+ "eager": GPTNeoXAttention,
676
+ "flash_attention_2": GPTNeoXFlashAttention2,
677
+ "sdpa": GPTNeoXSdpaAttention,
678
+ }
679
+
680
+
681
+ class GPTNeoXLayer(nn.Module):
682
+ def __init__(self, config, layer_idx):
683
+ super().__init__()
684
+ self.use_parallel_residual = config.use_parallel_residual
685
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
686
+ self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
687
+ self.post_attention_dropout = nn.Dropout(config.hidden_dropout)
688
+ self.post_mlp_dropout = nn.Dropout(config.hidden_dropout)
689
+ self.attention = GPT_NEOX_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
690
+ self.mlp = GPTNeoXMLP(config)
691
+
692
+ def forward(
693
+ self,
694
+ hidden_states: Optional[torch.FloatTensor],
695
+ attention_mask: Optional[torch.FloatTensor] = None,
696
+ position_ids: Optional[torch.LongTensor] = None,
697
+ head_mask: Optional[torch.FloatTensor] = None,
698
+ use_cache: Optional[bool] = False,
699
+ layer_past: Optional[Cache] = None,
700
+ output_attentions: Optional[bool] = False,
701
+ cache_position: Optional[torch.LongTensor] = None,
702
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
703
+ ):
704
+ attention_layer_outputs = self.attention(
705
+ self.input_layernorm(hidden_states),
706
+ attention_mask=attention_mask,
707
+ position_ids=position_ids,
708
+ layer_past=layer_past,
709
+ head_mask=head_mask,
710
+ use_cache=use_cache,
711
+ output_attentions=output_attentions,
712
+ cache_position=cache_position,
713
+ position_embeddings=position_embeddings,
714
+ )
715
+ attn_output = attention_layer_outputs[0] # output_attn: attn_output, present, (attn_weights)
716
+ attn_output = self.post_attention_dropout(attn_output)
717
+ outputs = attention_layer_outputs[1:]
718
+
719
+ if self.use_parallel_residual:
720
+ # pseudocode:
721
+ # x = x + attn(ln1(x)) + mlp(ln2(x))
722
+ mlp_output = self.mlp(self.post_attention_layernorm(hidden_states))
723
+ mlp_output = self.post_mlp_dropout(mlp_output)
724
+ hidden_states = mlp_output + attn_output + hidden_states
725
+ else:
726
+ # pseudocode:
727
+ # x = x + attn(ln1(x))
728
+ # x = x + mlp(ln2(x))
729
+ attn_output = attn_output + hidden_states
730
+ mlp_output = self.mlp(self.post_attention_layernorm(attn_output))
731
+ mlp_output = self.post_mlp_dropout(mlp_output)
732
+ hidden_states = mlp_output + attn_output
733
+
734
+ if use_cache:
735
+ outputs = (hidden_states,) + outputs # hidden_states, present, (attn_weights)
736
+ else:
737
+ outputs = (hidden_states,) + outputs[1:] # hidden_states, (attn_weights)
738
+
739
+ return outputs
740
+
741
+
742
+ GPT_NEOX_START_DOCSTRING = r"""
743
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
744
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
745
+ behavior.
746
+
747
+ Parameters:
748
+ config ([`~GPTNeoXConfig`]): Model configuration class with all the parameters of the model.
749
+ Initializing with a config file does not load the weights associated with the model, only the
750
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
751
+ """
752
+
753
+ GPT_NEOX_INPUTS_DOCSTRING = r"""
754
+ Args:
755
+ input_ids (`torch.LongTensor` of shape `({0})`):
756
+ Indices of input sequence tokens in the vocabulary.
757
+
758
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
759
+ [`PreTrainedTokenizer.__call__`] for details.
760
+
761
+ [What are input IDs?](../glossary#input-ids)
762
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
763
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
764
+
765
+ - 1 for tokens that are **not masked**,
766
+ - 0 for tokens that are **masked**.
767
+
768
+ [What are attention masks?](../glossary#attention-mask)
769
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
770
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
771
+ config.n_positions - 1]`.
772
+
773
+ [What are position IDs?](../glossary#position-ids)
774
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
775
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
776
+
777
+ - 1 indicates the head is **not masked**,
778
+ - 0 indicates the head is **masked**.
779
+
780
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
781
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
782
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
783
+ model's internal embedding lookup matrix.
784
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
785
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
786
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
787
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
788
+
789
+ Two formats are allowed:
790
+ - a [`~cache_utils.Cache`] instance, see our
791
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
792
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
793
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
794
+ cache format.
795
+
796
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
797
+ legacy cache format will be returned.
798
+
799
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
800
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
801
+ of shape `(batch_size, sequence_length)`.
802
+ output_attentions (`bool`, *optional*):
803
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
804
+ tensors for more detail.
805
+ output_hidden_states (`bool`, *optional*):
806
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
807
+ more detail.
808
+ return_dict (`bool`, *optional*):
809
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
810
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
811
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
812
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
813
+ the complete sequence length.
814
+ """
815
+
816
+
817
+ @add_start_docstrings(
818
+ "The bare GPTNeoX Model transformer outputting raw hidden-states without any specific head on top.",
819
+ GPT_NEOX_START_DOCSTRING,
820
+ )
821
+ class GPTNeoXModel(GPTNeoXPreTrainedModel):
822
+ def __init__(self, config):
823
+ super().__init__(config)
824
+ self.config = config
825
+
826
+ self.embed_in = nn.Embedding(config.vocab_size, config.hidden_size)
827
+ self.emb_dropout = nn.Dropout(config.hidden_dropout)
828
+ self.layers = nn.ModuleList([GPTNeoXLayer(config, i) for i in range(config.num_hidden_layers)])
829
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
830
+ self.rotary_emb = GPTNeoXRotaryEmbedding(config=config)
831
+
832
+ self._attn_implementation = config._attn_implementation
833
+
834
+ self.gradient_checkpointing = False
835
+
836
+ # Initialize weights and apply final processing
837
+ self.post_init()
838
+
839
+ def get_input_embeddings(self):
840
+ return self.embed_in
841
+
842
+ def set_input_embeddings(self, value):
843
+ self.embed_in = value
844
+
845
+ @add_start_docstrings_to_model_forward(GPT_NEOX_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
846
+ @add_code_sample_docstrings(
847
+ checkpoint=_CHECKPOINT_FOR_DOC,
848
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
849
+ output_type=BaseModelOutputWithPast,
850
+ config_class=_CONFIG_FOR_DOC,
851
+ )
852
+ def forward(
853
+ self,
854
+ input_ids: Optional[torch.LongTensor] = None,
855
+ attention_mask: Optional[torch.FloatTensor] = None,
856
+ position_ids: Optional[torch.LongTensor] = None,
857
+ head_mask: Optional[torch.FloatTensor] = None,
858
+ inputs_embeds: Optional[torch.FloatTensor] = None,
859
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.FloatTensor]]]] = None,
860
+ use_cache: Optional[bool] = None,
861
+ output_attentions: Optional[bool] = None,
862
+ output_hidden_states: Optional[bool] = None,
863
+ return_dict: Optional[bool] = None,
864
+ cache_position: Optional[torch.LongTensor] = None,
865
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
866
+ r"""
867
+ use_cache (`bool`, *optional*):
868
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
869
+ `past_key_values`).
870
+ """
871
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
872
+ output_hidden_states = (
873
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
874
+ )
875
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
876
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
877
+
878
+ if (input_ids is None) ^ (inputs_embeds is not None):
879
+ raise ValueError(
880
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
881
+ )
882
+
883
+ if self.gradient_checkpointing and self.training:
884
+ if use_cache:
885
+ logger.warning_once(
886
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
887
+ )
888
+ use_cache = False
889
+
890
+ if inputs_embeds is None:
891
+ inputs_embeds = self.embed_in(input_ids)
892
+
893
+ # kept for BC (non `Cache` `past_key_values` inputs)
894
+ return_legacy_cache = False
895
+ if use_cache and not isinstance(past_key_values, Cache):
896
+ return_legacy_cache = True
897
+ if past_key_values is None:
898
+ past_key_values = DynamicCache()
899
+ else:
900
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
901
+ logger.warning_once(
902
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
903
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
904
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
905
+ )
906
+
907
+ seq_length = inputs_embeds.shape[1]
908
+ if cache_position is None:
909
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
910
+ cache_position = torch.arange(past_seen_tokens, past_seen_tokens + seq_length, device=inputs_embeds.device)
911
+
912
+ if position_ids is None:
913
+ position_ids = cache_position.unsqueeze(0)
914
+
915
+ causal_mask = self._update_causal_mask(
916
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
917
+ )
918
+
919
+ # Prepare head mask if needed
920
+ # 1.0 in head_mask indicate we keep the head
921
+ # attention_probs has shape bsz x n_heads x N x N
922
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
923
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
924
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
925
+ hidden_states = self.emb_dropout(inputs_embeds)
926
+
927
+ # create position embeddings to be shared across the decoder layers
928
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
929
+
930
+ next_decoder_cache = None
931
+ all_attentions = () if output_attentions else None
932
+ all_hidden_states = () if output_hidden_states else None
933
+ for i, layer in enumerate(
934
+ self.layers,
935
+ ):
936
+ if output_hidden_states:
937
+ all_hidden_states = all_hidden_states + (hidden_states,)
938
+
939
+ if self.gradient_checkpointing and self.training:
940
+ outputs = self._gradient_checkpointing_func(
941
+ layer.__call__,
942
+ hidden_states,
943
+ causal_mask,
944
+ position_ids,
945
+ head_mask[i],
946
+ use_cache,
947
+ None,
948
+ output_attentions,
949
+ cache_position,
950
+ position_embeddings,
951
+ )
952
+ else:
953
+ outputs = layer(
954
+ hidden_states,
955
+ attention_mask=causal_mask,
956
+ position_ids=position_ids,
957
+ head_mask=head_mask[i],
958
+ layer_past=past_key_values,
959
+ use_cache=use_cache,
960
+ output_attentions=output_attentions,
961
+ cache_position=cache_position,
962
+ position_embeddings=position_embeddings,
963
+ )
964
+ hidden_states = outputs[0]
965
+ if use_cache is True:
966
+ next_decoder_cache = outputs[1]
967
+ if output_attentions:
968
+ all_attentions = all_attentions + (outputs[2 if use_cache else 1],)
969
+
970
+ hidden_states = self.final_layer_norm(hidden_states)
971
+ # Add last hidden state
972
+ if output_hidden_states:
973
+ all_hidden_states = all_hidden_states + (hidden_states,)
974
+
975
+ next_cache = next_decoder_cache if use_cache else None
976
+ if return_legacy_cache:
977
+ next_cache = next_cache.to_legacy_cache()
978
+
979
+ if not return_dict:
980
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_attentions] if v is not None)
981
+
982
+ return BaseModelOutputWithPast(
983
+ last_hidden_state=hidden_states,
984
+ past_key_values=next_cache,
985
+ hidden_states=all_hidden_states,
986
+ attentions=all_attentions,
987
+ )
988
+
989
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
990
+ def _update_causal_mask(
991
+ self,
992
+ attention_mask: torch.Tensor,
993
+ input_tensor: torch.Tensor,
994
+ cache_position: torch.Tensor,
995
+ past_key_values: Cache,
996
+ output_attentions: bool,
997
+ ):
998
+ if self.config._attn_implementation == "flash_attention_2":
999
+ if attention_mask is not None and 0.0 in attention_mask:
1000
+ return attention_mask
1001
+ return None
1002
+
1003
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1004
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1005
+ # to infer the attention mask.
1006
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1007
+ using_static_cache = isinstance(past_key_values, StaticCache)
1008
+
1009
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1010
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1011
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1012
+ attention_mask,
1013
+ inputs_embeds=input_tensor,
1014
+ past_key_values_length=past_seen_tokens,
1015
+ is_training=self.training,
1016
+ ):
1017
+ return None
1018
+
1019
+ dtype, device = input_tensor.dtype, input_tensor.device
1020
+ sequence_length = input_tensor.shape[1]
1021
+ if using_static_cache:
1022
+ target_length = past_key_values.get_max_length()
1023
+ else:
1024
+ target_length = (
1025
+ attention_mask.shape[-1]
1026
+ if isinstance(attention_mask, torch.Tensor)
1027
+ else past_seen_tokens + sequence_length + 1
1028
+ )
1029
+
1030
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1031
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1032
+ attention_mask,
1033
+ sequence_length=sequence_length,
1034
+ target_length=target_length,
1035
+ dtype=dtype,
1036
+ device=device,
1037
+ cache_position=cache_position,
1038
+ batch_size=input_tensor.shape[0],
1039
+ )
1040
+
1041
+ if (
1042
+ self.config._attn_implementation == "sdpa"
1043
+ and attention_mask is not None
1044
+ and attention_mask.device.type == "cuda"
1045
+ and not output_attentions
1046
+ ):
1047
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1048
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1049
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1050
+ min_dtype = torch.finfo(dtype).min
1051
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1052
+
1053
+ return causal_mask
1054
+
1055
+ @staticmethod
1056
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._prepare_4d_causal_attention_mask_with_cache_position
1057
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1058
+ attention_mask: torch.Tensor,
1059
+ sequence_length: int,
1060
+ target_length: int,
1061
+ dtype: torch.dtype,
1062
+ device: torch.device,
1063
+ cache_position: torch.Tensor,
1064
+ batch_size: int,
1065
+ ):
1066
+ """
1067
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1068
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1069
+
1070
+ Args:
1071
+ attention_mask (`torch.Tensor`):
1072
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1073
+ `(batch_size, 1, query_length, key_value_length)`.
1074
+ sequence_length (`int`):
1075
+ The sequence length being processed.
1076
+ target_length (`int`):
1077
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1078
+ to account for the 0 padding, the part of the cache that is not filled yet.
1079
+ dtype (`torch.dtype`):
1080
+ The dtype to use for the 4D attention mask.
1081
+ device (`torch.device`):
1082
+ The device to plcae the 4D attention mask on.
1083
+ cache_position (`torch.Tensor`):
1084
+ Indices depicting the position of the input sequence tokens in the sequence.
1085
+ batch_size (`torch.Tensor`):
1086
+ Batch size.
1087
+ """
1088
+ if attention_mask is not None and attention_mask.dim() == 4:
1089
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1090
+ causal_mask = attention_mask
1091
+ else:
1092
+ min_dtype = torch.finfo(dtype).min
1093
+ causal_mask = torch.full(
1094
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1095
+ )
1096
+ if sequence_length != 1:
1097
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1098
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1099
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1100
+ if attention_mask is not None:
1101
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1102
+ mask_length = attention_mask.shape[-1]
1103
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1104
+ padding_mask = padding_mask == 0
1105
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1106
+ padding_mask, min_dtype
1107
+ )
1108
+
1109
+ return causal_mask
1110
+
1111
+
1112
+ @add_start_docstrings(
1113
+ """GPTNeoX Model with a `language modeling` head on top for CLM fine-tuning.""", GPT_NEOX_START_DOCSTRING
1114
+ )
1115
+ class GPTNeoXForCausalLM(GPTNeoXPreTrainedModel, GenerationMixin):
1116
+ _tied_weights_keys = ["embed_out.weight"]
1117
+
1118
+ def __init__(self, config):
1119
+ super().__init__(config)
1120
+
1121
+ self.gpt_neox = GPTNeoXModel(config)
1122
+ self.embed_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1123
+
1124
+ # Initialize weights and apply final processing
1125
+ self.post_init()
1126
+
1127
+ def get_output_embeddings(self):
1128
+ return self.embed_out
1129
+
1130
+ def set_output_embeddings(self, new_embeddings):
1131
+ self.embed_out = new_embeddings
1132
+
1133
+ @add_start_docstrings_to_model_forward(GPT_NEOX_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1134
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1135
+ def forward(
1136
+ self,
1137
+ input_ids: Optional[torch.LongTensor] = None,
1138
+ attention_mask: Optional[torch.FloatTensor] = None,
1139
+ position_ids: Optional[torch.LongTensor] = None,
1140
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1141
+ head_mask: Optional[torch.FloatTensor] = None,
1142
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.FloatTensor]]]] = None,
1143
+ labels: Optional[torch.LongTensor] = None,
1144
+ use_cache: Optional[bool] = None,
1145
+ output_attentions: Optional[bool] = None,
1146
+ output_hidden_states: Optional[bool] = None,
1147
+ return_dict: Optional[bool] = None,
1148
+ cache_position: Optional[torch.LongTensor] = None,
1149
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1150
+ r"""
1151
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1152
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1153
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1154
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
1155
+ use_cache (`bool`, *optional*):
1156
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1157
+ `past_key_values`).
1158
+
1159
+ Returns:
1160
+
1161
+ Example:
1162
+
1163
+ ```python
1164
+ >>> from transformers import AutoTokenizer, GPTNeoXForCausalLM, GPTNeoXConfig
1165
+ >>> import torch
1166
+
1167
+ >>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
1168
+ >>> config = GPTNeoXConfig.from_pretrained("EleutherAI/gpt-neox-20b")
1169
+ >>> config.is_decoder = True
1170
+ >>> model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b", config=config)
1171
+
1172
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1173
+ >>> outputs = model(**inputs)
1174
+
1175
+ >>> prediction_logits = outputs.logits
1176
+ ```"""
1177
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1178
+
1179
+ outputs = self.gpt_neox(
1180
+ input_ids,
1181
+ attention_mask=attention_mask,
1182
+ position_ids=position_ids,
1183
+ head_mask=head_mask,
1184
+ inputs_embeds=inputs_embeds,
1185
+ past_key_values=past_key_values,
1186
+ use_cache=use_cache,
1187
+ output_attentions=output_attentions,
1188
+ output_hidden_states=output_hidden_states,
1189
+ return_dict=return_dict,
1190
+ cache_position=cache_position,
1191
+ )
1192
+
1193
+ hidden_states = outputs[0]
1194
+ lm_logits = self.embed_out(hidden_states)
1195
+
1196
+ lm_loss = None
1197
+ if labels is not None:
1198
+ # move labels to correct device to enable model parallelism
1199
+ labels = labels.to(lm_logits.device)
1200
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1201
+ shift_logits = lm_logits[:, :-1, :].contiguous()
1202
+ labels = labels[:, 1:].contiguous()
1203
+ loss_fct = CrossEntropyLoss()
1204
+ lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), labels.view(-1))
1205
+
1206
+ if not return_dict:
1207
+ output = (lm_logits,) + outputs[1:]
1208
+ return ((lm_loss,) + output) if lm_loss is not None else output
1209
+
1210
+ return CausalLMOutputWithPast(
1211
+ loss=lm_loss,
1212
+ logits=lm_logits,
1213
+ past_key_values=outputs.past_key_values,
1214
+ hidden_states=outputs.hidden_states,
1215
+ attentions=outputs.attentions,
1216
+ )
1217
+
1218
+ def _reorder_cache(self, past_key_values, beam_idx):
1219
+ reordered_past = ()
1220
+ for layer_past in past_key_values:
1221
+ reordered_past += (
1222
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
1223
+ + layer_past[2:],
1224
+ )
1225
+ return reordered_past
1226
+
1227
+
1228
+ @add_start_docstrings(
1229
+ """
1230
+ The GPTNeoX Model transformer with a sequence classification head on top (linear layer).
1231
+
1232
+ [`GPTNeoXForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1233
+ (e.g. GPT-1) do.
1234
+
1235
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1236
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1237
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1238
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1239
+ each row of the batch).
1240
+ """,
1241
+ GPT_NEOX_START_DOCSTRING,
1242
+ )
1243
+ class GPTNeoXForSequenceClassification(GPTNeoXPreTrainedModel):
1244
+ def __init__(self, config):
1245
+ super().__init__(config)
1246
+ self.num_labels = config.num_labels
1247
+ self.gpt_neox = GPTNeoXModel(config)
1248
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1249
+
1250
+ # Initialize weights and apply final processing
1251
+ self.post_init()
1252
+
1253
+ @add_start_docstrings_to_model_forward(GPT_NEOX_INPUTS_DOCSTRING)
1254
+ @add_code_sample_docstrings(
1255
+ checkpoint=_CHECKPOINT_FOR_DOC,
1256
+ output_type=SequenceClassifierOutputWithPast,
1257
+ config_class=_CONFIG_FOR_DOC,
1258
+ )
1259
+ def forward(
1260
+ self,
1261
+ input_ids: Optional[torch.LongTensor] = None,
1262
+ attention_mask: Optional[torch.FloatTensor] = None,
1263
+ position_ids: Optional[torch.LongTensor] = None,
1264
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1265
+ head_mask: Optional[torch.FloatTensor] = None,
1266
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.FloatTensor]]]] = None,
1267
+ labels: Optional[torch.LongTensor] = None,
1268
+ use_cache: Optional[bool] = None,
1269
+ output_attentions: Optional[bool] = None,
1270
+ output_hidden_states: Optional[bool] = None,
1271
+ return_dict: Optional[bool] = None,
1272
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
1273
+ r"""
1274
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1275
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1276
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1277
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1278
+ """
1279
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1280
+
1281
+ outputs = self.gpt_neox(
1282
+ input_ids,
1283
+ attention_mask=attention_mask,
1284
+ position_ids=position_ids,
1285
+ head_mask=head_mask,
1286
+ inputs_embeds=inputs_embeds,
1287
+ past_key_values=past_key_values,
1288
+ use_cache=use_cache,
1289
+ output_attentions=output_attentions,
1290
+ output_hidden_states=output_hidden_states,
1291
+ return_dict=return_dict,
1292
+ )
1293
+ hidden_states = outputs[0]
1294
+ logits = self.score(hidden_states)
1295
+
1296
+ if input_ids is not None:
1297
+ batch_size, sequence_length = input_ids.shape[:2]
1298
+ else:
1299
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1300
+
1301
+ if self.config.pad_token_id is None and batch_size != 1:
1302
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1303
+ if self.config.pad_token_id is None:
1304
+ sequence_lengths = -1
1305
+ else:
1306
+ if input_ids is not None:
1307
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1308
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1309
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1310
+ sequence_lengths = sequence_lengths.to(logits.device)
1311
+ else:
1312
+ sequence_lengths = -1
1313
+ logger.warning_once(
1314
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1315
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1316
+ )
1317
+
1318
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1319
+
1320
+ loss = None
1321
+ if labels is not None:
1322
+ labels = labels.to(logits.device)
1323
+ if self.config.problem_type is None:
1324
+ if self.num_labels == 1:
1325
+ self.config.problem_type = "regression"
1326
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1327
+ self.config.problem_type = "single_label_classification"
1328
+ else:
1329
+ self.config.problem_type = "multi_label_classification"
1330
+
1331
+ if self.config.problem_type == "regression":
1332
+ loss_fct = MSELoss()
1333
+ if self.num_labels == 1:
1334
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1335
+ else:
1336
+ loss = loss_fct(pooled_logits, labels)
1337
+ elif self.config.problem_type == "single_label_classification":
1338
+ loss_fct = CrossEntropyLoss()
1339
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1340
+ elif self.config.problem_type == "multi_label_classification":
1341
+ loss_fct = BCEWithLogitsLoss()
1342
+ loss = loss_fct(pooled_logits, labels)
1343
+ if not return_dict:
1344
+ output = (pooled_logits,) + outputs[1:]
1345
+ return ((loss,) + output) if loss is not None else output
1346
+
1347
+ return SequenceClassifierOutputWithPast(
1348
+ loss=loss,
1349
+ logits=pooled_logits,
1350
+ past_key_values=outputs.past_key_values,
1351
+ hidden_states=outputs.hidden_states,
1352
+ attentions=outputs.attentions,
1353
+ )
1354
+
1355
+
1356
+ class GPTNeoXForTokenClassification(GPTNeoXPreTrainedModel):
1357
+ def __init__(self, config):
1358
+ super().__init__(config)
1359
+ self.num_labels = config.num_labels
1360
+
1361
+ self.gpt_neox = GPTNeoXModel(config)
1362
+ self.dropout = nn.Dropout(config.classifier_dropout)
1363
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1364
+
1365
+ # Initialize weights and apply final processing
1366
+ self.post_init()
1367
+
1368
+ @add_start_docstrings_to_model_forward(GPT_NEOX_INPUTS_DOCSTRING)
1369
+ @add_code_sample_docstrings(
1370
+ checkpoint="LarsJonasson/pythia-410m-deduped-sft-swedish",
1371
+ output_type=TokenClassifierOutput,
1372
+ config_class=_CONFIG_FOR_DOC,
1373
+ expected_loss=0.25,
1374
+ )
1375
+ def forward(
1376
+ self,
1377
+ input_ids: Optional[torch.LongTensor] = None,
1378
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.Tensor]]]] = None,
1379
+ attention_mask: Optional[torch.FloatTensor] = None,
1380
+ token_type_ids: Optional[torch.LongTensor] = None,
1381
+ position_ids: Optional[torch.LongTensor] = None,
1382
+ head_mask: Optional[torch.FloatTensor] = None,
1383
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1384
+ labels: Optional[torch.LongTensor] = None,
1385
+ use_cache: Optional[bool] = None,
1386
+ output_attentions: Optional[bool] = None,
1387
+ output_hidden_states: Optional[bool] = None,
1388
+ return_dict: Optional[bool] = None,
1389
+ ) -> Union[Tuple, TokenClassifierOutput]:
1390
+ r"""
1391
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1392
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1393
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1394
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1395
+ """
1396
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1397
+
1398
+ outputs = self.gpt_neox(
1399
+ input_ids,
1400
+ past_key_values=past_key_values,
1401
+ attention_mask=attention_mask,
1402
+ position_ids=position_ids,
1403
+ head_mask=head_mask,
1404
+ inputs_embeds=inputs_embeds,
1405
+ use_cache=use_cache,
1406
+ output_attentions=output_attentions,
1407
+ output_hidden_states=output_hidden_states,
1408
+ return_dict=return_dict,
1409
+ )
1410
+
1411
+ hidden_states = outputs[0]
1412
+ hidden_states = self.dropout(hidden_states)
1413
+ logits = self.classifier(hidden_states)
1414
+
1415
+ loss = None
1416
+ if labels is not None:
1417
+ labels = labels.to(logits.device)
1418
+ loss_fct = CrossEntropyLoss()
1419
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1420
+
1421
+ if not return_dict:
1422
+ output = (logits,) + outputs[2:]
1423
+ return ((loss,) + output) if loss is not None else output
1424
+
1425
+ return TokenClassifierOutput(
1426
+ loss=loss,
1427
+ logits=logits,
1428
+ hidden_states=outputs.hidden_states,
1429
+ attentions=outputs.attentions,
1430
+ )
1431
+
1432
+
1433
+ @add_start_docstrings(
1434
+ """
1435
+ The GPT-NeoX Model transformer with a span classification head on top for extractive question-answering tasks like
1436
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1437
+ """,
1438
+ GPT_NEOX_START_DOCSTRING,
1439
+ )
1440
+ class GPTNeoXForQuestionAnswering(GPTNeoXPreTrainedModel):
1441
+ def __init__(self, config):
1442
+ super().__init__(config)
1443
+ self.num_labels = config.num_labels
1444
+ self.gpt_neox = GPTNeoXModel(config)
1445
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1446
+
1447
+ # Initialize weights and apply final processing
1448
+ self.post_init()
1449
+
1450
+ @add_start_docstrings_to_model_forward(GPT_NEOX_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1451
+ @add_code_sample_docstrings(
1452
+ checkpoint=_CHECKPOINT_FOR_DOC,
1453
+ output_type=QuestionAnsweringModelOutput,
1454
+ config_class=_CONFIG_FOR_DOC,
1455
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
1456
+ )
1457
+ def forward(
1458
+ self,
1459
+ input_ids: Optional[torch.LongTensor] = None,
1460
+ attention_mask: Optional[torch.FloatTensor] = None,
1461
+ token_type_ids: Optional[torch.LongTensor] = None,
1462
+ position_ids: Optional[torch.LongTensor] = None,
1463
+ head_mask: Optional[torch.FloatTensor] = None,
1464
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1465
+ start_positions: Optional[torch.LongTensor] = None,
1466
+ end_positions: Optional[torch.LongTensor] = None,
1467
+ output_attentions: Optional[bool] = None,
1468
+ output_hidden_states: Optional[bool] = None,
1469
+ return_dict: Optional[bool] = None,
1470
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1471
+ r"""
1472
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1473
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1474
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1475
+ are not taken into account for computing the loss.
1476
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1477
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1478
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1479
+ are not taken into account for computing the loss.
1480
+ """
1481
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1482
+
1483
+ outputs = self.gpt_neox(
1484
+ input_ids,
1485
+ attention_mask=attention_mask,
1486
+ position_ids=position_ids,
1487
+ head_mask=head_mask,
1488
+ inputs_embeds=inputs_embeds,
1489
+ output_attentions=output_attentions,
1490
+ output_hidden_states=output_hidden_states,
1491
+ return_dict=return_dict,
1492
+ )
1493
+
1494
+ sequence_output = outputs[0]
1495
+
1496
+ logits = self.qa_outputs(sequence_output)
1497
+ start_logits, end_logits = logits.split(1, dim=-1)
1498
+ start_logits = start_logits.squeeze(-1).contiguous()
1499
+ end_logits = end_logits.squeeze(-1).contiguous()
1500
+
1501
+ total_loss = None
1502
+ if start_positions is not None and end_positions is not None:
1503
+ # If we are on multi-GPU, split add a dimension
1504
+ if len(start_positions.size()) > 1:
1505
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1506
+ if len(end_positions.size()) > 1:
1507
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1508
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1509
+ ignored_index = start_logits.size(1)
1510
+ start_positions = start_positions.clamp(0, ignored_index)
1511
+ end_positions = end_positions.clamp(0, ignored_index)
1512
+
1513
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1514
+ start_loss = loss_fct(start_logits, start_positions)
1515
+ end_loss = loss_fct(end_logits, end_positions)
1516
+ total_loss = (start_loss + end_loss) / 2
1517
+
1518
+ if not return_dict:
1519
+ output = (start_logits, end_logits) + outputs[2:]
1520
+ return ((total_loss,) + output) if total_loss is not None else output
1521
+
1522
+ return QuestionAnsweringModelOutput(
1523
+ loss=total_loss,
1524
+ start_logits=start_logits,
1525
+ end_logits=end_logits,
1526
+ hidden_states=outputs.hidden_states,
1527
+ attentions=outputs.attentions,
1528
+ )
tokenization_gpt_neox_fast.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization classes for GPTNeoX."""
16
+
17
+ import json
18
+ from typing import List, Optional, Tuple
19
+
20
+ from tokenizers import pre_tokenizers, processors
21
+
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
29
+
30
+
31
+ class GPTNeoXTokenizerFast(PreTrainedTokenizerFast):
32
+ """
33
+ Construct a "fast" GPT-NeoX-20B tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
34
+ Byte-Pair-Encoding.
35
+
36
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
37
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
38
+
39
+ ```python
40
+ >>> from transformers import GPTNeoXTokenizerFast
41
+
42
+ >>> tokenizer = GPTNeoXTokenizerFast.from_pretrained("openai-community/gpt2")
43
+ >>> tokenizer("Hello world")["input_ids"]
44
+ [15496, 995]
45
+
46
+ >>> tokenizer(" Hello world")["input_ids"]
47
+ [18435, 995]
48
+ ```
49
+
50
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
51
+ the model was not pretrained this way, it might yield a decrease in performance.
52
+
53
+ <Tip>
54
+
55
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
56
+
57
+ </Tip>
58
+
59
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
60
+ refer to this superclass for more information regarding those methods.
61
+
62
+ Args:
63
+ vocab_file (`str`):
64
+ Path to the vocabulary file.
65
+ merges_file (`str`):
66
+ Path to the merges file.
67
+ errors (`str`, *optional*, defaults to `"replace"`):
68
+ Paradigm to follow when decoding bytes to UTF-8. See
69
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
70
+ unk_token (`str`, *optional*, defaults to `<|endoftext|>`):
71
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
72
+ token instead.
73
+ bos_token (`str`, *optional*, defaults to `<|endoftext|>`):
74
+ The beginning of sequence token.
75
+ eos_token (`str`, *optional*, defaults to `<|endoftext|>`):
76
+ The end of sequence token.
77
+ pad_token (`str`, *optional*):
78
+ Token for padding a sequence.
79
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
80
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
81
+ other word. (GPTNeoX tokenizer detect beginning of words by the preceding space).
82
+ add_bos_token (`bool`, *optional*, defaults to `False`):
83
+ Whether or not to add a `bos_token` at the start of sequences.
84
+ add_eos_token (`bool`, *optional*, defaults to `False`):
85
+ Whether or not to add an `eos_token` at the end of sequences.
86
+ trim_offsets (`bool`, *optional*, defaults to `True`):
87
+ Whether or not the post-processing step should trim offsets to avoid including whitespaces.
88
+ """
89
+
90
+ vocab_files_names = VOCAB_FILES_NAMES
91
+ model_input_names = ["input_ids", "attention_mask"]
92
+
93
+ def __init__(
94
+ self,
95
+ vocab_file=None,
96
+ merges_file=None,
97
+ tokenizer_file=None,
98
+ unk_token="<|endoftext|>",
99
+ bos_token="<|endoftext|>",
100
+ eos_token="<|endoftext|>",
101
+ pad_token=None,
102
+ add_bos_token=False,
103
+ add_eos_token=False,
104
+ add_prefix_space=False,
105
+ **kwargs,
106
+ ):
107
+ super().__init__(
108
+ vocab_file,
109
+ merges_file,
110
+ tokenizer_file=tokenizer_file,
111
+ unk_token=unk_token,
112
+ bos_token=bos_token,
113
+ eos_token=eos_token,
114
+ pad_token=pad_token,
115
+ add_bos_token=add_bos_token,
116
+ add_eos_token=add_eos_token,
117
+ add_prefix_space=add_prefix_space,
118
+ **kwargs,
119
+ )
120
+
121
+ self._add_bos_token = add_bos_token
122
+ self._add_eos_token = add_eos_token
123
+ self.update_post_processor()
124
+
125
+ pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
126
+ if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
127
+ pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
128
+ pre_tok_state["add_prefix_space"] = add_prefix_space
129
+ self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
130
+
131
+ self.add_prefix_space = add_prefix_space
132
+
133
+ @property
134
+ def add_eos_token(self):
135
+ return self._add_eos_token
136
+
137
+ @property
138
+ def add_bos_token(self):
139
+ return self._add_bos_token
140
+
141
+ @add_eos_token.setter
142
+ def add_eos_token(self, value):
143
+ self._add_eos_token = value
144
+ self.update_post_processor()
145
+
146
+ @add_bos_token.setter
147
+ def add_bos_token(self, value):
148
+ self._add_bos_token = value
149
+ self.update_post_processor()
150
+
151
+ # Copied from transformers.models.llama.tokenization_llama_fast.LlamaTokenizerFast.update_post_processor
152
+ def update_post_processor(self):
153
+ """
154
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
155
+ """
156
+ bos = self.bos_token
157
+ bos_token_id = self.bos_token_id
158
+ if bos is None and self.add_bos_token:
159
+ raise ValueError("add_bos_token = True but bos_token = None")
160
+
161
+ eos = self.eos_token
162
+ eos_token_id = self.eos_token_id
163
+ if eos is None and self.add_eos_token:
164
+ raise ValueError("add_eos_token = True but eos_token = None")
165
+
166
+ single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
167
+ pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
168
+
169
+ special_tokens = []
170
+ if self.add_bos_token:
171
+ special_tokens.append((bos, bos_token_id))
172
+ if self.add_eos_token:
173
+ special_tokens.append((eos, eos_token_id))
174
+ self._tokenizer.post_processor = processors.TemplateProcessing(
175
+ single=single, pair=pair, special_tokens=special_tokens
176
+ )
177
+
178
+ # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.get_special_tokens_mask
179
+ def get_special_tokens_mask(
180
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
181
+ ) -> List[int]:
182
+ """
183
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
184
+ special tokens using the tokenizer `prepare_for_model` method.
185
+
186
+ Args:
187
+ token_ids_0 (`List[int]`):
188
+ List of IDs.
189
+ token_ids_1 (`List[int]`, *optional*):
190
+ Optional second list of IDs for sequence pairs.
191
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
192
+ Whether or not the token list is already formatted with special tokens for the model.
193
+
194
+ Returns:
195
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
196
+ """
197
+ if already_has_special_tokens:
198
+ return super().get_special_tokens_mask(
199
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
200
+ )
201
+
202
+ bos_token_id = [1] if self.add_bos_token else []
203
+ eos_token_id = [1] if self.add_eos_token else []
204
+
205
+ if token_ids_1 is None:
206
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
207
+ return (
208
+ bos_token_id
209
+ + ([0] * len(token_ids_0))
210
+ + eos_token_id
211
+ + bos_token_id
212
+ + ([0] * len(token_ids_1))
213
+ + eos_token_id
214
+ )
215
+
216
+ # Copied from transformers.models.llama.tokenization_llama_fast.LlamaTokenizerFast.build_inputs_with_special_tokens
217
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
218
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
219
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
220
+
221
+ output = bos_token_id + token_ids_0 + eos_token_id
222
+
223
+ if token_ids_1 is not None:
224
+ output = output + bos_token_id + token_ids_1 + eos_token_id
225
+
226
+ return output
227
+
228
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
229
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
230
+ return tuple(files)