mccoole commited on
Commit
68041c6
1 Parent(s): c38c46e

Upload folder using huggingface_hub

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