lalagi2 commited on
Commit
4264413
·
verified ·
1 Parent(s): 211c5da

Upload Phi3ForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - llama-factory
5
+ ---
6
+
7
+ # Model Card for Model ID
8
+
9
+ <!-- Provide a quick summary of what the model is/does. -->
10
+
11
+
12
+
13
+ ## Model Details
14
+
15
+ ### Model Description
16
+
17
+ <!-- Provide a longer summary of what this model is. -->
18
+
19
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
20
+
21
+ - **Developed by:** [More Information Needed]
22
+ - **Funded by [optional]:** [More Information Needed]
23
+ - **Shared by [optional]:** [More Information Needed]
24
+ - **Model type:** [More Information Needed]
25
+ - **Language(s) (NLP):** [More Information Needed]
26
+ - **License:** [More Information Needed]
27
+ - **Finetuned from model [optional]:** [More Information Needed]
28
+
29
+ ### Model Sources [optional]
30
+
31
+ <!-- Provide the basic links for the model. -->
32
+
33
+ - **Repository:** [More Information Needed]
34
+ - **Paper [optional]:** [More Information Needed]
35
+ - **Demo [optional]:** [More Information Needed]
36
+
37
+ ## Uses
38
+
39
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
40
+
41
+ ### Direct Use
42
+
43
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
44
+
45
+ [More Information Needed]
46
+
47
+ ### Downstream Use [optional]
48
+
49
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
50
+
51
+ [More Information Needed]
52
+
53
+ ### Out-of-Scope Use
54
+
55
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
56
+
57
+ [More Information Needed]
58
+
59
+ ## Bias, Risks, and Limitations
60
+
61
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
62
+
63
+ [More Information Needed]
64
+
65
+ ### Recommendations
66
+
67
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
68
+
69
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
70
+
71
+ ## How to Get Started with the Model
72
+
73
+ Use the code below to get started with the model.
74
+
75
+ [More Information Needed]
76
+
77
+ ## Training Details
78
+
79
+ ### Training Data
80
+
81
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
82
+
83
+ [More Information Needed]
84
+
85
+ ### Training Procedure
86
+
87
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
88
+
89
+ #### Preprocessing [optional]
90
+
91
+ [More Information Needed]
92
+
93
+
94
+ #### Training Hyperparameters
95
+
96
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
97
+
98
+ #### Speeds, Sizes, Times [optional]
99
+
100
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
101
+
102
+ [More Information Needed]
103
+
104
+ ## Evaluation
105
+
106
+ <!-- This section describes the evaluation protocols and provides the results. -->
107
+
108
+ ### Testing Data, Factors & Metrics
109
+
110
+ #### Testing Data
111
+
112
+ <!-- This should link to a Dataset Card if possible. -->
113
+
114
+ [More Information Needed]
115
+
116
+ #### Factors
117
+
118
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
119
+
120
+ [More Information Needed]
121
+
122
+ #### Metrics
123
+
124
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
125
+
126
+ [More Information Needed]
127
+
128
+ ### Results
129
+
130
+ [More Information Needed]
131
+
132
+ #### Summary
133
+
134
+
135
+
136
+ ## Model Examination [optional]
137
+
138
+ <!-- Relevant interpretability work for the model goes here -->
139
+
140
+ [More Information Needed]
141
+
142
+ ## Environmental Impact
143
+
144
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
145
+
146
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
147
+
148
+ - **Hardware Type:** [More Information Needed]
149
+ - **Hours used:** [More Information Needed]
150
+ - **Cloud Provider:** [More Information Needed]
151
+ - **Compute Region:** [More Information Needed]
152
+ - **Carbon Emitted:** [More Information Needed]
153
+
154
+ ## Technical Specifications [optional]
155
+
156
+ ### Model Architecture and Objective
157
+
158
+ [More Information Needed]
159
+
160
+ ### Compute Infrastructure
161
+
162
+ [More Information Needed]
163
+
164
+ #### Hardware
165
+
166
+ [More Information Needed]
167
+
168
+ #### Software
169
+
170
+ [More Information Needed]
171
+
172
+ ## Citation [optional]
173
+
174
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
175
+
176
+ **BibTeX:**
177
+
178
+ [More Information Needed]
179
+
180
+ **APA:**
181
+
182
+ [More Information Needed]
183
+
184
+ ## Glossary [optional]
185
+
186
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
187
+
188
+ [More Information Needed]
189
+
190
+ ## More Information [optional]
191
+
192
+ [More Information Needed]
193
+
194
+ ## Model Card Authors [optional]
195
+
196
+ [More Information Needed]
197
+
198
+ ## Model Card Contact
199
+
200
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "microsoft/Phi-3.5-mini-instruct",
3
+ "architectures": [
4
+ "Phi3ForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_phi3.Phi3Config",
10
+ "AutoModel": "modeling_phi3.Phi3ForCausalLM",
11
+ "AutoModelForCausalLM": "microsoft/Phi-3.5-mini-instruct--modeling_phi3.Phi3ForCausalLM"
12
+ },
13
+ "bos_token_id": 1,
14
+ "embd_pdrop": 0.0,
15
+ "eos_token_id": 32000,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 3072,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 8192,
20
+ "max_position_embeddings": 131072,
21
+ "model_type": "phi3",
22
+ "num_attention_heads": 32,
23
+ "num_hidden_layers": 32,
24
+ "num_key_value_heads": 32,
25
+ "original_max_position_embeddings": 4096,
26
+ "pad_token_id": 32000,
27
+ "resid_pdrop": 0.0,
28
+ "rms_norm_eps": 1e-05,
29
+ "rope_scaling": {
30
+ "long_factor": [
31
+ 1.0800000429153442,
32
+ 1.1100000143051147,
33
+ 1.1399999856948853,
34
+ 1.340000033378601,
35
+ 1.5899999141693115,
36
+ 1.600000023841858,
37
+ 1.6200000047683716,
38
+ 2.620000123977661,
39
+ 3.2300000190734863,
40
+ 3.2300000190734863,
41
+ 4.789999961853027,
42
+ 7.400000095367432,
43
+ 7.700000286102295,
44
+ 9.09000015258789,
45
+ 12.199999809265137,
46
+ 17.670000076293945,
47
+ 24.46000099182129,
48
+ 28.57000160217285,
49
+ 30.420001983642578,
50
+ 30.840002059936523,
51
+ 32.590003967285156,
52
+ 32.93000411987305,
53
+ 42.320003509521484,
54
+ 44.96000289916992,
55
+ 50.340003967285156,
56
+ 50.45000457763672,
57
+ 57.55000305175781,
58
+ 57.93000411987305,
59
+ 58.21000289916992,
60
+ 60.1400032043457,
61
+ 62.61000442504883,
62
+ 62.62000274658203,
63
+ 62.71000289916992,
64
+ 63.1400032043457,
65
+ 63.1400032043457,
66
+ 63.77000427246094,
67
+ 63.93000411987305,
68
+ 63.96000289916992,
69
+ 63.970001220703125,
70
+ 64.02999877929688,
71
+ 64.06999969482422,
72
+ 64.08000183105469,
73
+ 64.12000274658203,
74
+ 64.41000366210938,
75
+ 64.4800033569336,
76
+ 64.51000213623047,
77
+ 64.52999877929688,
78
+ 64.83999633789062
79
+ ],
80
+ "short_factor": [
81
+ 1.0,
82
+ 1.0199999809265137,
83
+ 1.0299999713897705,
84
+ 1.0299999713897705,
85
+ 1.0499999523162842,
86
+ 1.0499999523162842,
87
+ 1.0499999523162842,
88
+ 1.0499999523162842,
89
+ 1.0499999523162842,
90
+ 1.0699999332427979,
91
+ 1.0999999046325684,
92
+ 1.1099998950958252,
93
+ 1.1599998474121094,
94
+ 1.1599998474121094,
95
+ 1.1699998378753662,
96
+ 1.2899998426437378,
97
+ 1.339999794960022,
98
+ 1.679999828338623,
99
+ 1.7899998426437378,
100
+ 1.8199998140335083,
101
+ 1.8499997854232788,
102
+ 1.8799997568130493,
103
+ 1.9099997282028198,
104
+ 1.9399996995925903,
105
+ 1.9899996519088745,
106
+ 2.0199997425079346,
107
+ 2.0199997425079346,
108
+ 2.0199997425079346,
109
+ 2.0199997425079346,
110
+ 2.0199997425079346,
111
+ 2.0199997425079346,
112
+ 2.0299997329711914,
113
+ 2.0299997329711914,
114
+ 2.0299997329711914,
115
+ 2.0299997329711914,
116
+ 2.0299997329711914,
117
+ 2.0299997329711914,
118
+ 2.0299997329711914,
119
+ 2.0299997329711914,
120
+ 2.0299997329711914,
121
+ 2.0799996852874756,
122
+ 2.0899996757507324,
123
+ 2.189999580383301,
124
+ 2.2199995517730713,
125
+ 2.5899994373321533,
126
+ 2.729999542236328,
127
+ 2.749999523162842,
128
+ 2.8399994373321533
129
+ ],
130
+ "type": "longrope"
131
+ },
132
+ "rope_theta": 10000.0,
133
+ "sliding_window": 262144,
134
+ "tie_word_embeddings": false,
135
+ "torch_dtype": "bfloat16",
136
+ "transformers_version": "4.46.1",
137
+ "use_cache": true,
138
+ "vocab_size": 32064
139
+ }
configuration_phi3.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft 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
+
16
+ """Phi-3 model configuration"""
17
+
18
+ from ...configuration_utils import PretrainedConfig
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Phi3Config(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
28
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
29
+ defaults will yield a similar configuration to that of the
30
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
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
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32064):
37
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Phi3Model`].
39
+ hidden_size (`int`, *optional*, defaults to 3072):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 8192):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer decoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer decoder.
47
+ num_key_value_heads (`int`, *optional*):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
54
+ `num_attention_heads`.
55
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
56
+ Dropout probability for mlp outputs.
57
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
58
+ The dropout ratio for the embeddings.
59
+ attention_dropout (`float`, *optional*, defaults to 0.0):
60
+ The dropout ratio after computing the attention scores.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
64
+ The maximum sequence length that this model might ever be used with.
65
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
66
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
67
+ original RoPE embeddings when using long scaling.
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
71
+ The epsilon value used for the RMSNorm.
72
+ use_cache (`bool`, *optional*, defaults to `True`):
73
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
74
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
75
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
76
+ Whether to tie weight embeddings
77
+ rope_theta (`float`, *optional*, defaults to 10000.0):
78
+ The base period of the RoPE embeddings.
79
+ rope_scaling (`dict`, *optional*):
80
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
81
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
82
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
83
+ divided by the number of attention heads divided by 2.
84
+ bos_token_id (`int`, *optional*, defaults to 1):
85
+ The id of the "beginning-of-sequence" token.
86
+ eos_token_id (`int`, *optional*, defaults to 32000):
87
+ The id of the "end-of-sequence" token.
88
+ pad_token_id (`int`, *optional*, defaults to 32000):
89
+ The id of the padding token.
90
+ sliding_window (`int`, *optional*):
91
+ Sliding window attention window size. If `None`, no sliding window is applied.
92
+
93
+ Example:
94
+
95
+ ```python
96
+ >>> from transformers import Phi3Model, Phi3Config
97
+
98
+ >>> # Initializing a Phi-3 style configuration
99
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
100
+
101
+ >>> # Initializing a model from the configuration
102
+ >>> model = Phi3Model(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+
108
+ model_type = "phi3"
109
+ keys_to_ignore_at_inference = ["past_key_values"]
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=32064,
114
+ hidden_size=3072,
115
+ intermediate_size=8192,
116
+ num_hidden_layers=32,
117
+ num_attention_heads=32,
118
+ num_key_value_heads=None,
119
+ resid_pdrop=0.0,
120
+ embd_pdrop=0.0,
121
+ attention_dropout=0.0,
122
+ hidden_act="silu",
123
+ max_position_embeddings=4096,
124
+ original_max_position_embeddings=4096,
125
+ initializer_range=0.02,
126
+ rms_norm_eps=1e-5,
127
+ use_cache=True,
128
+ tie_word_embeddings=False,
129
+ rope_theta=10000.0,
130
+ rope_scaling=None,
131
+ bos_token_id=1,
132
+ eos_token_id=32000,
133
+ pad_token_id=32000,
134
+ sliding_window=None,
135
+ **kwargs,
136
+ ):
137
+ self.vocab_size = vocab_size
138
+ self.hidden_size = hidden_size
139
+ self.intermediate_size = intermediate_size
140
+ self.num_hidden_layers = num_hidden_layers
141
+ self.num_attention_heads = num_attention_heads
142
+
143
+ if num_key_value_heads is None:
144
+ num_key_value_heads = num_attention_heads
145
+
146
+ self.num_key_value_heads = num_key_value_heads
147
+ self.resid_pdrop = resid_pdrop
148
+ self.embd_pdrop = embd_pdrop
149
+ self.attention_dropout = attention_dropout
150
+ self.hidden_act = hidden_act
151
+ self.max_position_embeddings = max_position_embeddings
152
+ self.original_max_position_embeddings = original_max_position_embeddings
153
+ self.initializer_range = initializer_range
154
+ self.rms_norm_eps = rms_norm_eps
155
+ self.use_cache = use_cache
156
+ self.rope_theta = rope_theta
157
+ self.rope_scaling = rope_scaling
158
+ self._rope_scaling_adjustment()
159
+ self._rope_scaling_validation()
160
+ self.sliding_window = sliding_window
161
+
162
+ super().__init__(
163
+ bos_token_id=bos_token_id,
164
+ eos_token_id=eos_token_id,
165
+ pad_token_id=pad_token_id,
166
+ tie_word_embeddings=tie_word_embeddings,
167
+ **kwargs,
168
+ )
169
+
170
+ def _rope_scaling_adjustment(self):
171
+ """
172
+ Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
173
+ """
174
+ if self.rope_scaling is None:
175
+ return
176
+
177
+ rope_scaling_type = self.rope_scaling.get("type", None)
178
+
179
+ # For backward compatibility if previous version used "su" or "yarn"
180
+ if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
181
+ self.rope_scaling["type"] = "longrope"
182
+
183
+ def _rope_scaling_validation(self):
184
+ """
185
+ Validate the `rope_scaling` configuration.
186
+ """
187
+ if self.rope_scaling is None:
188
+ return
189
+
190
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
191
+ raise ValueError(
192
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
193
+ f"got {self.rope_scaling}"
194
+ )
195
+ rope_scaling_type = self.rope_scaling.get("type", None)
196
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
197
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
198
+ if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
199
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
200
+ if not (
201
+ isinstance(rope_scaling_short_factor, list)
202
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
203
+ ):
204
+ raise ValueError(
205
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
206
+ )
207
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
208
+ raise ValueError(
209
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
210
+ )
211
+ if not (
212
+ isinstance(rope_scaling_long_factor, list)
213
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
214
+ ):
215
+ raise ValueError(
216
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
217
+ )
218
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
219
+ raise ValueError(
220
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
221
+ )
generation_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": [
5
+ 32007,
6
+ 32001,
7
+ 32000
8
+ ],
9
+ "pad_token_id": 32000,
10
+ "transformers_version": "4.46.1"
11
+ }
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea7fc068524920f3bf964c8462de2c3eaf1604ed3b249b3941c70d85a8cd2f12
3
+ size 1958700256
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af3803f6df398f99cd40817bbcd16eadac5bd4ef21371ec38c2fa63a655a0738
3
+ size 1937885224
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60567b01a56e6bd42c76855b5a896da3aa70362ae83af4f5e50e17748c512391
3
+ size 1981925424
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4bae33482a8983b6e745fe91ff3e63e7cec9a2a996503616f3035e5dadfeaaa0
3
+ size 1763670920
model.safetensors.index.json ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 7642159104
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00004-of-00004.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
10
+ "model.layers.0.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.0.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
14
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
15
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
16
+ "model.layers.1.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
17
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
18
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
19
+ "model.layers.1.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
20
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
21
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
22
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
23
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
24
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
25
+ "model.layers.10.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
26
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
27
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
28
+ "model.layers.11.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
29
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
30
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
31
+ "model.layers.11.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
32
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
33
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
34
+ "model.layers.12.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
35
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
36
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
37
+ "model.layers.12.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
38
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
39
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
40
+ "model.layers.13.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
41
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
42
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
43
+ "model.layers.13.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
44
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
45
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
46
+ "model.layers.14.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
47
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
48
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
49
+ "model.layers.14.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
50
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
51
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
52
+ "model.layers.15.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
53
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
54
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
55
+ "model.layers.15.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
56
+ "model.layers.16.input_layernorm.weight": "model-00003-of-00004.safetensors",
57
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
58
+ "model.layers.16.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
59
+ "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
60
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
61
+ "model.layers.16.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
62
+ "model.layers.17.input_layernorm.weight": "model-00003-of-00004.safetensors",
63
+ "model.layers.17.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
64
+ "model.layers.17.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
65
+ "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
66
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
67
+ "model.layers.17.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
68
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
69
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
70
+ "model.layers.18.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
71
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
72
+ "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
73
+ "model.layers.18.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
74
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
75
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
76
+ "model.layers.19.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
77
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
78
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
79
+ "model.layers.19.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
80
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
81
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
82
+ "model.layers.2.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
83
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
84
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
85
+ "model.layers.2.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
86
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
87
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
88
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
89
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
90
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
91
+ "model.layers.20.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
92
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
93
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
94
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
95
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
96
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
97
+ "model.layers.21.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
98
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
99
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
100
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
101
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
102
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
103
+ "model.layers.22.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
104
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
105
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
106
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
107
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
108
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
109
+ "model.layers.23.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
110
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
111
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
112
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00003-of-00004.safetensors",
113
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
114
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
115
+ "model.layers.24.self_attn.qkv_proj.weight": "model-00003-of-00004.safetensors",
116
+ "model.layers.25.input_layernorm.weight": "model-00004-of-00004.safetensors",
117
+ "model.layers.25.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
118
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
119
+ "model.layers.25.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
120
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
121
+ "model.layers.25.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
122
+ "model.layers.26.input_layernorm.weight": "model-00004-of-00004.safetensors",
123
+ "model.layers.26.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
124
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
125
+ "model.layers.26.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
126
+ "model.layers.26.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
127
+ "model.layers.26.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
128
+ "model.layers.27.input_layernorm.weight": "model-00004-of-00004.safetensors",
129
+ "model.layers.27.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
130
+ "model.layers.27.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
131
+ "model.layers.27.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
132
+ "model.layers.27.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
133
+ "model.layers.27.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
134
+ "model.layers.28.input_layernorm.weight": "model-00004-of-00004.safetensors",
135
+ "model.layers.28.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
136
+ "model.layers.28.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
137
+ "model.layers.28.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
138
+ "model.layers.28.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
139
+ "model.layers.28.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
140
+ "model.layers.29.input_layernorm.weight": "model-00004-of-00004.safetensors",
141
+ "model.layers.29.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
142
+ "model.layers.29.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
143
+ "model.layers.29.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
144
+ "model.layers.29.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
145
+ "model.layers.29.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
146
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
147
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
148
+ "model.layers.3.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
149
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
150
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
151
+ "model.layers.3.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
152
+ "model.layers.30.input_layernorm.weight": "model-00004-of-00004.safetensors",
153
+ "model.layers.30.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
154
+ "model.layers.30.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
155
+ "model.layers.30.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
156
+ "model.layers.30.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
157
+ "model.layers.30.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
158
+ "model.layers.31.input_layernorm.weight": "model-00004-of-00004.safetensors",
159
+ "model.layers.31.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
160
+ "model.layers.31.mlp.gate_up_proj.weight": "model-00004-of-00004.safetensors",
161
+ "model.layers.31.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
162
+ "model.layers.31.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
163
+ "model.layers.31.self_attn.qkv_proj.weight": "model-00004-of-00004.safetensors",
164
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
165
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
166
+ "model.layers.4.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
167
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
168
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
169
+ "model.layers.4.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
170
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
171
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
172
+ "model.layers.5.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
173
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
174
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
175
+ "model.layers.5.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
176
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
177
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
178
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
179
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
180
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
181
+ "model.layers.6.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
182
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00004.safetensors",
183
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
184
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00001-of-00004.safetensors",
185
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
186
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
187
+ "model.layers.7.self_attn.qkv_proj.weight": "model-00001-of-00004.safetensors",
188
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
189
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
190
+ "model.layers.8.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
191
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
192
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
193
+ "model.layers.8.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
194
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
195
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
196
+ "model.layers.9.mlp.gate_up_proj.weight": "model-00002-of-00004.safetensors",
197
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
198
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
199
+ "model.layers.9.self_attn.qkv_proj.weight": "model-00002-of-00004.safetensors",
200
+ "model.norm.weight": "model-00004-of-00004.safetensors"
201
+ }
202
+ }
modeling_phi3.py ADDED
@@ -0,0 +1,1525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft 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
+
16
+ """PyTorch Phi-3 model."""
17
+
18
+ import math
19
+ import warnings
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
29
+ from ...generation import GenerationMixin
30
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
31
+ from ...modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ SequenceClassifierOutputWithPast,
35
+ TokenClassifierOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...utils import (
39
+ add_code_sample_docstrings,
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ is_flash_attn_2_available,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_phi3 import Phi3Config
48
+
49
+
50
+ if is_flash_attn_2_available():
51
+ from ...modeling_flash_attention_utils import _flash_attention_forward
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
56
+ _CONFIG_FOR_DOC = "Phi3Config"
57
+
58
+
59
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
60
+ class Phi3RMSNorm(nn.Module):
61
+ def __init__(self, hidden_size, eps=1e-6):
62
+ """
63
+ Phi3RMSNorm is equivalent to T5LayerNorm
64
+ """
65
+ super().__init__()
66
+ self.weight = nn.Parameter(torch.ones(hidden_size))
67
+ self.variance_epsilon = eps
68
+
69
+ def forward(self, hidden_states):
70
+ input_dtype = hidden_states.dtype
71
+ hidden_states = hidden_states.to(torch.float32)
72
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
73
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
74
+ return self.weight * hidden_states.to(input_dtype)
75
+
76
+ def extra_repr(self):
77
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
78
+
79
+
80
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
81
+ class Phi3RotaryEmbedding(nn.Module):
82
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
83
+ super().__init__()
84
+
85
+ self.dim = dim
86
+ self.max_position_embeddings = max_position_embeddings
87
+ self.base = base
88
+
89
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
90
+ self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
91
+
92
+ @torch.no_grad()
93
+ def forward(self, x, position_ids, seq_len=None):
94
+ # x: [bs, num_attention_heads, seq_len, head_size]
95
+ self.inv_freq.to(x.device)
96
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
97
+ position_ids_expanded = position_ids[:, None, :].float()
98
+ # Force float32 since bfloat16 loses precision on long contexts
99
+ # See https://github.com/huggingface/transformers/pull/29285
100
+ device_type = x.device.type
101
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
102
+ with torch.autocast(device_type=device_type, enabled=False):
103
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
104
+ emb = torch.cat((freqs, freqs), dim=-1)
105
+ cos = emb.cos()
106
+ sin = emb.sin()
107
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
108
+
109
+
110
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
111
+ def __init__(self, dim, config, device=None):
112
+ warnings.warn(
113
+ "The class Phi3SuScaledRotaryEmbedding is deprecated and will be removed in version 5 of Transformers. Please"
114
+ " use Phi3LongRoPEScaledRotaryEmbedding instead.",
115
+ FutureWarning,
116
+ )
117
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
118
+
119
+ self.short_factor = config.rope_scaling["short_factor"]
120
+ self.long_factor = config.rope_scaling["long_factor"]
121
+ self.original_max_position_embeddings = config.original_max_position_embeddings
122
+
123
+ @torch.no_grad()
124
+ def forward(self, x, position_ids, seq_len=None):
125
+ seq_len = torch.max(position_ids) + 1
126
+ if seq_len > self.original_max_position_embeddings:
127
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
128
+ else:
129
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
130
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
131
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
132
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
133
+ position_ids_expanded = position_ids[:, None, :].float()
134
+ # Force float32 since bfloat16 loses precision on long contexts
135
+ # See https://github.com/huggingface/transformers/pull/29285
136
+ device_type = x.device.type
137
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
138
+ with torch.autocast(device_type=device_type, enabled=False):
139
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
140
+ emb = torch.cat((freqs, freqs), dim=-1)
141
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
142
+ if scale <= 1.0:
143
+ scaling_factor = 1.0
144
+ else:
145
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
146
+ cos = emb.cos() * scaling_factor
147
+ sin = emb.sin() * scaling_factor
148
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
149
+
150
+
151
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
152
+ def __init__(self, dim, config, device=None):
153
+ warnings.warn(
154
+ "The class Phi3YarnScaledRotaryEmbedding is deprecated and will be removed in version 5 of Transformers",
155
+ FutureWarning,
156
+ )
157
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
158
+
159
+ self.short_factor = config.rope_scaling["short_factor"]
160
+ self.long_factor = config.rope_scaling["long_factor"]
161
+ self.original_max_position_embeddings = config.original_max_position_embeddings
162
+
163
+ @torch.no_grad()
164
+ def forward(self, x, position_ids, seq_len=None):
165
+ seq_len = torch.max(position_ids) + 1
166
+ if seq_len > self.original_max_position_embeddings:
167
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
168
+ else:
169
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
170
+
171
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
172
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
173
+
174
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
175
+ position_ids_expanded = position_ids[:, None, :].float()
176
+
177
+ # Force float32 since bfloat16 loses precision on long contexts
178
+ # See https://github.com/huggingface/transformers/pull/29285
179
+ device_type = x.device.type
180
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
181
+ with torch.autocast(device_type=device_type, enabled=False):
182
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
183
+ emb = torch.cat((freqs, freqs), dim=-1)
184
+
185
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
186
+ if scale <= 1.0:
187
+ scaling_factor = 1.0
188
+ else:
189
+ scaling_factor = 0.1 * math.log(scale) + 1.0
190
+
191
+ cos = emb.cos() * scaling_factor
192
+ sin = emb.sin() * scaling_factor
193
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
194
+
195
+
196
+ class Phi3LongRoPEScaledRotaryEmbedding(Phi3RotaryEmbedding):
197
+ def __init__(self, dim, config, device=None):
198
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
199
+
200
+ self.short_factor = config.rope_scaling["short_factor"]
201
+ self.long_factor = config.rope_scaling["long_factor"]
202
+ self.original_max_position_embeddings = config.original_max_position_embeddings
203
+
204
+ @torch.no_grad()
205
+ def forward(self, x, position_ids, seq_len=None):
206
+ seq_len = seq_len or torch.max(position_ids) + 1
207
+ if seq_len > self.original_max_position_embeddings:
208
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
209
+ else:
210
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
211
+
212
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
213
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
214
+
215
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
216
+ position_ids_expanded = position_ids[:, None, :].float()
217
+
218
+ # Force float32 since bfloat16 loses precision on long contexts
219
+ # See https://github.com/huggingface/transformers/pull/29285
220
+ device_type = x.device.type
221
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
222
+ with torch.autocast(device_type=device_type, enabled=False):
223
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
224
+ emb = torch.cat((freqs, freqs), dim=-1)
225
+
226
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
227
+ if scale <= 1.0:
228
+ scaling_factor = 1.0
229
+ else:
230
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
231
+
232
+ cos = emb.cos() * scaling_factor
233
+ sin = emb.sin() * scaling_factor
234
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
235
+
236
+
237
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
238
+ def rotate_half(x):
239
+ """Rotates half the hidden dims of the input."""
240
+ x1 = x[..., : x.shape[-1] // 2]
241
+ x2 = x[..., x.shape[-1] // 2 :]
242
+ return torch.cat((-x2, x1), dim=-1)
243
+
244
+
245
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
246
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
247
+ """Applies Rotary Position Embedding to the query and key tensors.
248
+
249
+ Args:
250
+ q (`torch.Tensor`): The query tensor.
251
+ k (`torch.Tensor`): The key tensor.
252
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
253
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
254
+ position_ids (`torch.Tensor`, *optional*):
255
+ Deprecated and unused.
256
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
257
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
258
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
259
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
260
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
261
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
262
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
263
+ Returns:
264
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
265
+ """
266
+ cos = cos.unsqueeze(unsqueeze_dim)
267
+ sin = sin.unsqueeze(unsqueeze_dim)
268
+ q_embed = (q * cos) + (rotate_half(q) * sin)
269
+ k_embed = (k * cos) + (rotate_half(k) * sin)
270
+ return q_embed, k_embed
271
+
272
+
273
+ class Phi3MLP(nn.Module):
274
+ def __init__(self, config):
275
+ super().__init__()
276
+
277
+ self.config = config
278
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
279
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
280
+
281
+ self.activation_fn = ACT2FN[config.hidden_act]
282
+
283
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
284
+ up_states = self.gate_up_proj(hidden_states)
285
+
286
+ gate, up_states = up_states.chunk(2, dim=-1)
287
+ up_states = up_states * self.activation_fn(gate)
288
+
289
+ return self.down_proj(up_states)
290
+
291
+
292
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
293
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
294
+ """
295
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
296
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
297
+ """
298
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
299
+ if n_rep == 1:
300
+ return hidden_states
301
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
302
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
303
+
304
+
305
+ class Phi3Attention(nn.Module):
306
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
307
+
308
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
309
+ super().__init__()
310
+ self.config = config
311
+ self.layer_idx = layer_idx
312
+ if layer_idx is None:
313
+ logger.warning_once(
314
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
315
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
316
+ "when creating this class."
317
+ )
318
+
319
+ self.attention_dropout = config.attention_dropout
320
+ self.hidden_size = config.hidden_size
321
+ self.num_heads = config.num_attention_heads
322
+ self.head_dim = self.hidden_size // self.num_heads
323
+ self.num_key_value_heads = config.num_key_value_heads
324
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
325
+ self.max_position_embeddings = config.max_position_embeddings
326
+ self.original_max_position_embeddings = config.original_max_position_embeddings
327
+ self.rope_theta = config.rope_theta
328
+ self.rope_scaling = config.rope_scaling
329
+ self.is_causal = True
330
+
331
+ if (self.head_dim * self.num_heads) != self.hidden_size:
332
+ raise ValueError(
333
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
334
+ f" and `num_heads`: {self.num_heads})."
335
+ )
336
+
337
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
338
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
339
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
340
+ self._init_rope()
341
+
342
+ def _init_rope(self):
343
+ if self.rope_scaling is None:
344
+ self.rotary_emb = Phi3RotaryEmbedding(
345
+ self.head_dim,
346
+ max_position_embeddings=self.max_position_embeddings,
347
+ base=self.rope_theta,
348
+ )
349
+ else:
350
+ scaling_type = self.config.rope_scaling["type"]
351
+ if scaling_type == "longrope":
352
+ self.rotary_emb = Phi3LongRoPEScaledRotaryEmbedding(self.head_dim, self.config)
353
+ else:
354
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
355
+
356
+ def forward(
357
+ self,
358
+ hidden_states: torch.Tensor,
359
+ attention_mask: Optional[torch.Tensor] = None,
360
+ position_ids: Optional[torch.LongTensor] = None,
361
+ past_key_value: Optional[Cache] = None,
362
+ output_attentions: bool = False,
363
+ use_cache: bool = False,
364
+ cache_position: Optional[torch.LongTensor] = None,
365
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
366
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
367
+
368
+ bsz, q_len, _ = hidden_states.size()
369
+
370
+ qkv = self.qkv_proj(hidden_states)
371
+ query_pos = self.num_heads * self.head_dim
372
+ query_states = qkv[..., :query_pos]
373
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
374
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
375
+
376
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
377
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
378
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
379
+
380
+ kv_seq_len = key_states.shape[-2]
381
+ if past_key_value is not None:
382
+ if self.layer_idx is None:
383
+ raise ValueError(
384
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
385
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
386
+ "with a layer index."
387
+ )
388
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
389
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
390
+
391
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
392
+
393
+ if past_key_value is not None:
394
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
395
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
396
+
397
+ # repeat k/v heads if n_kv_heads < n_heads
398
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
399
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
400
+
401
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
402
+
403
+ if attention_mask is not None:
404
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
405
+ attn_weights += causal_mask
406
+
407
+ # upcast attention to fp32
408
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
409
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
410
+
411
+ attn_output = torch.matmul(attn_weights, value_states)
412
+
413
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
414
+ raise ValueError(
415
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
416
+ f" {attn_output.size()}"
417
+ )
418
+
419
+ attn_output = attn_output.transpose(1, 2).contiguous()
420
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
421
+
422
+ attn_output = self.o_proj(attn_output)
423
+
424
+ if not output_attentions:
425
+ attn_weights = None
426
+
427
+ return attn_output, attn_weights, past_key_value
428
+
429
+
430
+ class Phi3FlashAttention2(Phi3Attention):
431
+ """
432
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
433
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
434
+ flash attention and deal with padding tokens in case the input contains any of them.
435
+ """
436
+
437
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
438
+ def __init__(self, *args, **kwargs):
439
+ super().__init__(*args, **kwargs)
440
+
441
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
442
+ # 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.
443
+ # 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).
444
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
445
+
446
+ def forward(
447
+ self,
448
+ hidden_states: torch.Tensor,
449
+ attention_mask: Optional[torch.LongTensor] = None,
450
+ position_ids: Optional[torch.LongTensor] = None,
451
+ past_key_value: Optional[Cache] = None,
452
+ output_attentions: bool = False,
453
+ use_cache: bool = False,
454
+ cache_position: Optional[torch.LongTensor] = None,
455
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
456
+ # Phi3FlashAttention2 attention does not support output_attentions
457
+
458
+ output_attentions = False
459
+
460
+ bsz, q_len, _ = hidden_states.size()
461
+
462
+ qkv = self.qkv_proj(hidden_states)
463
+ query_pos = self.num_heads * self.head_dim
464
+ query_states = qkv[..., :query_pos]
465
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
466
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
467
+
468
+ # Flash attention requires the input to have the shape
469
+ # batch_size x seq_length x head_dim x hidden_dim
470
+ # therefore we just need to keep the original shape
471
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
472
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
473
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
474
+
475
+ kv_seq_len = key_states.shape[-2]
476
+ if past_key_value is not None:
477
+ if self.layer_idx is None:
478
+ raise ValueError(
479
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
480
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
481
+ "with a layer index."
482
+ )
483
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
484
+
485
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
486
+ rotary_seq_len = (
487
+ max(kv_seq_len, position_ids[:, -1].max().item() + 1) if position_ids is not None else kv_seq_len
488
+ )
489
+
490
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len, position_ids=position_ids)
491
+
492
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
493
+
494
+ if past_key_value is not None:
495
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
496
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
497
+
498
+ # repeat k/v heads if n_kv_heads < n_heads
499
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
500
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
501
+
502
+ attn_dropout = self.attention_dropout if self.training else 0.0
503
+
504
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
505
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
506
+ # cast them back in the correct dtype just to be sure everything works as expected.
507
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
508
+ # in fp32.
509
+
510
+ if query_states.dtype == torch.float32:
511
+ if torch.is_autocast_enabled():
512
+ target_dtype = torch.get_autocast_gpu_dtype()
513
+ # Handle the case where the model is quantized
514
+ elif hasattr(self.config, "_pre_quantization_dtype"):
515
+ target_dtype = self.config._pre_quantization_dtype
516
+ else:
517
+ target_dtype = self.qkv_proj.weight.dtype
518
+
519
+ logger.warning_once(
520
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
521
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
522
+ f" {target_dtype}."
523
+ )
524
+
525
+ query_states = query_states.to(target_dtype)
526
+ key_states = key_states.to(target_dtype)
527
+ value_states = value_states.to(target_dtype)
528
+
529
+ # Reashape to the expected shape for Flash Attention
530
+ query_states = query_states.transpose(1, 2)
531
+ key_states = key_states.transpose(1, 2)
532
+ value_states = value_states.transpose(1, 2)
533
+
534
+ attn_output = _flash_attention_forward(
535
+ query_states,
536
+ key_states,
537
+ value_states,
538
+ attention_mask,
539
+ q_len,
540
+ position_ids=position_ids,
541
+ dropout=attn_dropout,
542
+ sliding_window=getattr(self.config, "sliding_window", None),
543
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
544
+ is_causal=self.is_causal,
545
+ )
546
+
547
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
548
+ attn_output = self.o_proj(attn_output)
549
+
550
+ if not output_attentions:
551
+ attn_weights = None
552
+
553
+ return attn_output, attn_weights, past_key_value
554
+
555
+
556
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
557
+ # TODO @Arthur no longer copied from LLama after static cache
558
+ class Phi3SdpaAttention(Phi3Attention):
559
+ """
560
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
561
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
562
+ SDPA API.
563
+ """
564
+
565
+ # Adapted from Phi3Attention.forward
566
+ def forward(
567
+ self,
568
+ hidden_states: torch.Tensor,
569
+ attention_mask: Optional[torch.Tensor] = None,
570
+ position_ids: Optional[torch.LongTensor] = None,
571
+ past_key_value: Optional[Cache] = None,
572
+ output_attentions: bool = False,
573
+ use_cache: bool = False,
574
+ cache_position: Optional[torch.LongTensor] = None,
575
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
576
+ if output_attentions:
577
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
578
+ logger.warning_once(
579
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
580
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
581
+ )
582
+ return super().forward(
583
+ hidden_states=hidden_states,
584
+ attention_mask=attention_mask,
585
+ position_ids=position_ids,
586
+ past_key_value=past_key_value,
587
+ output_attentions=output_attentions,
588
+ use_cache=use_cache,
589
+ )
590
+
591
+ bsz, q_len, _ = hidden_states.size()
592
+
593
+ qkv = self.qkv_proj(hidden_states)
594
+ query_pos = self.num_heads * self.head_dim
595
+ query_states = qkv[..., :query_pos]
596
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
597
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
598
+
599
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
600
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
601
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
602
+
603
+ kv_seq_len = key_states.shape[-2]
604
+ if past_key_value is not None:
605
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
606
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
607
+
608
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
609
+
610
+ if past_key_value is not None:
611
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
612
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
613
+
614
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
615
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
616
+
617
+ causal_mask = attention_mask
618
+ if attention_mask is not None:
619
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
620
+
621
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
622
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
623
+ if query_states.device.type == "cuda" and attention_mask is not None:
624
+ query_states = query_states.contiguous()
625
+ key_states = key_states.contiguous()
626
+ value_states = value_states.contiguous()
627
+
628
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
629
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
630
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
631
+ is_causal = True if causal_mask is None and q_len > 1 else False
632
+
633
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
634
+ query_states,
635
+ key_states,
636
+ value_states,
637
+ attn_mask=causal_mask,
638
+ dropout_p=self.attention_dropout if self.training else 0.0,
639
+ is_causal=is_causal,
640
+ )
641
+
642
+ attn_output = attn_output.transpose(1, 2).contiguous()
643
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
644
+
645
+ attn_output = self.o_proj(attn_output)
646
+
647
+ return attn_output, None, past_key_value
648
+
649
+
650
+ PHI3_ATTENTION_CLASSES = {
651
+ "eager": Phi3Attention,
652
+ "flash_attention_2": Phi3FlashAttention2,
653
+ "sdpa": Phi3SdpaAttention,
654
+ }
655
+
656
+
657
+ class Phi3DecoderLayer(nn.Module):
658
+ def __init__(self, config: Phi3Config, layer_idx: int):
659
+ super().__init__()
660
+
661
+ self.config = config
662
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
663
+
664
+ self.mlp = Phi3MLP(config)
665
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
666
+
667
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
668
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
669
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
670
+
671
+ def forward(
672
+ self,
673
+ hidden_states: torch.Tensor,
674
+ attention_mask: Optional[torch.Tensor] = None,
675
+ position_ids: Optional[torch.LongTensor] = None,
676
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
677
+ output_attentions: Optional[bool] = False,
678
+ use_cache: Optional[bool] = False,
679
+ cache_position: Optional[torch.LongTensor] = None,
680
+ **kwargs,
681
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
682
+ """
683
+ Args:
684
+ hidden_states (`torch.FloatTensor`):
685
+ input to the layer of shape `(batch, seq_len, embed_dim)`
686
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
687
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
688
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
689
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
690
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
691
+ output_attentions (`bool`, *optional*):
692
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
693
+ returned tensors for more detail.
694
+ use_cache (`bool`, *optional*):
695
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
696
+ (see `past_key_values`).
697
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
698
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
699
+ Indices depicting the position of the input sequence tokens in the sequence
700
+ kwargs (`dict`, *optional*):
701
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
702
+ into the model
703
+ """
704
+
705
+ residual = hidden_states
706
+
707
+ hidden_states = self.input_layernorm(hidden_states)
708
+
709
+ # Self Attention
710
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
711
+ hidden_states=hidden_states,
712
+ attention_mask=attention_mask,
713
+ position_ids=position_ids,
714
+ past_key_value=past_key_value,
715
+ output_attentions=output_attentions,
716
+ use_cache=use_cache,
717
+ cache_position=cache_position,
718
+ )
719
+
720
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
721
+
722
+ residual = hidden_states
723
+ hidden_states = self.post_attention_layernorm(hidden_states)
724
+ hidden_states = self.mlp(hidden_states)
725
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
726
+
727
+ outputs = (hidden_states,)
728
+
729
+ if output_attentions:
730
+ outputs += (self_attn_weights,)
731
+
732
+ if use_cache:
733
+ outputs += (present_key_value,)
734
+
735
+ return outputs
736
+
737
+
738
+ PHI3_START_DOCSTRING = r"""
739
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
740
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
741
+ etc.)
742
+
743
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
744
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
745
+ and behavior.
746
+
747
+ Parameters:
748
+ config ([`Phi3Config`]):
749
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
750
+ load the weights associated with the model, only the configuration. Check out the
751
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
752
+ """
753
+
754
+
755
+ @add_start_docstrings(
756
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
757
+ PHI3_START_DOCSTRING,
758
+ )
759
+ class Phi3PreTrainedModel(PreTrainedModel):
760
+ config_class = Phi3Config
761
+ base_model_prefix = "model"
762
+ supports_gradient_checkpointing = True
763
+ _no_split_modules = ["Phi3DecoderLayer"]
764
+ _skip_keys_device_placement = "past_key_values"
765
+ _supports_flash_attn_2 = True
766
+ _supports_sdpa = True
767
+ _supports_cache_class = True
768
+
769
+ _version = "0.0.5"
770
+
771
+ def _init_weights(self, module):
772
+ std = self.config.initializer_range
773
+ if isinstance(module, nn.Linear):
774
+ module.weight.data.normal_(mean=0.0, std=std)
775
+ if module.bias is not None:
776
+ module.bias.data.zero_()
777
+ elif isinstance(module, nn.Embedding):
778
+ module.weight.data.normal_(mean=0.0, std=std)
779
+ if module.padding_idx is not None:
780
+ module.weight.data[module.padding_idx].zero_()
781
+
782
+
783
+ PHI3_INPUTS_DOCSTRING = r"""
784
+ Args:
785
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
786
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
787
+ it.
788
+
789
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
790
+ [`PreTrainedTokenizer.__call__`] for details.
791
+
792
+ [What are input IDs?](../glossary#input-ids)
793
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
794
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
795
+
796
+ - 1 for tokens that are **not masked**,
797
+ - 0 for tokens that are **masked**.
798
+
799
+ [What are attention masks?](../glossary#attention-mask)
800
+
801
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
802
+ [`PreTrainedTokenizer.__call__`] for details.
803
+
804
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
805
+ `past_key_values`).
806
+
807
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
808
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
809
+ information on the default strategy.
810
+
811
+ - 1 indicates the head is **not masked**,
812
+ - 0 indicates the head is **masked**.
813
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
814
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
815
+ config.n_positions - 1]`.
816
+
817
+ [What are position IDs?](../glossary#position-ids)
818
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
819
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
820
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
821
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
822
+
823
+ Two formats are allowed:
824
+ - a [`~cache_utils.Cache`] instance, see our
825
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
826
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
827
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
828
+ cache format.
829
+
830
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
831
+ legacy cache format will be returned.
832
+
833
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
834
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
835
+ of shape `(batch_size, sequence_length)`.
836
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
837
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
838
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
839
+ model's internal embedding lookup matrix.
840
+ use_cache (`bool`, *optional*):
841
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
842
+ `past_key_values`).
843
+ output_attentions (`bool`, *optional*):
844
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
845
+ tensors for more detail.
846
+ output_hidden_states (`bool`, *optional*):
847
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
848
+ more detail.
849
+ return_dict (`bool`, *optional*):
850
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
851
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
852
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
853
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
854
+ the complete sequence length.
855
+ """
856
+
857
+
858
+ @add_start_docstrings(
859
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
860
+ PHI3_START_DOCSTRING,
861
+ )
862
+ class Phi3Model(Phi3PreTrainedModel):
863
+ """
864
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
865
+
866
+ Args:
867
+ config: Phi3Config
868
+ """
869
+
870
+ def __init__(self, config: Phi3Config):
871
+ super().__init__(config)
872
+ self.padding_idx = config.pad_token_id
873
+ self.vocab_size = config.vocab_size
874
+
875
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
876
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
877
+ self.layers = nn.ModuleList(
878
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
879
+ )
880
+ self._attn_implementation = config._attn_implementation
881
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
882
+
883
+ self.gradient_checkpointing = False
884
+ # Initialize weights and apply final processing
885
+ self.post_init()
886
+
887
+ def get_input_embeddings(self):
888
+ return self.embed_tokens
889
+
890
+ def set_input_embeddings(self, value):
891
+ self.embed_tokens = value
892
+
893
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
894
+ def forward(
895
+ self,
896
+ input_ids: torch.LongTensor = None,
897
+ attention_mask: Optional[torch.Tensor] = None,
898
+ position_ids: Optional[torch.LongTensor] = None,
899
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
900
+ inputs_embeds: Optional[torch.FloatTensor] = None,
901
+ use_cache: Optional[bool] = None,
902
+ output_attentions: Optional[bool] = None,
903
+ output_hidden_states: Optional[bool] = None,
904
+ return_dict: Optional[bool] = None,
905
+ cache_position: Optional[torch.LongTensor] = None,
906
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
907
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
908
+ output_hidden_states = (
909
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
910
+ )
911
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
912
+
913
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
914
+
915
+ if (input_ids is None) ^ (inputs_embeds is not None):
916
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
917
+
918
+ if self.gradient_checkpointing and self.training:
919
+ if use_cache:
920
+ logger.warning_once(
921
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
922
+ )
923
+ use_cache = False
924
+
925
+ # kept for BC (non `Cache` `past_key_values` inputs)
926
+ return_legacy_cache = False
927
+ if use_cache and not isinstance(past_key_values, Cache):
928
+ return_legacy_cache = True
929
+ if past_key_values is None:
930
+ past_key_values = DynamicCache()
931
+ else:
932
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
933
+ logger.warning_once(
934
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
935
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
936
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
937
+ )
938
+
939
+ if inputs_embeds is None:
940
+ inputs_embeds = self.embed_tokens(input_ids)
941
+
942
+ if cache_position is None:
943
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
944
+ cache_position = torch.arange(
945
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
946
+ )
947
+ if position_ids is None:
948
+ position_ids = cache_position.unsqueeze(0)
949
+
950
+ causal_mask = self._update_causal_mask(
951
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
952
+ )
953
+
954
+ hidden_states = inputs_embeds
955
+
956
+ # decoder layers
957
+ all_hidden_states = () if output_hidden_states else None
958
+ all_self_attns = () if output_attentions else None
959
+ next_decoder_cache = None
960
+
961
+ for decoder_layer in self.layers:
962
+ if output_hidden_states:
963
+ all_hidden_states += (hidden_states,)
964
+
965
+ if self.gradient_checkpointing and self.training:
966
+ layer_outputs = self._gradient_checkpointing_func(
967
+ decoder_layer.__call__,
968
+ hidden_states,
969
+ causal_mask,
970
+ position_ids,
971
+ past_key_values,
972
+ output_attentions,
973
+ use_cache,
974
+ cache_position,
975
+ )
976
+ else:
977
+ layer_outputs = decoder_layer(
978
+ hidden_states,
979
+ attention_mask=causal_mask,
980
+ position_ids=position_ids,
981
+ past_key_value=past_key_values,
982
+ output_attentions=output_attentions,
983
+ use_cache=use_cache,
984
+ cache_position=cache_position,
985
+ )
986
+
987
+ hidden_states = layer_outputs[0]
988
+
989
+ if use_cache:
990
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
991
+
992
+ if output_attentions:
993
+ all_self_attns += (layer_outputs[1],)
994
+
995
+ hidden_states = self.norm(hidden_states)
996
+
997
+ # add hidden states from the last decoder layer
998
+ if output_hidden_states:
999
+ all_hidden_states += (hidden_states,)
1000
+
1001
+ next_cache = next_decoder_cache if use_cache else None
1002
+ if return_legacy_cache:
1003
+ next_cache = next_cache.to_legacy_cache()
1004
+
1005
+ if not return_dict:
1006
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1007
+ return BaseModelOutputWithPast(
1008
+ last_hidden_state=hidden_states,
1009
+ past_key_values=next_cache,
1010
+ hidden_states=all_hidden_states,
1011
+ attentions=all_self_attns,
1012
+ )
1013
+
1014
+ def _update_causal_mask(
1015
+ self,
1016
+ attention_mask: torch.Tensor,
1017
+ input_tensor: torch.Tensor,
1018
+ cache_position: torch.Tensor,
1019
+ past_key_values: Cache,
1020
+ output_attentions: bool,
1021
+ ):
1022
+ if self.config._attn_implementation == "flash_attention_2":
1023
+ if attention_mask is not None and 0.0 in attention_mask:
1024
+ return attention_mask
1025
+ return None
1026
+
1027
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1028
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1029
+ # to infer the attention mask.
1030
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1031
+ using_static_cache = isinstance(past_key_values, StaticCache)
1032
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
1033
+
1034
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1035
+ if (
1036
+ self.config._attn_implementation == "sdpa"
1037
+ and not (using_static_cache or using_sliding_window_cache)
1038
+ and not output_attentions
1039
+ ):
1040
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1041
+ attention_mask,
1042
+ inputs_embeds=input_tensor,
1043
+ past_key_values_length=past_seen_tokens,
1044
+ sliding_window=self.config.sliding_window,
1045
+ is_training=self.training,
1046
+ ):
1047
+ return None
1048
+
1049
+ dtype, device = input_tensor.dtype, input_tensor.device
1050
+ min_dtype = torch.finfo(dtype).min
1051
+ sequence_length = input_tensor.shape[1]
1052
+ # SlidingWindowCache or StaticCache
1053
+ if using_sliding_window_cache or using_static_cache:
1054
+ target_length = past_key_values.get_max_cache_shape()
1055
+ # DynamicCache or no cache
1056
+ else:
1057
+ target_length = (
1058
+ attention_mask.shape[-1]
1059
+ if isinstance(attention_mask, torch.Tensor)
1060
+ else past_seen_tokens + sequence_length + 1
1061
+ )
1062
+
1063
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1064
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1065
+ attention_mask,
1066
+ sequence_length=sequence_length,
1067
+ target_length=target_length,
1068
+ dtype=dtype,
1069
+ device=device,
1070
+ cache_position=cache_position,
1071
+ batch_size=input_tensor.shape[0],
1072
+ config=self.config,
1073
+ past_key_values=past_key_values,
1074
+ )
1075
+
1076
+ if (
1077
+ self.config._attn_implementation == "sdpa"
1078
+ and attention_mask is not None
1079
+ and attention_mask.device.type == "cuda"
1080
+ and not output_attentions
1081
+ ):
1082
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1083
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1084
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1085
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1086
+
1087
+ return causal_mask
1088
+
1089
+ @staticmethod
1090
+ # Copied from transformers.models.mistral.modeling_mistral.MistralModel._prepare_4d_causal_attention_mask_with_cache_position with Mistral->Phi3
1091
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1092
+ attention_mask: torch.Tensor,
1093
+ sequence_length: int,
1094
+ target_length: int,
1095
+ dtype: torch.dtype,
1096
+ device: torch.device,
1097
+ cache_position: torch.Tensor,
1098
+ batch_size: int,
1099
+ config: Phi3Config,
1100
+ past_key_values: Cache,
1101
+ ):
1102
+ """
1103
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1104
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1105
+
1106
+ Args:
1107
+ attention_mask (`torch.Tensor`):
1108
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
1109
+ sequence_length (`int`):
1110
+ The sequence length being processed.
1111
+ target_length (`int`):
1112
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
1113
+ dtype (`torch.dtype`):
1114
+ The dtype to use for the 4D attention mask.
1115
+ device (`torch.device`):
1116
+ The device to plcae the 4D attention mask on.
1117
+ cache_position (`torch.Tensor`):
1118
+ Indices depicting the position of the input sequence tokens in the sequence.
1119
+ batch_size (`torch.Tensor`):
1120
+ Batch size.
1121
+ config (`Phi3Config`):
1122
+ The model's configuration class
1123
+ past_key_values (`Cache`):
1124
+ The cache class that is being used currently to generate
1125
+ """
1126
+ if attention_mask is not None and attention_mask.dim() == 4:
1127
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1128
+ causal_mask = attention_mask
1129
+ else:
1130
+ min_dtype = torch.finfo(dtype).min
1131
+ causal_mask = torch.full(
1132
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1133
+ )
1134
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1135
+ if config.sliding_window is not None:
1136
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1137
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1138
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
1139
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
1140
+ cache_position.reshape(-1, 1) - config.sliding_window
1141
+ )
1142
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1143
+ causal_mask *= diagonal_attend_mask
1144
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1145
+ if attention_mask is not None:
1146
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1147
+ if attention_mask.shape[-1] > target_length:
1148
+ attention_mask = attention_mask[:, :target_length]
1149
+ mask_length = attention_mask.shape[-1]
1150
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1151
+ padding_mask = padding_mask == 0
1152
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1153
+ padding_mask, min_dtype
1154
+ )
1155
+ return causal_mask
1156
+
1157
+
1158
+ class Phi3ForCausalLM(Phi3PreTrainedModel, GenerationMixin):
1159
+ _tied_weights_keys = ["lm_head.weight"]
1160
+
1161
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1162
+ def __init__(self, config):
1163
+ super().__init__(config)
1164
+ self.model = Phi3Model(config)
1165
+ self.vocab_size = config.vocab_size
1166
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1167
+
1168
+ # Initialize weights and apply final processing
1169
+ self.post_init()
1170
+
1171
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1172
+ def get_input_embeddings(self):
1173
+ return self.model.embed_tokens
1174
+
1175
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1176
+ def set_input_embeddings(self, value):
1177
+ self.model.embed_tokens = value
1178
+
1179
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1180
+ def get_output_embeddings(self):
1181
+ return self.lm_head
1182
+
1183
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1184
+ def set_output_embeddings(self, new_embeddings):
1185
+ self.lm_head = new_embeddings
1186
+
1187
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1188
+ def set_decoder(self, decoder):
1189
+ self.model = decoder
1190
+
1191
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1192
+ def get_decoder(self):
1193
+ return self.model
1194
+
1195
+ # Ignore copy
1196
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1197
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1198
+ def forward(
1199
+ self,
1200
+ input_ids: torch.LongTensor = None,
1201
+ attention_mask: Optional[torch.Tensor] = None,
1202
+ position_ids: Optional[torch.LongTensor] = None,
1203
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1204
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1205
+ labels: Optional[torch.LongTensor] = None,
1206
+ use_cache: Optional[bool] = None,
1207
+ output_attentions: Optional[bool] = None,
1208
+ output_hidden_states: Optional[bool] = None,
1209
+ return_dict: Optional[bool] = None,
1210
+ cache_position: Optional[torch.LongTensor] = None,
1211
+ num_logits_to_keep: int = 0,
1212
+ **loss_kwargs,
1213
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1214
+ r"""
1215
+ Args:
1216
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1217
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1218
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1219
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1220
+
1221
+ num_logits_to_keep (`int`, *optional*):
1222
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1223
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1224
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1225
+
1226
+ Returns:
1227
+
1228
+ Example:
1229
+
1230
+ ```python
1231
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1232
+
1233
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1234
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1235
+
1236
+ >>> prompt = "This is an example script ."
1237
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1238
+
1239
+ >>> # Generate
1240
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1241
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1242
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1243
+ ```"""
1244
+ if (
1245
+ use_cache
1246
+ and self.config.rope_scaling
1247
+ and cache_position is not None
1248
+ and cache_position[0] == self.config.original_max_position_embeddings
1249
+ ):
1250
+ logger.warning(
1251
+ f"If you are not using the generate method, you may encounter nonsensical outputs after the {self.config.original_max_position_embeddings}th token, as the KV cache needs to be recomputed."
1252
+ )
1253
+
1254
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1255
+ output_hidden_states = (
1256
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1257
+ )
1258
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1259
+
1260
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1261
+ outputs = self.model(
1262
+ input_ids=input_ids,
1263
+ attention_mask=attention_mask,
1264
+ position_ids=position_ids,
1265
+ past_key_values=past_key_values,
1266
+ inputs_embeds=inputs_embeds,
1267
+ use_cache=use_cache,
1268
+ output_attentions=output_attentions,
1269
+ output_hidden_states=output_hidden_states,
1270
+ return_dict=return_dict,
1271
+ )
1272
+
1273
+ hidden_states = outputs[0]
1274
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1275
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1276
+
1277
+ loss = None
1278
+ if labels is not None:
1279
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
1280
+
1281
+ if not return_dict:
1282
+ output = (logits,) + outputs[1:]
1283
+ return (loss,) + output if loss is not None else output
1284
+
1285
+ return CausalLMOutputWithPast(
1286
+ loss=loss,
1287
+ logits=logits,
1288
+ past_key_values=outputs.past_key_values,
1289
+ hidden_states=outputs.hidden_states,
1290
+ attentions=outputs.attentions,
1291
+ )
1292
+
1293
+ def prepare_inputs_for_generation(
1294
+ self,
1295
+ input_ids,
1296
+ past_key_values=None,
1297
+ attention_mask=None,
1298
+ inputs_embeds=None,
1299
+ cache_position=None,
1300
+ position_ids=None,
1301
+ use_cache=True,
1302
+ num_logits_to_keep=None,
1303
+ **kwargs,
1304
+ ):
1305
+ # Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the
1306
+ # process
1307
+
1308
+ # When the first time input length reached long and short factor switching point, enforce re-compute cache
1309
+ # It will cause downside of slower at this single token position, however, better than current failure.
1310
+ if (
1311
+ past_key_values
1312
+ and self.config.rope_scaling
1313
+ and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1
1314
+ ):
1315
+ past_length = cache_position[0]
1316
+ if past_length <= self.config.original_max_position_embeddings:
1317
+ past_key_values = None
1318
+
1319
+ model_inputs = super().prepare_inputs_for_generation(
1320
+ input_ids=input_ids,
1321
+ past_key_values=past_key_values,
1322
+ attention_mask=attention_mask,
1323
+ inputs_embeds=inputs_embeds,
1324
+ cache_position=cache_position,
1325
+ position_ids=position_ids,
1326
+ use_cache=use_cache,
1327
+ num_logits_to_keep=num_logits_to_keep,
1328
+ **kwargs,
1329
+ )
1330
+ return model_inputs
1331
+
1332
+
1333
+ @add_start_docstrings(
1334
+ """
1335
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1336
+
1337
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1338
+ (e.g. GPT-2) do.
1339
+
1340
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1341
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1342
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1343
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1344
+ each row of the batch).
1345
+ """,
1346
+ PHI3_START_DOCSTRING,
1347
+ )
1348
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1349
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1350
+ def __init__(self, config):
1351
+ super().__init__(config)
1352
+ self.num_labels = config.num_labels
1353
+ self.model = Phi3Model(config)
1354
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1355
+
1356
+ # Initialize weights and apply final processing
1357
+ self.post_init()
1358
+
1359
+ def get_input_embeddings(self):
1360
+ return self.model.embed_tokens
1361
+
1362
+ def set_input_embeddings(self, value):
1363
+ self.model.embed_tokens = value
1364
+
1365
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1366
+ def forward(
1367
+ self,
1368
+ input_ids: Optional[torch.LongTensor] = None,
1369
+ attention_mask: Optional[torch.Tensor] = None,
1370
+ position_ids: Optional[torch.LongTensor] = None,
1371
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1372
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1373
+ labels: Optional[torch.LongTensor] = None,
1374
+ use_cache: Optional[bool] = None,
1375
+ output_attentions: Optional[bool] = None,
1376
+ output_hidden_states: Optional[bool] = None,
1377
+ return_dict: Optional[bool] = None,
1378
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1379
+ r"""
1380
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1381
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1382
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1383
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1384
+ """
1385
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1386
+
1387
+ model_outputs = self.model(
1388
+ input_ids,
1389
+ attention_mask=attention_mask,
1390
+ position_ids=position_ids,
1391
+ past_key_values=past_key_values,
1392
+ inputs_embeds=inputs_embeds,
1393
+ use_cache=use_cache,
1394
+ output_attentions=output_attentions,
1395
+ output_hidden_states=output_hidden_states,
1396
+ return_dict=return_dict,
1397
+ )
1398
+ hidden_states = model_outputs[0]
1399
+ logits = self.score(hidden_states)
1400
+
1401
+ if input_ids is not None:
1402
+ batch_size = input_ids.shape[0]
1403
+ else:
1404
+ batch_size = inputs_embeds.shape[0]
1405
+
1406
+ if self.config.pad_token_id is None and batch_size != 1:
1407
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1408
+ if self.config.pad_token_id is None:
1409
+ sequence_lengths = -1
1410
+ else:
1411
+ if input_ids is not None:
1412
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1413
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1414
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1415
+ sequence_lengths = sequence_lengths.to(logits.device)
1416
+ else:
1417
+ sequence_lengths = -1
1418
+
1419
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1420
+
1421
+ loss = None
1422
+ if labels is not None:
1423
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1424
+
1425
+ if not return_dict:
1426
+ output = (pooled_logits,) + model_outputs[1:]
1427
+ return ((loss,) + output) if loss is not None else output
1428
+
1429
+ return SequenceClassifierOutputWithPast(
1430
+ loss=loss,
1431
+ logits=pooled_logits,
1432
+ past_key_values=model_outputs.past_key_values,
1433
+ hidden_states=model_outputs.hidden_states,
1434
+ attentions=model_outputs.attentions,
1435
+ )
1436
+
1437
+
1438
+ @add_start_docstrings(
1439
+ """
1440
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1441
+ Named-Entity-Recognition (NER) tasks.
1442
+ """,
1443
+ PHI3_START_DOCSTRING,
1444
+ )
1445
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1446
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1447
+ def __init__(self, config: Phi3Config):
1448
+ super().__init__(config)
1449
+ self.num_labels = config.num_labels
1450
+
1451
+ self.model = Phi3Model(config)
1452
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1453
+ classifier_dropout = config.classifier_dropout
1454
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1455
+ classifier_dropout = config.hidden_dropout
1456
+ else:
1457
+ classifier_dropout = 0.1
1458
+ self.dropout = nn.Dropout(classifier_dropout)
1459
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1460
+
1461
+ # Initialize weights and apply final processing
1462
+ self.post_init()
1463
+
1464
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1465
+ @add_code_sample_docstrings(
1466
+ checkpoint=_CHECKPOINT_FOR_DOC,
1467
+ output_type=TokenClassifierOutput,
1468
+ config_class=_CONFIG_FOR_DOC,
1469
+ )
1470
+ def forward(
1471
+ self,
1472
+ input_ids: Optional[torch.LongTensor] = None,
1473
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1474
+ attention_mask: Optional[torch.Tensor] = None,
1475
+ inputs_embeds: Optional[torch.Tensor] = None,
1476
+ labels: Optional[torch.Tensor] = None,
1477
+ use_cache: Optional[bool] = None,
1478
+ output_attentions: Optional[bool] = None,
1479
+ output_hidden_states: Optional[bool] = None,
1480
+ return_dict: Optional[bool] = None,
1481
+ **deprecated_arguments,
1482
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1483
+ r"""
1484
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1485
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1486
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1487
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1488
+ """
1489
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1490
+
1491
+ model_outputs = self.model(
1492
+ input_ids,
1493
+ past_key_values=past_key_values,
1494
+ attention_mask=attention_mask,
1495
+ inputs_embeds=inputs_embeds,
1496
+ use_cache=use_cache,
1497
+ output_attentions=output_attentions,
1498
+ output_hidden_states=output_hidden_states,
1499
+ return_dict=return_dict,
1500
+ )
1501
+
1502
+ hidden_states = model_outputs[0]
1503
+ hidden_states = self.dropout(hidden_states)
1504
+ logits = self.classifier(hidden_states)
1505
+
1506
+ loss = None
1507
+ if labels is not None:
1508
+ # move labels to correct device to enable model parallelism
1509
+ labels = labels.to(logits.device)
1510
+ batch_size, seq_length = labels.shape
1511
+ loss_fct = CrossEntropyLoss()
1512
+ loss = loss_fct(
1513
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1514
+ )
1515
+
1516
+ if not return_dict:
1517
+ output = (logits,) + model_outputs[2:]
1518
+ return ((loss,) + output) if loss is not None else output
1519
+
1520
+ return TokenClassifierOutput(
1521
+ loss=loss,
1522
+ logits=logits,
1523
+ hidden_states=model_outputs.hidden_states,
1524
+ attentions=model_outputs.attentions,
1525
+ )