HridaAIofficial commited on
Commit
3be18e9
1 Parent(s): d678ef5

Upload 11 files

Browse files
added_tokens.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|assistant|>": 32001,
3
+ "<|endoftext|>": 32000,
4
+ "<|end|>": 32007,
5
+ "<|placeholder1|>": 32002,
6
+ "<|placeholder2|>": 32003,
7
+ "<|placeholder3|>": 32004,
8
+ "<|placeholder4|>": 32005,
9
+ "<|placeholder5|>": 32008,
10
+ "<|placeholder6|>": 32009,
11
+ "<|system|>": 32006,
12
+ "<|user|>": 32010
13
+ }
config.json ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Phi3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3.Phi3Config",
9
+ "AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM",
10
+ "AutoModelForSequenceClassification": "modeling_phi3.Phi3ForSequenceClassification",
11
+ "AutoModelForTokenClassification": "modeling_phi3.Phi3ForTokenClassification"
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.0299999713897705,
32
+ 1.0499999523162842,
33
+ 1.0499999523162842,
34
+ 1.0799999237060547,
35
+ 1.2299998998641968,
36
+ 1.2299998998641968,
37
+ 1.2999999523162842,
38
+ 1.4499999284744263,
39
+ 1.5999999046325684,
40
+ 1.6499998569488525,
41
+ 1.8999998569488525,
42
+ 2.859999895095825,
43
+ 3.68999981880188,
44
+ 5.419999599456787,
45
+ 5.489999771118164,
46
+ 5.489999771118164,
47
+ 9.09000015258789,
48
+ 11.579999923706055,
49
+ 15.65999984741211,
50
+ 15.769999504089355,
51
+ 15.789999961853027,
52
+ 18.360000610351562,
53
+ 21.989999771118164,
54
+ 23.079999923706055,
55
+ 30.009998321533203,
56
+ 32.35000228881836,
57
+ 32.590003967285156,
58
+ 35.56000518798828,
59
+ 39.95000457763672,
60
+ 53.840003967285156,
61
+ 56.20000457763672,
62
+ 57.95000457763672,
63
+ 59.29000473022461,
64
+ 59.77000427246094,
65
+ 59.920005798339844,
66
+ 61.190006256103516,
67
+ 61.96000671386719,
68
+ 62.50000762939453,
69
+ 63.3700065612793,
70
+ 63.48000717163086,
71
+ 63.48000717163086,
72
+ 63.66000747680664,
73
+ 63.850006103515625,
74
+ 64.08000946044922,
75
+ 64.760009765625,
76
+ 64.80001068115234,
77
+ 64.81001281738281,
78
+ 64.81001281738281
79
+ ],
80
+ "short_factor": [
81
+ 1.05,
82
+ 1.05,
83
+ 1.05,
84
+ 1.1,
85
+ 1.1,
86
+ 1.1500000000000001,
87
+ 1.2000000000000002,
88
+ 1.2500000000000002,
89
+ 1.3000000000000003,
90
+ 1.3500000000000003,
91
+ 1.5000000000000004,
92
+ 2.000000000000001,
93
+ 2.000000000000001,
94
+ 2.000000000000001,
95
+ 2.000000000000001,
96
+ 2.000000000000001,
97
+ 2.000000000000001,
98
+ 2.000000000000001,
99
+ 2.000000000000001,
100
+ 2.000000000000001,
101
+ 2.000000000000001,
102
+ 2.000000000000001,
103
+ 2.000000000000001,
104
+ 2.000000000000001,
105
+ 2.000000000000001,
106
+ 2.000000000000001,
107
+ 2.000000000000001,
108
+ 2.000000000000001,
109
+ 2.000000000000001,
110
+ 2.000000000000001,
111
+ 2.000000000000001,
112
+ 2.000000000000001,
113
+ 2.0500000000000007,
114
+ 2.0500000000000007,
115
+ 2.0500000000000007,
116
+ 2.1000000000000005,
117
+ 2.1000000000000005,
118
+ 2.1000000000000005,
119
+ 2.1500000000000004,
120
+ 2.1500000000000004,
121
+ 2.3499999999999996,
122
+ 2.549999999999999,
123
+ 2.5999999999999988,
124
+ 2.5999999999999988,
125
+ 2.7499999999999982,
126
+ 2.849999999999998,
127
+ 2.849999999999998,
128
+ 2.9499999999999975
129
+ ],
130
+ "type": "su"
131
+ },
132
+ "rope_theta": 10000.0,
133
+ "sliding_window": 262144,
134
+ "tie_word_embeddings": false,
135
+ "torch_dtype": "bfloat16",
136
+ "transformers_version": "4.39.3",
137
+ "use_cache": true,
138
+ "vocab_size": 32064
139
+ }
configuration_phi3.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json",
27
+ "microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class Phi3Config(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the
36
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32064):
43
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Phi3Model`].
45
+ hidden_size (`int`, *optional*, defaults to 3072):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 8192):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
62
+ Dropout probability for mlp outputs.
63
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the embeddings.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio after computing the attention scores.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model might ever be used with.
71
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
73
+ original RoPE embeddings when using long scaling.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon value used for the RMSNorm.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`dict`, *optional*):
86
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be either `su` or `yarn` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ The id of the "beginning-of-sequence" token.
92
+ eos_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the "end-of-sequence" token.
94
+ pad_token_id (`int`, *optional*, defaults to 32000):
95
+ The id of the padding token.
96
+ sliding_window (`int`, *optional*):
97
+ Sliding window attention window size. If `None`, no sliding window is applied.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import Phi3Model, Phi3Config
103
+
104
+ >>> # Initializing a Phi-3 style configuration
105
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = Phi3Model(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32064,
120
+ hidden_size=3072,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="silu",
129
+ max_position_embeddings=4096,
130
+ original_max_position_embeddings=4096,
131
+ initializer_range=0.02,
132
+ rms_norm_eps=1e-5,
133
+ use_cache=True,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ bos_token_id=1,
138
+ eos_token_id=32000,
139
+ pad_token_id=32000,
140
+ sliding_window=None,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.hidden_size = hidden_size
145
+ self.intermediate_size = intermediate_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.resid_pdrop = resid_pdrop
154
+ self.embd_pdrop = embd_pdrop
155
+ self.attention_dropout = attention_dropout
156
+ self.hidden_act = hidden_act
157
+ self.max_position_embeddings = max_position_embeddings
158
+ self.original_max_position_embeddings = original_max_position_embeddings
159
+ self.initializer_range = initializer_range
160
+ self.rms_norm_eps = rms_norm_eps
161
+ self.use_cache = use_cache
162
+ self.rope_theta = rope_theta
163
+ self.rope_scaling = rope_scaling
164
+ self._rope_scaling_validation()
165
+ self.sliding_window = sliding_window
166
+
167
+ super().__init__(
168
+ bos_token_id=bos_token_id,
169
+ eos_token_id=eos_token_id,
170
+ pad_token_id=pad_token_id,
171
+ tie_word_embeddings=tie_word_embeddings,
172
+ **kwargs,
173
+ )
174
+
175
+ def _rope_scaling_validation(self):
176
+ """
177
+ Validate the `rope_scaling` configuration.
178
+ """
179
+ if self.rope_scaling is None:
180
+ return
181
+
182
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
183
+ raise ValueError(
184
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
185
+ f"got {self.rope_scaling}"
186
+ )
187
+ rope_scaling_type = self.rope_scaling.get("type", None)
188
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
189
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
190
+ if rope_scaling_type is None or rope_scaling_type not in ["su", "yarn"]:
191
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
192
+ if not (
193
+ isinstance(rope_scaling_short_factor, list)
194
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
195
+ ):
196
+ raise ValueError(
197
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
198
+ )
199
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
200
+ raise ValueError(
201
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
202
+ )
203
+ if not (
204
+ isinstance(rope_scaling_long_factor, list)
205
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
206
+ ):
207
+ raise ValueError(
208
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
209
+ )
210
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
211
+ raise ValueError(
212
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
213
+ )
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0f504204ef88a41c3a36c3e7ad8f7292a524642aec9b4fcf3d8650c8252ef0d
3
+ size 5356281360
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddc323b2152c4160cac4e2c6794aa15b725d07ce4f3c735d52e50493d5282e9f
3
+ size 2285900500
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-00002-of-00002.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.1.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.10.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.11.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.11.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.12.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.12.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.13.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.13.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.14.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.14.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.15.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.15.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.16.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.16.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.17.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.17.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.18.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.18.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.19.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.19.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.2.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.2.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
88
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
90
+ "model.layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.20.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors",
93
+ "model.layers.21.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
94
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
95
+ "model.layers.21.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
96
+ "model.layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.21.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
98
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
99
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
100
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
101
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
102
+ "model.layers.22.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
103
+ "model.layers.22.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
104
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
105
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
106
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
107
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
108
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
109
+ "model.layers.23.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
110
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
111
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
112
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
113
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
114
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
115
+ "model.layers.24.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
116
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
117
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
118
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
119
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
120
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
121
+ "model.layers.25.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
122
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
123
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
124
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
125
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
126
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
127
+ "model.layers.26.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
128
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
129
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
130
+ "model.layers.27.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
131
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
132
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
133
+ "model.layers.27.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
134
+ "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
135
+ "model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
136
+ "model.layers.28.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
137
+ "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
138
+ "model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
139
+ "model.layers.28.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
140
+ "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
141
+ "model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
142
+ "model.layers.29.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
143
+ "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
144
+ "model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
145
+ "model.layers.29.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
146
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.3.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.3.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
153
+ "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
154
+ "model.layers.30.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
155
+ "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
156
+ "model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
157
+ "model.layers.30.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
158
+ "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
159
+ "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
160
+ "model.layers.31.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
161
+ "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
162
+ "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
163
+ "model.layers.31.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
164
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
165
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
166
+ "model.layers.4.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
167
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
168
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
169
+ "model.layers.4.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
170
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
171
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
172
+ "model.layers.5.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
173
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
174
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
175
+ "model.layers.5.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
176
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
177
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
178
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
179
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
180
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
181
+ "model.layers.6.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
182
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
183
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
184
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
185
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
186
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
187
+ "model.layers.7.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
188
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.8.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.8.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.9.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
199
+ "model.layers.9.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
200
+ "model.norm.weight": "model-00002-of-00002.safetensors"
201
+ }
202
+ }
modeling_phi3.py ADDED
@@ -0,0 +1,1604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import inspect
17
+ import math
18
+ import warnings
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from transformers.activations import ACT2FN
28
+ from transformers.cache_utils import Cache, DynamicCache
29
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
30
+ from transformers.modeling_outputs import (
31
+ BaseModelOutputWithPast,
32
+ CausalLMOutputWithPast,
33
+ SequenceClassifierOutputWithPast,
34
+ TokenClassifierOutput,
35
+ )
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.utils import (
38
+ add_code_sample_docstrings,
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ is_flash_attn_2_available,
42
+ is_flash_attn_greater_or_equal_2_10,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from .configuration_phi3 import Phi3Config
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
52
+ # if is_flash_attn_2_available():
53
+ _flash_supports_window_size = False
54
+ try:
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+
58
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
59
+ except ImportError as error:
60
+ logger.warning(
61
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
62
+ )
63
+ if not _flash_supports_window_size:
64
+ logger.warning(
65
+ "Current `flash-attenton` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
66
+ )
67
+
68
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
69
+ _CONFIG_FOR_DOC = "Phi3Config"
70
+
71
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
72
+ "microsoft/Phi-3-mini-4k-instruct",
73
+ "microsoft/Phi-3-mini-128k-instruct",
74
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
75
+ ]
76
+
77
+
78
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
79
+ class Phi3RMSNorm(nn.Module):
80
+ def __init__(self, hidden_size, eps=1e-6):
81
+ """
82
+ Phi3RMSNorm is equivalent to T5LayerNorm
83
+ """
84
+ super().__init__()
85
+ self.weight = nn.Parameter(torch.ones(hidden_size))
86
+ self.variance_epsilon = eps
87
+
88
+ def forward(self, hidden_states):
89
+ input_dtype = hidden_states.dtype
90
+ hidden_states = hidden_states.to(torch.float32)
91
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
92
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
93
+ return self.weight * hidden_states.to(input_dtype)
94
+
95
+
96
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
97
+ def _get_unpad_data(attention_mask):
98
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
99
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
100
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
101
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
102
+ return (
103
+ indices,
104
+ cu_seqlens,
105
+ max_seqlen_in_batch,
106
+ )
107
+
108
+
109
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
110
+ class Phi3RotaryEmbedding(nn.Module):
111
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
112
+ super().__init__()
113
+
114
+ self.dim = dim
115
+ self.max_position_embeddings = max_position_embeddings
116
+ self.base = base
117
+ self.register_buffer("inv_freq", None, persistent=False)
118
+
119
+ @torch.no_grad()
120
+ def forward(self, x, position_ids, seq_len=None):
121
+ # x: [bs, num_attention_heads, seq_len, head_size]
122
+ if self.inv_freq is None:
123
+ self.inv_freq = 1.0 / (
124
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
125
+ )
126
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
127
+ position_ids_expanded = position_ids[:, None, :].float()
128
+ # Force float32 since bfloat16 loses precision on long contexts
129
+ # See https://github.com/huggingface/transformers/pull/29285
130
+ device_type = x.device.type
131
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
132
+ with torch.autocast(device_type=device_type, enabled=False):
133
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
134
+ emb = torch.cat((freqs, freqs), dim=-1)
135
+ cos = emb.cos()
136
+ sin = emb.sin()
137
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
138
+
139
+
140
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
141
+ def __init__(self, dim, config, device=None):
142
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
143
+
144
+ self.short_factor = config.rope_scaling["short_factor"]
145
+ self.long_factor = config.rope_scaling["long_factor"]
146
+ self.original_max_position_embeddings = config.original_max_position_embeddings
147
+
148
+ @torch.no_grad()
149
+ def forward(self, x, position_ids, seq_len=None):
150
+ seq_len = torch.max(position_ids) + 1
151
+ if seq_len > self.original_max_position_embeddings:
152
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
153
+ else:
154
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
155
+
156
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
157
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
158
+
159
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
160
+ position_ids_expanded = position_ids[:, None, :].float()
161
+
162
+ # Force float32 since bfloat16 loses precision on long contexts
163
+ # See https://github.com/huggingface/transformers/pull/29285
164
+ device_type = x.device.type
165
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
166
+ with torch.autocast(device_type=device_type, enabled=False):
167
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
168
+ emb = torch.cat((freqs, freqs), dim=-1)
169
+
170
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
171
+ if scale <= 1.0:
172
+ scaling_factor = 1.0
173
+ else:
174
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
175
+
176
+ cos = emb.cos() * scaling_factor
177
+ sin = emb.sin() * scaling_factor
178
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
179
+
180
+
181
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
182
+ def __init__(self, dim, config, device=None):
183
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
184
+
185
+ self.short_factor = config.rope_scaling["short_factor"]
186
+ self.long_factor = config.rope_scaling["long_factor"]
187
+ self.original_max_position_embeddings = config.original_max_position_embeddings
188
+
189
+ @torch.no_grad()
190
+ def forward(self, x, position_ids, seq_len=None):
191
+ seq_len = torch.max(position_ids) + 1
192
+ if seq_len > self.original_max_position_embeddings:
193
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
194
+ else:
195
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
196
+
197
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
198
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
199
+
200
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
201
+ position_ids_expanded = position_ids[:, None, :].float()
202
+
203
+ # Force float32 since bfloat16 loses precision on long contexts
204
+ # See https://github.com/huggingface/transformers/pull/29285
205
+ device_type = x.device.type
206
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
207
+ with torch.autocast(device_type=device_type, enabled=False):
208
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
209
+ emb = torch.cat((freqs, freqs), dim=-1)
210
+
211
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
212
+ if scale <= 1.0:
213
+ scaling_factor = 1.0
214
+ else:
215
+ scaling_factor = 0.1 * math.log(scale) + 1.0
216
+
217
+ cos = emb.cos() * scaling_factor
218
+ sin = emb.sin() * scaling_factor
219
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
220
+
221
+
222
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
223
+ def rotate_half(x):
224
+ """Rotates half the hidden dims of the input."""
225
+ x1 = x[..., : x.shape[-1] // 2]
226
+ x2 = x[..., x.shape[-1] // 2 :]
227
+ return torch.cat((-x2, x1), dim=-1)
228
+
229
+
230
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
231
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
232
+ """Applies Rotary Position Embedding to the query and key tensors.
233
+
234
+ Args:
235
+ q (`torch.Tensor`): The query tensor.
236
+ k (`torch.Tensor`): The key tensor.
237
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
238
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
239
+ position_ids (`torch.Tensor`, *optional*):
240
+ Deprecated and unused.
241
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
242
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
243
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
244
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
245
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
246
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
247
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
248
+ Returns:
249
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
250
+ """
251
+ cos = cos.unsqueeze(unsqueeze_dim)
252
+ sin = sin.unsqueeze(unsqueeze_dim)
253
+ q_embed = (q * cos) + (rotate_half(q) * sin)
254
+ k_embed = (k * cos) + (rotate_half(k) * sin)
255
+ return q_embed, k_embed
256
+
257
+
258
+ class Phi3MLP(nn.Module):
259
+ def __init__(self, config):
260
+ super().__init__()
261
+
262
+ self.config = config
263
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
264
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
265
+
266
+ self.activation_fn = ACT2FN[config.hidden_act]
267
+
268
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
269
+ up_states = self.gate_up_proj(hidden_states)
270
+
271
+ gate, up_states = up_states.chunk(2, dim=-1)
272
+ up_states = up_states * self.activation_fn(gate)
273
+
274
+ return self.down_proj(up_states)
275
+
276
+
277
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
278
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
279
+ """
280
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
281
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
282
+ """
283
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
284
+ if n_rep == 1:
285
+ return hidden_states
286
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
287
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
288
+
289
+
290
+ class Phi3Attention(nn.Module):
291
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
292
+
293
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
294
+ super().__init__()
295
+ self.config = config
296
+ self.layer_idx = layer_idx
297
+ if layer_idx is None:
298
+ logger.warning_once(
299
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
300
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
301
+ "when creating this class."
302
+ )
303
+
304
+ self.attention_dropout = config.attention_dropout
305
+ self.hidden_size = config.hidden_size
306
+ self.num_heads = config.num_attention_heads
307
+ self.head_dim = self.hidden_size // self.num_heads
308
+ self.num_key_value_heads = config.num_key_value_heads
309
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
310
+ self.max_position_embeddings = config.max_position_embeddings
311
+ self.original_max_position_embeddings = config.original_max_position_embeddings
312
+ self.rope_theta = config.rope_theta
313
+ self.rope_scaling = config.rope_scaling
314
+ self.is_causal = True
315
+
316
+ if (self.head_dim * self.num_heads) != self.hidden_size:
317
+ raise ValueError(
318
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
319
+ f" and `num_heads`: {self.num_heads})."
320
+ )
321
+
322
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
323
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
324
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
325
+ self._init_rope()
326
+
327
+ def _init_rope(self):
328
+ if self.rope_scaling is None:
329
+ self.rotary_emb = Phi3RotaryEmbedding(
330
+ self.head_dim,
331
+ max_position_embeddings=self.max_position_embeddings,
332
+ base=self.rope_theta,
333
+ )
334
+ else:
335
+ scaling_type = self.config.rope_scaling["type"]
336
+ if scaling_type == "su":
337
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
338
+ elif scaling_type == "yarn":
339
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
340
+ else:
341
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
342
+
343
+ def forward(
344
+ self,
345
+ hidden_states: torch.Tensor,
346
+ attention_mask: Optional[torch.Tensor] = None,
347
+ position_ids: Optional[torch.LongTensor] = None,
348
+ past_key_value: Optional[Cache] = None,
349
+ output_attentions: bool = False,
350
+ use_cache: bool = False,
351
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
352
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
353
+
354
+ bsz, q_len, _ = hidden_states.size()
355
+
356
+ qkv = self.qkv_proj(hidden_states)
357
+ query_pos = self.num_heads * self.head_dim
358
+ query_states = qkv[..., :query_pos]
359
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
360
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
361
+
362
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
363
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
364
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
365
+
366
+ kv_seq_len = key_states.shape[-2]
367
+ if past_key_value is not None:
368
+ if self.layer_idx is None:
369
+ raise ValueError(
370
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
371
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
372
+ "with a layer index."
373
+ )
374
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
375
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
376
+
377
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
378
+
379
+ if past_key_value is not None:
380
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
381
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
382
+
383
+ # repeat k/v heads if n_kv_heads < n_heads
384
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
385
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
386
+
387
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
388
+
389
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
390
+ raise ValueError(
391
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
392
+ f" {attn_weights.size()}"
393
+ )
394
+
395
+ if attention_mask is not None:
396
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
397
+ raise ValueError(
398
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
399
+ )
400
+ attn_weights = attn_weights + attention_mask
401
+
402
+ # upcast attention to fp32
403
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
404
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
405
+
406
+ attn_output = torch.matmul(attn_weights, value_states)
407
+
408
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
409
+ raise ValueError(
410
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
411
+ f" {attn_output.size()}"
412
+ )
413
+
414
+ attn_output = attn_output.transpose(1, 2).contiguous()
415
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
416
+
417
+ attn_output = self.o_proj(attn_output)
418
+
419
+ if not output_attentions:
420
+ attn_weights = None
421
+
422
+ return attn_output, attn_weights, past_key_value
423
+
424
+
425
+ class Phi3FlashAttention2(Phi3Attention):
426
+ """
427
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
428
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
429
+ flash attention and deal with padding tokens in case the input contains any of them.
430
+ """
431
+
432
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
433
+ def __init__(self, *args, **kwargs):
434
+ super().__init__(*args, **kwargs)
435
+
436
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
437
+ # 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.
438
+ # 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).
439
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
440
+
441
+ def forward(
442
+ self,
443
+ hidden_states: torch.Tensor,
444
+ attention_mask: Optional[torch.LongTensor] = None,
445
+ position_ids: Optional[torch.LongTensor] = None,
446
+ past_key_value: Optional[Cache] = None,
447
+ output_attentions: bool = False,
448
+ use_cache: bool = False,
449
+ **kwargs,
450
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
451
+ # Phi3FlashAttention2 attention does not support output_attentions
452
+
453
+ if not _flash_supports_window_size:
454
+ logger.warning_once(
455
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
456
+ )
457
+ raise ValueError("The current flash attention version does not support sliding window attention.")
458
+
459
+ output_attentions = False
460
+
461
+ if "padding_mask" in kwargs:
462
+ warnings.warn(
463
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
464
+ )
465
+
466
+ # overwrite attention_mask with padding_mask
467
+ attention_mask = kwargs.pop("padding_mask")
468
+
469
+ bsz, q_len, _ = hidden_states.size()
470
+
471
+ qkv = self.qkv_proj(hidden_states)
472
+ query_pos = self.num_heads * self.head_dim
473
+ query_states = qkv[..., :query_pos]
474
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
475
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
476
+
477
+ # Flash attention requires the input to have the shape
478
+ # batch_size x seq_length x head_dim x hidden_dim
479
+ # therefore we just need to keep the original shape
480
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
481
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
482
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
483
+
484
+ kv_seq_len = key_states.shape[-2]
485
+ if past_key_value is not None:
486
+ if self.layer_idx is None:
487
+ raise ValueError(
488
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
489
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
490
+ "with a layer index."
491
+ )
492
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
493
+
494
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
495
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
496
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
497
+
498
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
499
+
500
+ use_sliding_windows = (
501
+ _flash_supports_window_size
502
+ and getattr(self.config, "sliding_window", None) is not None
503
+ and kv_seq_len > self.config.sliding_window
504
+ )
505
+
506
+ if past_key_value is not None:
507
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
508
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
509
+ if (
510
+ getattr(self.config, "sliding_window", None) is not None
511
+ and kv_seq_len > self.config.sliding_window
512
+ and cache_has_contents
513
+ ):
514
+ slicing_tokens = 1 - self.config.sliding_window
515
+
516
+ past_key = past_key_value[self.layer_idx][0]
517
+ past_value = past_key_value[self.layer_idx][1]
518
+
519
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
520
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
521
+
522
+ if past_key.shape[-2] != self.config.sliding_window - 1:
523
+ raise ValueError(
524
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
525
+ f" {past_key.shape}"
526
+ )
527
+
528
+ if attention_mask is not None:
529
+ attention_mask = attention_mask[:, slicing_tokens:]
530
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
531
+
532
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
533
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
534
+
535
+ # repeat k/v heads if n_kv_heads < n_heads
536
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
537
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
538
+
539
+ attn_dropout = self.attention_dropout if self.training else 0.0
540
+
541
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
542
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
543
+ # cast them back in the correct dtype just to be sure everything works as expected.
544
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
545
+ # in fp32.
546
+
547
+ if query_states.dtype == torch.float32:
548
+ if torch.is_autocast_enabled():
549
+ target_dtype = torch.get_autocast_gpu_dtype()
550
+ # Handle the case where the model is quantized
551
+ elif hasattr(self.config, "_pre_quantization_dtype"):
552
+ target_dtype = self.config._pre_quantization_dtype
553
+ else:
554
+ target_dtype = self.qkv_proj.weight.dtype
555
+
556
+ logger.warning_once(
557
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
558
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
559
+ f" {target_dtype}."
560
+ )
561
+
562
+ query_states = query_states.to(target_dtype)
563
+ key_states = key_states.to(target_dtype)
564
+ value_states = value_states.to(target_dtype)
565
+
566
+ # Reashape to the expected shape for Flash Attention
567
+ query_states = query_states.transpose(1, 2)
568
+ key_states = key_states.transpose(1, 2)
569
+ value_states = value_states.transpose(1, 2)
570
+
571
+ attn_output = self._flash_attention_forward(
572
+ query_states,
573
+ key_states,
574
+ value_states,
575
+ attention_mask,
576
+ q_len,
577
+ dropout=attn_dropout,
578
+ use_sliding_windows=use_sliding_windows,
579
+ )
580
+
581
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
582
+ attn_output = self.o_proj(attn_output)
583
+
584
+ if not output_attentions:
585
+ attn_weights = None
586
+
587
+ return attn_output, attn_weights, past_key_value
588
+
589
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
590
+ def _flash_attention_forward(
591
+ self,
592
+ query_states,
593
+ key_states,
594
+ value_states,
595
+ attention_mask,
596
+ query_length,
597
+ dropout=0.0,
598
+ softmax_scale=None,
599
+ use_sliding_windows=False,
600
+ ):
601
+ """
602
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
603
+ first unpad the input, then computes the attention scores and pad the final attention scores.
604
+
605
+ Args:
606
+ query_states (`torch.Tensor`):
607
+ Input query states to be passed to Flash Attention API
608
+ key_states (`torch.Tensor`):
609
+ Input key states to be passed to Flash Attention API
610
+ value_states (`torch.Tensor`):
611
+ Input value states to be passed to Flash Attention API
612
+ attention_mask (`torch.Tensor`):
613
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
614
+ position of padding tokens and 1 for the position of non-padding tokens.
615
+ dropout (`float`):
616
+ Attention dropout
617
+ softmax_scale (`float`, *optional*):
618
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
619
+ use_sliding_windows (`bool`, *optional*):
620
+ Whether to activate sliding window attention.
621
+ """
622
+ if not self._flash_attn_uses_top_left_mask:
623
+ causal = self.is_causal
624
+ else:
625
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
626
+ causal = self.is_causal and query_length != 1
627
+
628
+ # Contains at least one padding token in the sequence
629
+ if attention_mask is not None:
630
+ batch_size = query_states.shape[0]
631
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
632
+ query_states, key_states, value_states, attention_mask, query_length
633
+ )
634
+
635
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
636
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
637
+
638
+ if not use_sliding_windows:
639
+ attn_output_unpad = flash_attn_varlen_func(
640
+ query_states,
641
+ key_states,
642
+ value_states,
643
+ cu_seqlens_q=cu_seqlens_q,
644
+ cu_seqlens_k=cu_seqlens_k,
645
+ max_seqlen_q=max_seqlen_in_batch_q,
646
+ max_seqlen_k=max_seqlen_in_batch_k,
647
+ dropout_p=dropout,
648
+ softmax_scale=softmax_scale,
649
+ causal=causal,
650
+ )
651
+ else:
652
+ attn_output_unpad = flash_attn_varlen_func(
653
+ query_states,
654
+ key_states,
655
+ value_states,
656
+ cu_seqlens_q=cu_seqlens_q,
657
+ cu_seqlens_k=cu_seqlens_k,
658
+ max_seqlen_q=max_seqlen_in_batch_q,
659
+ max_seqlen_k=max_seqlen_in_batch_k,
660
+ dropout_p=dropout,
661
+ softmax_scale=softmax_scale,
662
+ causal=causal,
663
+ window_size=(self.config.sliding_window, self.config.sliding_window),
664
+ )
665
+
666
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
667
+ else:
668
+ if not use_sliding_windows:
669
+ attn_output = flash_attn_func(
670
+ query_states,
671
+ key_states,
672
+ value_states,
673
+ dropout,
674
+ softmax_scale=softmax_scale,
675
+ causal=causal,
676
+ )
677
+ else:
678
+ attn_output = flash_attn_func(
679
+ query_states,
680
+ key_states,
681
+ value_states,
682
+ dropout,
683
+ softmax_scale=softmax_scale,
684
+ causal=causal,
685
+ window_size=(self.config.sliding_window, self.config.sliding_window),
686
+ )
687
+
688
+ return attn_output
689
+
690
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
691
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
692
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
693
+
694
+ # On the first iteration we need to properly re-create the padding mask
695
+ # by slicing it on the proper place
696
+ if kv_seq_len != attention_mask.shape[-1]:
697
+ attention_mask_num_tokens = attention_mask.shape[-1]
698
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
699
+
700
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
701
+
702
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
703
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
704
+
705
+ if query_length == kv_seq_len:
706
+ query_layer = index_first_axis(
707
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
708
+ )
709
+ cu_seqlens_q = cu_seqlens_k
710
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
711
+ indices_q = indices_k
712
+ elif query_length == 1:
713
+ max_seqlen_in_batch_q = 1
714
+ cu_seqlens_q = torch.arange(
715
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
716
+ ) # There is a memcpy here, that is very bad.
717
+ indices_q = cu_seqlens_q[:-1]
718
+ query_layer = query_layer.squeeze(1)
719
+ else:
720
+ # The -q_len: slice assumes left padding.
721
+ attention_mask = attention_mask[:, -query_length:]
722
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
723
+
724
+ return (
725
+ query_layer,
726
+ key_layer,
727
+ value_layer,
728
+ indices_q,
729
+ (cu_seqlens_q, cu_seqlens_k),
730
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
731
+ )
732
+
733
+
734
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
735
+ # TODO @Arthur no longer copied from LLama after static cache
736
+ class Phi3SdpaAttention(Phi3Attention):
737
+ """
738
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
739
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
740
+ SDPA API.
741
+ """
742
+
743
+ # Adapted from Phi3Attention.forward
744
+ def forward(
745
+ self,
746
+ hidden_states: torch.Tensor,
747
+ attention_mask: Optional[torch.Tensor] = None,
748
+ position_ids: Optional[torch.LongTensor] = None,
749
+ past_key_value: Optional[Cache] = None,
750
+ output_attentions: bool = False,
751
+ use_cache: bool = False,
752
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
753
+ if output_attentions:
754
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
755
+ logger.warning_once(
756
+ "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, "
757
+ '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.'
758
+ )
759
+ return super().forward(
760
+ hidden_states=hidden_states,
761
+ attention_mask=attention_mask,
762
+ position_ids=position_ids,
763
+ past_key_value=past_key_value,
764
+ output_attentions=output_attentions,
765
+ use_cache=use_cache,
766
+ )
767
+
768
+ bsz, q_len, _ = hidden_states.size()
769
+
770
+ qkv = self.qkv_proj(hidden_states)
771
+ query_pos = self.num_heads * self.head_dim
772
+ query_states = qkv[..., :query_pos]
773
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
774
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
775
+
776
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
777
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
778
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
779
+
780
+ kv_seq_len = key_states.shape[-2]
781
+ if past_key_value is not None:
782
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
783
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
784
+
785
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
786
+
787
+ if past_key_value is not None:
788
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
789
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
790
+
791
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
792
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
793
+
794
+ if attention_mask is not None:
795
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
796
+ raise ValueError(
797
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
798
+ )
799
+
800
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
801
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
802
+ if query_states.device.type == "cuda" and attention_mask is not None:
803
+ query_states = query_states.contiguous()
804
+ key_states = key_states.contiguous()
805
+ value_states = value_states.contiguous()
806
+
807
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
808
+ query_states,
809
+ key_states,
810
+ value_states,
811
+ attn_mask=attention_mask,
812
+ dropout_p=self.attention_dropout if self.training else 0.0,
813
+ # 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.
814
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
815
+ )
816
+
817
+ attn_output = attn_output.transpose(1, 2).contiguous()
818
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
819
+
820
+ attn_output = self.o_proj(attn_output)
821
+
822
+ return attn_output, None, past_key_value
823
+
824
+
825
+ PHI3_ATTENTION_CLASSES = {
826
+ "eager": Phi3Attention,
827
+ "flash_attention_2": Phi3FlashAttention2,
828
+ "sdpa": Phi3SdpaAttention,
829
+ }
830
+
831
+
832
+ class Phi3DecoderLayer(nn.Module):
833
+ def __init__(self, config: Phi3Config, layer_idx: int):
834
+ super().__init__()
835
+
836
+ self.config = config
837
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
838
+
839
+ self.mlp = Phi3MLP(config)
840
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
841
+
842
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
843
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
844
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
845
+
846
+ def forward(
847
+ self,
848
+ hidden_states: torch.Tensor,
849
+ attention_mask: Optional[torch.Tensor] = None,
850
+ position_ids: Optional[torch.LongTensor] = None,
851
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
852
+ output_attentions: Optional[bool] = False,
853
+ use_cache: Optional[bool] = False,
854
+ **kwargs,
855
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
856
+ if "padding_mask" in kwargs:
857
+ warnings.warn(
858
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
859
+ )
860
+ """
861
+ Args:
862
+ hidden_states (`torch.FloatTensor`):
863
+ input to the layer of shape `(batch, seq_len, embed_dim)`
864
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
865
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
866
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
867
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
868
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
869
+ output_attentions (`bool`, *optional*):
870
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
871
+ returned tensors for more detail.
872
+ use_cache (`bool`, *optional*):
873
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
874
+ (see `past_key_values`).
875
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
876
+ """
877
+
878
+ residual = hidden_states
879
+
880
+ hidden_states = self.input_layernorm(hidden_states)
881
+
882
+ # Self Attention
883
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
884
+ hidden_states=hidden_states,
885
+ attention_mask=attention_mask,
886
+ position_ids=position_ids,
887
+ past_key_value=past_key_value,
888
+ output_attentions=output_attentions,
889
+ use_cache=use_cache,
890
+ )
891
+
892
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
893
+
894
+ residual = hidden_states
895
+ hidden_states = self.post_attention_layernorm(hidden_states)
896
+ hidden_states = self.mlp(hidden_states)
897
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
898
+
899
+ outputs = (hidden_states,)
900
+
901
+ if output_attentions:
902
+ outputs += (self_attn_weights,)
903
+
904
+ if use_cache:
905
+ outputs += (present_key_value,)
906
+
907
+ return outputs
908
+
909
+
910
+ PHI3_START_DOCSTRING = r"""
911
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
912
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
913
+ etc.)
914
+
915
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
916
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
917
+ and behavior.
918
+
919
+ Parameters:
920
+ config ([`Phi3Config`]):
921
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
922
+ load the weights associated with the model, only the configuration. Check out the
923
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
924
+ """
925
+
926
+
927
+ @add_start_docstrings(
928
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
929
+ PHI3_START_DOCSTRING,
930
+ )
931
+ class Phi3PreTrainedModel(PreTrainedModel):
932
+ config_class = Phi3Config
933
+ base_model_prefix = "model"
934
+ supports_gradient_checkpointing = True
935
+ _no_split_modules = ["Phi3DecoderLayer"]
936
+ _skip_keys_device_placement = "past_key_values"
937
+ _supports_flash_attn_2 = True
938
+ _supports_sdpa = False
939
+ _supports_cache_class = True
940
+
941
+ _version = "0.0.5"
942
+
943
+ def _init_weights(self, module):
944
+ std = self.config.initializer_range
945
+ if isinstance(module, nn.Linear):
946
+ module.weight.data.normal_(mean=0.0, std=std)
947
+ if module.bias is not None:
948
+ module.bias.data.zero_()
949
+ elif isinstance(module, nn.Embedding):
950
+ module.weight.data.normal_(mean=0.0, std=std)
951
+ if module.padding_idx is not None:
952
+ module.weight.data[module.padding_idx].zero_()
953
+
954
+
955
+ PHI3_INPUTS_DOCSTRING = r"""
956
+ Args:
957
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
958
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
959
+ it.
960
+
961
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
962
+ [`PreTrainedTokenizer.__call__`] for details.
963
+
964
+ [What are input IDs?](../glossary#input-ids)
965
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
966
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
967
+
968
+ - 1 for tokens that are **not masked**,
969
+ - 0 for tokens that are **masked**.
970
+
971
+ [What are attention masks?](../glossary#attention-mask)
972
+
973
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
974
+ [`PreTrainedTokenizer.__call__`] for details.
975
+
976
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
977
+ `past_key_values`).
978
+
979
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
980
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
981
+ information on the default strategy.
982
+
983
+ - 1 indicates the head is **not masked**,
984
+ - 0 indicates the head is **masked**.
985
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
986
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
987
+ config.n_positions - 1]`.
988
+
989
+ [What are position IDs?](../glossary#position-ids)
990
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
991
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
992
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
993
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
994
+
995
+ Two formats are allowed:
996
+ - a [`~cache_utils.Cache`] instance;
997
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
998
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
999
+ cache format.
1000
+
1001
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1002
+ legacy cache format will be returned.
1003
+
1004
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1005
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1006
+ of shape `(batch_size, sequence_length)`.
1007
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1008
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1009
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1010
+ model's internal embedding lookup matrix.
1011
+ use_cache (`bool`, *optional*):
1012
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1013
+ `past_key_values`).
1014
+ output_attentions (`bool`, *optional*):
1015
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1016
+ tensors for more detail.
1017
+ output_hidden_states (`bool`, *optional*):
1018
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1019
+ more detail.
1020
+ return_dict (`bool`, *optional*):
1021
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1022
+ """
1023
+
1024
+
1025
+ @add_start_docstrings(
1026
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
1027
+ PHI3_START_DOCSTRING,
1028
+ )
1029
+ class Phi3Model(Phi3PreTrainedModel):
1030
+ """
1031
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1032
+
1033
+ Args:
1034
+ config: Phi3Config
1035
+ """
1036
+
1037
+ def __init__(self, config: Phi3Config):
1038
+ super().__init__(config)
1039
+ self.padding_idx = config.pad_token_id
1040
+ self.vocab_size = config.vocab_size
1041
+
1042
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1043
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1044
+ self.layers = nn.ModuleList(
1045
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1046
+ )
1047
+ self._attn_implementation = config._attn_implementation
1048
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1049
+
1050
+ self.gradient_checkpointing = False
1051
+ # Initialize weights and apply final processing
1052
+ self.post_init()
1053
+
1054
+ def get_input_embeddings(self):
1055
+ return self.embed_tokens
1056
+
1057
+ def set_input_embeddings(self, value):
1058
+ self.embed_tokens = value
1059
+
1060
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1061
+ def forward(
1062
+ self,
1063
+ input_ids: torch.LongTensor = None,
1064
+ attention_mask: Optional[torch.Tensor] = None,
1065
+ position_ids: Optional[torch.LongTensor] = None,
1066
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1067
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1068
+ use_cache: Optional[bool] = None,
1069
+ output_attentions: Optional[bool] = None,
1070
+ output_hidden_states: Optional[bool] = None,
1071
+ return_dict: Optional[bool] = None,
1072
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1073
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1074
+ output_hidden_states = (
1075
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1076
+ )
1077
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1078
+
1079
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1080
+
1081
+ # retrieve input_ids and inputs_embeds
1082
+ if input_ids is not None and inputs_embeds is not None:
1083
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1084
+ elif input_ids is not None:
1085
+ batch_size, seq_length = input_ids.shape[:2]
1086
+ elif inputs_embeds is not None:
1087
+ batch_size, seq_length = inputs_embeds.shape[:2]
1088
+ else:
1089
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1090
+
1091
+ past_key_values_length = 0
1092
+
1093
+ if self.gradient_checkpointing and self.training:
1094
+ if use_cache:
1095
+ logger.warning_once(
1096
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1097
+ )
1098
+ use_cache = False
1099
+
1100
+ if use_cache:
1101
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1102
+ if use_legacy_cache:
1103
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1104
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1105
+
1106
+ if position_ids is None:
1107
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1108
+ position_ids = torch.arange(
1109
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1110
+ )
1111
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1112
+ else:
1113
+ position_ids = position_ids.view(-1, seq_length).long()
1114
+
1115
+ if inputs_embeds is None:
1116
+ inputs_embeds = self.embed_tokens(input_ids)
1117
+
1118
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1119
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1120
+ if is_padding_right:
1121
+ raise ValueError(
1122
+ "You are attempting to perform batched generation with padding_side='right'"
1123
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1124
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1125
+ )
1126
+
1127
+ if self._attn_implementation == "flash_attention_2":
1128
+ # 2d mask is passed through the layers
1129
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1130
+ else:
1131
+ # 4d mask is passed through the layers
1132
+ attention_mask = _prepare_4d_causal_attention_mask(
1133
+ attention_mask,
1134
+ (batch_size, seq_length),
1135
+ inputs_embeds,
1136
+ past_key_values_length,
1137
+ sliding_window=self.config.sliding_window,
1138
+ )
1139
+
1140
+ hidden_states = inputs_embeds
1141
+
1142
+ # decoder layers
1143
+ all_hidden_states = () if output_hidden_states else None
1144
+ all_self_attns = () if output_attentions else None
1145
+ next_decoder_cache = None
1146
+
1147
+ for decoder_layer in self.layers:
1148
+ if output_hidden_states:
1149
+ all_hidden_states += (hidden_states,)
1150
+
1151
+ if self.gradient_checkpointing and self.training:
1152
+ layer_outputs = self._gradient_checkpointing_func(
1153
+ decoder_layer.__call__,
1154
+ hidden_states,
1155
+ attention_mask,
1156
+ position_ids,
1157
+ past_key_values,
1158
+ output_attentions,
1159
+ use_cache,
1160
+ )
1161
+ else:
1162
+ layer_outputs = decoder_layer(
1163
+ hidden_states,
1164
+ attention_mask=attention_mask,
1165
+ position_ids=position_ids,
1166
+ past_key_value=past_key_values,
1167
+ output_attentions=output_attentions,
1168
+ use_cache=use_cache,
1169
+ )
1170
+
1171
+ hidden_states = layer_outputs[0]
1172
+
1173
+ if use_cache:
1174
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1175
+
1176
+ if output_attentions:
1177
+ all_self_attns += (layer_outputs[1],)
1178
+
1179
+ hidden_states = self.norm(hidden_states)
1180
+
1181
+ # add hidden states from the last decoder layer
1182
+ if output_hidden_states:
1183
+ all_hidden_states += (hidden_states,)
1184
+
1185
+ next_cache = None
1186
+ if use_cache:
1187
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1188
+ if not return_dict:
1189
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1190
+ return BaseModelOutputWithPast(
1191
+ last_hidden_state=hidden_states,
1192
+ past_key_values=next_cache,
1193
+ hidden_states=all_hidden_states,
1194
+ attentions=all_self_attns,
1195
+ )
1196
+
1197
+
1198
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1199
+ _tied_weights_keys = ["lm_head.weight"]
1200
+
1201
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1202
+ def __init__(self, config):
1203
+ super().__init__(config)
1204
+ self.model = Phi3Model(config)
1205
+ self.vocab_size = config.vocab_size
1206
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1207
+
1208
+ # Initialize weights and apply final processing
1209
+ self.post_init()
1210
+
1211
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1212
+ def get_input_embeddings(self):
1213
+ return self.model.embed_tokens
1214
+
1215
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1216
+ def set_input_embeddings(self, value):
1217
+ self.model.embed_tokens = value
1218
+
1219
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1220
+ def get_output_embeddings(self):
1221
+ return self.lm_head
1222
+
1223
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1224
+ def set_output_embeddings(self, new_embeddings):
1225
+ self.lm_head = new_embeddings
1226
+
1227
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1228
+ def set_decoder(self, decoder):
1229
+ self.model = decoder
1230
+
1231
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1232
+ def get_decoder(self):
1233
+ return self.model
1234
+
1235
+ # Ignore copy
1236
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1237
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1238
+ def forward(
1239
+ self,
1240
+ input_ids: torch.LongTensor = None,
1241
+ attention_mask: Optional[torch.Tensor] = None,
1242
+ position_ids: Optional[torch.LongTensor] = None,
1243
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1244
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1245
+ labels: Optional[torch.LongTensor] = None,
1246
+ use_cache: Optional[bool] = None,
1247
+ output_attentions: Optional[bool] = None,
1248
+ output_hidden_states: Optional[bool] = None,
1249
+ return_dict: Optional[bool] = None,
1250
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1251
+ r"""
1252
+ Args:
1253
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1254
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1255
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1256
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1257
+
1258
+ Returns:
1259
+
1260
+ Example:
1261
+
1262
+ ```python
1263
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1264
+
1265
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1266
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1267
+
1268
+ >>> prompt = "This is an example script ."
1269
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1270
+
1271
+ >>> # Generate
1272
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1273
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1274
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1275
+ ```"""
1276
+
1277
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1278
+ output_hidden_states = (
1279
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1280
+ )
1281
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1282
+
1283
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1284
+ outputs = self.model(
1285
+ input_ids=input_ids,
1286
+ attention_mask=attention_mask,
1287
+ position_ids=position_ids,
1288
+ past_key_values=past_key_values,
1289
+ inputs_embeds=inputs_embeds,
1290
+ use_cache=use_cache,
1291
+ output_attentions=output_attentions,
1292
+ output_hidden_states=output_hidden_states,
1293
+ return_dict=return_dict,
1294
+ )
1295
+
1296
+ hidden_states = outputs[0]
1297
+ logits = self.lm_head(hidden_states)
1298
+ logits = logits.float()
1299
+
1300
+ loss = None
1301
+ if labels is not None:
1302
+ # Shift so that tokens < n predict n
1303
+ shift_logits = logits[..., :-1, :].contiguous()
1304
+ shift_labels = labels[..., 1:].contiguous()
1305
+ # Flatten the tokens
1306
+ loss_fct = CrossEntropyLoss()
1307
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1308
+ shift_labels = shift_labels.view(-1)
1309
+ # Enable model parallelism
1310
+ shift_labels = shift_labels.to(shift_logits.device)
1311
+ loss = loss_fct(shift_logits, shift_labels)
1312
+
1313
+ if not return_dict:
1314
+ output = (logits,) + outputs[1:]
1315
+ return (loss,) + output if loss is not None else output
1316
+
1317
+ return CausalLMOutputWithPast(
1318
+ loss=loss,
1319
+ logits=logits,
1320
+ past_key_values=outputs.past_key_values,
1321
+ hidden_states=outputs.hidden_states,
1322
+ attentions=outputs.attentions,
1323
+ )
1324
+
1325
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1326
+ def prepare_inputs_for_generation(
1327
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1328
+ ):
1329
+ if past_key_values is not None:
1330
+ if isinstance(past_key_values, Cache):
1331
+ cache_length = past_key_values.get_seq_length()
1332
+ past_length = past_key_values.seen_tokens
1333
+ max_cache_length = past_key_values.get_max_length()
1334
+ else:
1335
+ cache_length = past_length = past_key_values[0][0].shape[2]
1336
+ max_cache_length = None
1337
+
1338
+ # Keep only the unprocessed tokens:
1339
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1340
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1341
+ # input)
1342
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1343
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1344
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1345
+ # input_ids based on the past_length.
1346
+ elif past_length < input_ids.shape[1]:
1347
+ input_ids = input_ids[:, past_length:]
1348
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1349
+
1350
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1351
+ if (
1352
+ max_cache_length is not None
1353
+ and attention_mask is not None
1354
+ and cache_length + input_ids.shape[1] > max_cache_length
1355
+ ):
1356
+ attention_mask = attention_mask[:, -max_cache_length:]
1357
+
1358
+ position_ids = kwargs.get("position_ids", None)
1359
+ if attention_mask is not None and position_ids is None:
1360
+ # create position_ids on the fly for batch generation
1361
+ position_ids = attention_mask.long().cumsum(-1) - 1
1362
+ position_ids.masked_fill_(attention_mask == 0, 1)
1363
+ if past_key_values:
1364
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1365
+
1366
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1367
+ if inputs_embeds is not None and past_key_values is None:
1368
+ model_inputs = {"inputs_embeds": inputs_embeds}
1369
+ else:
1370
+ model_inputs = {"input_ids": input_ids}
1371
+
1372
+ model_inputs.update(
1373
+ {
1374
+ "position_ids": position_ids,
1375
+ "past_key_values": past_key_values,
1376
+ "use_cache": kwargs.get("use_cache"),
1377
+ "attention_mask": attention_mask,
1378
+ }
1379
+ )
1380
+ return model_inputs
1381
+
1382
+ @staticmethod
1383
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1384
+ def _reorder_cache(past_key_values, beam_idx):
1385
+ reordered_past = ()
1386
+ for layer_past in past_key_values:
1387
+ reordered_past += (
1388
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1389
+ )
1390
+ return reordered_past
1391
+
1392
+
1393
+ @add_start_docstrings(
1394
+ """
1395
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1396
+
1397
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1398
+ (e.g. GPT-2) do.
1399
+
1400
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1401
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1402
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1403
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1404
+ each row of the batch).
1405
+ """,
1406
+ PHI3_START_DOCSTRING,
1407
+ )
1408
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1409
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1410
+ def __init__(self, config):
1411
+ super().__init__(config)
1412
+ self.num_labels = config.num_labels
1413
+ self.model = Phi3Model(config)
1414
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1415
+
1416
+ # Initialize weights and apply final processing
1417
+ self.post_init()
1418
+
1419
+ def get_input_embeddings(self):
1420
+ return self.model.embed_tokens
1421
+
1422
+ def set_input_embeddings(self, value):
1423
+ self.model.embed_tokens = value
1424
+
1425
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1426
+ def forward(
1427
+ self,
1428
+ input_ids: torch.LongTensor = None,
1429
+ attention_mask: Optional[torch.Tensor] = None,
1430
+ position_ids: Optional[torch.LongTensor] = None,
1431
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1432
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1433
+ labels: Optional[torch.LongTensor] = None,
1434
+ use_cache: Optional[bool] = None,
1435
+ output_attentions: Optional[bool] = None,
1436
+ output_hidden_states: Optional[bool] = None,
1437
+ return_dict: Optional[bool] = None,
1438
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1439
+ r"""
1440
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1441
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1442
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1443
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1444
+ """
1445
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1446
+
1447
+ model_outputs = self.model(
1448
+ input_ids,
1449
+ attention_mask=attention_mask,
1450
+ position_ids=position_ids,
1451
+ past_key_values=past_key_values,
1452
+ inputs_embeds=inputs_embeds,
1453
+ use_cache=use_cache,
1454
+ output_attentions=output_attentions,
1455
+ output_hidden_states=output_hidden_states,
1456
+ return_dict=return_dict,
1457
+ )
1458
+ hidden_states = model_outputs[0]
1459
+ logits = self.score(hidden_states)
1460
+
1461
+ if input_ids is not None:
1462
+ batch_size = input_ids.shape[0]
1463
+ else:
1464
+ batch_size = inputs_embeds.shape[0]
1465
+
1466
+ if self.config.pad_token_id is None and batch_size != 1:
1467
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1468
+ if self.config.pad_token_id is None:
1469
+ sequence_lengths = -1
1470
+ else:
1471
+ if input_ids is not None:
1472
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1473
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1474
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1475
+ sequence_lengths = sequence_lengths.to(logits.device)
1476
+ else:
1477
+ sequence_lengths = -1
1478
+
1479
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1480
+
1481
+ loss = None
1482
+ if labels is not None:
1483
+ labels = labels.to(logits.device)
1484
+ if self.config.problem_type is None:
1485
+ if self.num_labels == 1:
1486
+ self.config.problem_type = "regression"
1487
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1488
+ self.config.problem_type = "single_label_classification"
1489
+ else:
1490
+ self.config.problem_type = "multi_label_classification"
1491
+
1492
+ if self.config.problem_type == "regression":
1493
+ loss_fct = MSELoss()
1494
+ if self.num_labels == 1:
1495
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1496
+ else:
1497
+ loss = loss_fct(pooled_logits, labels)
1498
+ elif self.config.problem_type == "single_label_classification":
1499
+ loss_fct = CrossEntropyLoss()
1500
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1501
+ elif self.config.problem_type == "multi_label_classification":
1502
+ loss_fct = BCEWithLogitsLoss()
1503
+ loss = loss_fct(pooled_logits, labels)
1504
+ if not return_dict:
1505
+ output = (pooled_logits,) + model_outputs[1:]
1506
+ return ((loss,) + output) if loss is not None else output
1507
+
1508
+ return SequenceClassifierOutputWithPast(
1509
+ loss=loss,
1510
+ logits=pooled_logits,
1511
+ past_key_values=model_outputs.past_key_values,
1512
+ hidden_states=model_outputs.hidden_states,
1513
+ attentions=model_outputs.attentions,
1514
+ )
1515
+
1516
+
1517
+ @add_start_docstrings(
1518
+ """
1519
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1520
+ Named-Entity-Recognition (NER) tasks.
1521
+ """,
1522
+ PHI3_START_DOCSTRING,
1523
+ )
1524
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1525
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1526
+ def __init__(self, config: Phi3Config):
1527
+ super().__init__(config)
1528
+ self.num_labels = config.num_labels
1529
+
1530
+ self.model = Phi3Model(config)
1531
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1532
+ classifier_dropout = config.classifier_dropout
1533
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1534
+ classifier_dropout = config.hidden_dropout
1535
+ else:
1536
+ classifier_dropout = 0.1
1537
+ self.dropout = nn.Dropout(classifier_dropout)
1538
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1539
+
1540
+ # Initialize weights and apply final processing
1541
+ self.post_init()
1542
+
1543
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1544
+ @add_code_sample_docstrings(
1545
+ checkpoint=_CHECKPOINT_FOR_DOC,
1546
+ output_type=TokenClassifierOutput,
1547
+ config_class=_CONFIG_FOR_DOC,
1548
+ )
1549
+ def forward(
1550
+ self,
1551
+ input_ids: Optional[torch.LongTensor] = None,
1552
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1553
+ attention_mask: Optional[torch.Tensor] = None,
1554
+ inputs_embeds: Optional[torch.Tensor] = None,
1555
+ labels: Optional[torch.Tensor] = None,
1556
+ use_cache: Optional[bool] = None,
1557
+ output_attentions: Optional[bool] = None,
1558
+ output_hidden_states: Optional[bool] = None,
1559
+ return_dict: Optional[bool] = None,
1560
+ **deprecated_arguments,
1561
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1562
+ r"""
1563
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1564
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1565
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1566
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1567
+ """
1568
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1569
+
1570
+ model_outputs = self.model(
1571
+ input_ids,
1572
+ past_key_values=past_key_values,
1573
+ attention_mask=attention_mask,
1574
+ inputs_embeds=inputs_embeds,
1575
+ use_cache=use_cache,
1576
+ output_attentions=output_attentions,
1577
+ output_hidden_states=output_hidden_states,
1578
+ return_dict=return_dict,
1579
+ )
1580
+
1581
+ hidden_states = model_outputs[0]
1582
+ hidden_states = self.dropout(hidden_states)
1583
+ logits = self.classifier(hidden_states)
1584
+
1585
+ loss = None
1586
+ if labels is not None:
1587
+ # move labels to correct device to enable model parallelism
1588
+ labels = labels.to(logits.device)
1589
+ batch_size, seq_length = labels.shape
1590
+ loss_fct = CrossEntropyLoss()
1591
+ loss = loss_fct(
1592
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1593
+ )
1594
+
1595
+ if not return_dict:
1596
+ output = (logits,) + model_outputs[2:]
1597
+ return ((loss,) + output) if loss is not None else output
1598
+
1599
+ return TokenClassifierOutput(
1600
+ loss=loss,
1601
+ logits=logits,
1602
+ hidden_states=model_outputs.hidden_states,
1603
+ attentions=model_outputs.attentions,
1604
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": true,
26
+ "single_word": false,
27
+ "special": false
28
+ },
29
+ "32000": {
30
+ "content": "<|endoftext|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "32001": {
38
+ "content": "<|assistant|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": true,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "32002": {
46
+ "content": "<|placeholder1|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": true,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "32003": {
54
+ "content": "<|placeholder2|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": true,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "32004": {
62
+ "content": "<|placeholder3|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": true,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "32005": {
70
+ "content": "<|placeholder4|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": true,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "32006": {
78
+ "content": "<|system|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": true,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "32007": {
86
+ "content": "<|end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": true,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "32008": {
94
+ "content": "<|placeholder5|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": true,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "32009": {
102
+ "content": "<|placeholder6|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": true,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "32010": {
110
+ "content": "<|user|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": true,
114
+ "single_word": false,
115
+ "special": true
116
+ }
117
+ },
118
+ "bos_token": "<s>",
119
+ "chat_template": "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') %}{{'<|user|>' + '\n' + message['content'] + '<|end|>' + '\n' + '<|assistant|>' + '\n'}}{% elif (message['role'] == 'assistant') %}{{message['content'] + '<|end|>' + '\n'}}{% endif %}{% endfor %}",
120
+ "clean_up_tokenization_spaces": false,
121
+ "eos_token": "<|endoftext|>",
122
+ "model_max_length": 131072,
123
+ "pad_token": "<|endoftext|>",
124
+ "padding_side": "left",
125
+ "sp_model_kwargs": {},
126
+ "tokenizer_class": "LlamaTokenizer",
127
+ "unk_token": "<unk>",
128
+ "use_default_system_prompt": false
129
+ }