dev-slx commited on
Commit
1f862c9
1 Parent(s): 1ed42be

Upload folder using huggingface_hub

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