schuler commited on
Commit
c626774
·
verified ·
1 Parent(s): 3a3f18a

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_kphi3.py +231 -0
  2. modeling_kphi3.py +1892 -0
configuration_kphi3.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # This file modifies the original PHI3 Model from Microsoft. Please refer to
3
+ # https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/blob/main/configuration_phi3.py
4
+ # for the original implementation
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """ Phi-3 model configuration"""
19
+
20
+
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ KPHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
28
+ }
29
+
30
+
31
+ class KPhi3Config(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 `longrope` 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 = "kphi3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32064,
120
+ embed_size=1024,
121
+ hidden_size=1024,
122
+ intermediate_size=4096,
123
+ num_hidden_layers=4,
124
+ num_attention_heads=4,
125
+ num_key_value_heads=None,
126
+ resid_pdrop=0.0,
127
+ embd_pdrop=0.0,
128
+ attention_dropout=0.0,
129
+ hidden_act="silu",
130
+ max_position_embeddings=4096,
131
+ original_max_position_embeddings=4096,
132
+ initializer_range=0.02,
133
+ rms_norm_eps=1e-5,
134
+ use_cache=True,
135
+ tie_word_embeddings=False,
136
+ rope_theta=10000.0,
137
+ rope_scaling=None,
138
+ bos_token_id=1,
139
+ eos_token_id=32000,
140
+ pad_token_id=32000,
141
+ sliding_window=None,
142
+ min_channels_per_group=256,
143
+ **kwargs,
144
+ ):
145
+ self.vocab_size = vocab_size
146
+ self.embed_size = embed_size
147
+ self.hidden_size = hidden_size
148
+ self.intermediate_size = intermediate_size
149
+ self.num_hidden_layers = num_hidden_layers
150
+ self.num_attention_heads = num_attention_heads
151
+
152
+ if num_key_value_heads is None:
153
+ num_key_value_heads = num_attention_heads
154
+
155
+ self.num_key_value_heads = num_key_value_heads
156
+ self.resid_pdrop = resid_pdrop
157
+ self.embd_pdrop = embd_pdrop
158
+ self.attention_dropout = attention_dropout
159
+ self.hidden_act = hidden_act
160
+ self.max_position_embeddings = max_position_embeddings
161
+ self.original_max_position_embeddings = original_max_position_embeddings
162
+ self.initializer_range = initializer_range
163
+ self.rms_norm_eps = rms_norm_eps
164
+ self.use_cache = use_cache
165
+ self.rope_theta = rope_theta
166
+ self.rope_scaling = rope_scaling
167
+ self._rope_scaling_adjustment()
168
+ self._rope_scaling_validation()
169
+ self.sliding_window = sliding_window
170
+ self.min_channels_per_group = min_channels_per_group
171
+
172
+ super().__init__(
173
+ bos_token_id=bos_token_id,
174
+ eos_token_id=eos_token_id,
175
+ pad_token_id=pad_token_id,
176
+ tie_word_embeddings=tie_word_embeddings,
177
+ **kwargs,
178
+ )
179
+
180
+ def _rope_scaling_adjustment(self):
181
+ """
182
+ Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
183
+ """
184
+ if self.rope_scaling is None:
185
+ return
186
+
187
+ rope_scaling_type = self.rope_scaling.get("type", None)
188
+
189
+ # For backward compatibility if previous version used "su" or "yarn"
190
+ if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
191
+ self.rope_scaling["type"] = "longrope"
192
+
193
+ def _rope_scaling_validation(self):
194
+ """
195
+ Validate the `rope_scaling` configuration.
196
+ """
197
+ if self.rope_scaling is None:
198
+ return
199
+
200
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
201
+ raise ValueError(
202
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
203
+ f"got {self.rope_scaling}"
204
+ )
205
+ rope_scaling_type = self.rope_scaling.get("type", None)
206
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
207
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
208
+ if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
209
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
210
+ if not (
211
+ isinstance(rope_scaling_short_factor, list)
212
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
213
+ ):
214
+ raise ValueError(
215
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
216
+ )
217
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
218
+ raise ValueError(
219
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
220
+ )
221
+ if not (
222
+ isinstance(rope_scaling_long_factor, list)
223
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
224
+ ):
225
+ raise ValueError(
226
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
227
+ )
228
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
229
+ raise ValueError(
230
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
231
+ )
modeling_kphi3.py ADDED
@@ -0,0 +1,1892 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # This file modifies the original PHI3 Model from Microsoft. Please refer to
3
+ # https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/blob/main/modeling_phi3.py
4
+ # for the original implementation.
5
+ # This implementation takes advantage of the (K) optimization described at:
6
+ # https://www.researchgate.net/publication/360226228_Grouped_Pointwise_Convolutions_Reduce_Parameters_in_Convolutional_Neural_Networks
7
+ # https://www.researchgate.net/publication/355214501_Grouped_Pointwise_Convolutions_Significantly_Reduces_Parameters_in_EfficientNet
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ """ PyTorch KPhi-3 model."""
22
+
23
+ import inspect
24
+ import math
25
+ import warnings
26
+ from typing import List, Optional, Tuple, Union
27
+
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ from torch import nn
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.generation import GenerationMixin
36
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
37
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
38
+ from transformers.modeling_outputs import (
39
+ BaseModelOutputWithPast,
40
+ CausalLMOutputWithPast,
41
+ SequenceClassifierOutputWithPast,
42
+ TokenClassifierOutput,
43
+ )
44
+ from transformers.modeling_utils import PreTrainedModel
45
+ from transformers.utils import (
46
+ add_code_sample_docstrings,
47
+ add_start_docstrings,
48
+ add_start_docstrings_to_model_forward,
49
+ is_flash_attn_2_available,
50
+ is_flash_attn_greater_or_equal_2_10,
51
+ logging,
52
+ replace_return_docstrings,
53
+ )
54
+ from .configuration_kphi3 import KPhi3Config
55
+
56
+ if is_flash_attn_2_available():
57
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
58
+
59
+ def get_max_acceptable_common_divisor(a, b, max_acceptable=1000000):
60
+ """
61
+ This is an inefficient max acceptable common divisor implementation to be improved.
62
+ # Arguments
63
+ a: is an integer.
64
+ b: is an integer.
65
+ max_acceptable: maximum acceptable common divisor.
66
+ """
67
+ divisor = max(1, min(a, b, max_acceptable))
68
+ while divisor > 0:
69
+ if a % divisor == 0 and b % divisor == 0:
70
+ return divisor
71
+ break
72
+ divisor -= 1
73
+
74
+ class InterleaveChannels(nn.Module):
75
+ """
76
+ This layer interleaves channels stepping according to the number passed as parameter.
77
+ This layer assumes "channel last".
78
+ """
79
+ def __init__(self, step_size=2, last_dim=3):
80
+ super().__init__()
81
+ self.step_size = step_size if step_size >= 2 else 1
82
+ self.last_dim = last_dim
83
+
84
+ def forward(self, x):
85
+ if (self.last_dim==3):
86
+ return torch.cat([x[:, :, :, shift_pos::self.step_size] for shift_pos in range(self.step_size)], dim=3)
87
+ else:
88
+ if (self.last_dim==2):
89
+ return torch.cat([x[:, :, shift_pos::self.step_size] for shift_pos in range(self.step_size)], dim=2)
90
+
91
+ def SignedSquareRoot1(x):
92
+ """
93
+ Custom activation function that implements:
94
+ f(x) = sqrt(x) for x > 1
95
+ f(x) = sqrt(-x) for x < -1
96
+ f(x) = x for -1 ≤ x ≤ 1
97
+ """
98
+ return torch.where(x > 1,
99
+ torch.sqrt(x),
100
+ torch.where(x < -1, torch.sqrt(-x), x)
101
+ )
102
+
103
+ # coded by GPT o1 Preview
104
+ class InterleaveChannelsFast(nn.Module):
105
+ """
106
+ This layer interleaves channels stepping according to the number passed as parameter.
107
+ This layer assumes "channel last".
108
+ """
109
+ def __init__(self, step_size=2, last_dim=3):
110
+ super().__init__()
111
+ self.step_size = max(step_size, 1)
112
+ self.last_dim = last_dim
113
+
114
+ def forward(self, x):
115
+ if self.last_dim == 3:
116
+ N, H, W, C = x.shape
117
+ if C % self.step_size != 0:
118
+ raise ValueError("Number of channels must be divisible by step_size")
119
+ # Reshape to separate the interleaving groups
120
+ x = x.view(N, H, W, self.step_size, C // self.step_size)
121
+ # Transpose to interleave the channels
122
+ x = x.permute(0, 1, 2, 4, 3)
123
+ # Flatten back to the original shape
124
+ x = x.reshape(N, H, W, C)
125
+ return x
126
+ elif self.last_dim == 2:
127
+ N, H, W = x.shape
128
+ if W % self.step_size != 0:
129
+ raise ValueError("Width must be divisible by step_size")
130
+ x = x.view(N, H, self.step_size, W // self.step_size)
131
+ x = x.permute(0, 1, 3, 2)
132
+ x = x.reshape(N, H, W)
133
+ return x
134
+ else:
135
+ raise ValueError("last_dim must be 2 or 3")
136
+
137
+ class GroupedLinear(nn.Module):
138
+ """
139
+ Similarly to a grouped pointwise convolution, this layer is a grouped linear layer.
140
+ This layer assumes "channel last".
141
+ """
142
+ def __init__(self, in_features, out_features, num_groups=1, bias=True):
143
+ super().__init__()
144
+ self.in_features = in_features
145
+ self.out_features = out_features
146
+ self.num_groups = num_groups
147
+ self.bias = bias
148
+
149
+ # Check if input features are divisible by num_groups
150
+ if in_features % num_groups != 0:
151
+ raise ValueError("Input features must be divisible by num_groups.")
152
+ if out_features % num_groups != 0:
153
+ raise ValueError("Output features must be divisible by num_groups.")
154
+
155
+ self.in_features_per_group = in_features // num_groups
156
+ self.out_features_per_group = out_features // num_groups
157
+
158
+ # Create individual linear layers for each group
159
+ self.group_layers = nn.ModuleList([
160
+ nn.Linear(self.in_features_per_group, self.out_features_per_group, bias=bias)
161
+ for _ in range(num_groups)
162
+ ])
163
+
164
+ def forward(self, x):
165
+ # print('input:',x.shape,' in:',self.in_features,' out:',self.out_features,
166
+ # ' groups:',self.num_groups,
167
+ # ' in_per_group:',self.in_features_per_group,
168
+ # ' out_per_group:',self.out_features_per_group,
169
+ # ' bias:',self.bias
170
+ #)
171
+ if self.in_features != x.shape[-1]:
172
+ raise ValueError(
173
+ "GroupedLinear error: "+
174
+ "expected in_feautures "+str(self.in_features)+
175
+ " but got "+str(x.shape[-1])
176
+ )
177
+ # Split the input tensor into groups along the last dimension
178
+ x_groups = x.chunk(self.num_groups, dim=-1)
179
+
180
+ # for i, tensor in enumerate(x_groups):
181
+ # print(f'x_groups[{i}]: {tensor.shape}')
182
+
183
+ # Apply individual linear layers to each group
184
+ out_groups = [layer(group) for layer, group in zip(self.group_layers, x_groups)]
185
+
186
+ # Concatenate the output groups along the last dimension
187
+ out = torch.cat(out_groups, dim=-1)
188
+ if self.out_features != out.shape[-1]:
189
+ raise ValueError(
190
+ "GroupedLinear error: "+
191
+ "expected out_feautures "+str(self.out_features)+
192
+ " but got "+str(out.shape[-1])
193
+ )
194
+ # print('output:',out.shape)
195
+ return out
196
+
197
+ class GroupedLinearFast(nn.Module):
198
+ """
199
+ Optimized grouped linear layer.
200
+ This layer assumes "channel last".
201
+ """
202
+ def __init__(self, in_features, out_features, num_groups=1, bias=True):
203
+ super().__init__()
204
+ self.in_features = in_features
205
+ self.out_features = out_features
206
+ self.num_groups = num_groups
207
+
208
+ # Validate divisibility
209
+ if in_features % num_groups != 0:
210
+ raise ValueError("Input features must be divisible by num_groups.")
211
+ if out_features % num_groups != 0:
212
+ raise ValueError("Output features must be divisible by num_groups.")
213
+
214
+ self.in_features_per_group = in_features // num_groups
215
+ self.out_features_per_group = out_features // num_groups
216
+
217
+ # Initialize weight and bias parameters
218
+ self.weight = nn.Parameter(
219
+ torch.Tensor(num_groups, self.in_features_per_group, self.out_features_per_group)
220
+ )
221
+ if bias:
222
+ self.bias = nn.Parameter(torch.Tensor(num_groups, self.out_features_per_group))
223
+ else:
224
+ self.register_parameter('bias', None)
225
+
226
+ self.reset_parameters()
227
+
228
+ def reset_parameters(self):
229
+ # Weight initialization
230
+ nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
231
+ if self.bias is not None:
232
+ # Bias initialization
233
+ fan_in = self.in_features_per_group
234
+ bound = 1 / math.sqrt(fan_in)
235
+ nn.init.uniform_(self.bias, -bound, bound)
236
+
237
+ def forward(self, x):
238
+ in_shape = x.shape
239
+ if x.shape[-1] != self.in_features:
240
+ raise ValueError(
241
+ f"GroupedLinear error: expected in_features {self.in_features}, but got {x.shape[-1]}"
242
+ )
243
+ # Reshape input to separate groups
244
+ x = x.view(*x.shape[:-1], self.num_groups, self.in_features_per_group)
245
+
246
+ # print('in shape', in_shape)
247
+ # print('x shape', x.shape)
248
+ # print('weight shape', self.weight.shape)
249
+
250
+ # Perform batch matrix multiplication
251
+ # x shape: [..., num_groups, in_features_per_group]
252
+ # weight shape: [num_groups, in_features_per_group, out_features_per_group]
253
+ # out = torch.matmul(x, self.weight)
254
+ out = torch.einsum('...ni,niq->...nq', x, self.weight)
255
+ # print('out shape', out.shape)
256
+ # print(in_shape[0], in_shape[1], self.out_features)
257
+
258
+ # Add bias if present
259
+ if self.bias is not None:
260
+ out += self.bias
261
+
262
+ # Reshape output back to original shape
263
+ # out = out.view(in_shape[0], in_shape[1], self.out_features)
264
+ out = out.contiguous().view(*out.shape[:-2], self.out_features)
265
+ return out
266
+
267
+ class GroupedPointwiseConvolutionBlock(nn.Module):
268
+ """
269
+ This layer is composed by a grouped pointwise convolution followed by interleaving and another grouped pointwise comvolution with skip connection. This basic architecture can
270
+ vary according to the input tensor and its parameters. This is the basic building block for the papers:
271
+ https://www.researchgate.net/publication/360226228_Grouped_Pointwise_Convolutions_Reduce_Parameters_in_Convolutional_Neural_Networks
272
+ https://www.researchgate.net/publication/355214501_Grouped_Pointwise_Convolutions_Significantly_Reduces_Parameters_in_EfficientNet
273
+ This layer assumes "channel last".
274
+ """
275
+ def __init__(self, in_features, out_features, min_channels_per_group=32, last_dim=2, use_bias=False, activation=None, has_batch_norm=False, has_batch_scale=False):
276
+ super().__init__()
277
+ self.in_features = in_features
278
+ self.out_features = out_features
279
+ self.min_channels_per_group = min_channels_per_group
280
+ self.last_dim = last_dim
281
+ self.activation = activation
282
+ self.has_batch_norm = has_batch_norm
283
+ self.has_batch_scale = has_batch_scale
284
+ self.has_interleaving = False
285
+ self.use_bias = use_bias
286
+ self.grouped = False
287
+ self.second_conv = False
288
+ self.first_pointwise_conv = None
289
+ self.second_pointwise_conv = None
290
+ self.interleave_layer = None
291
+ # this is a hack to prevent runtime errors
292
+ self.weight = torch.Tensor(1, 1, 1)
293
+ self.bias = torch.Tensor(1, 1, 1)
294
+
295
+ prev_layer_channel_count = in_features
296
+ output_channel_count = out_features
297
+ max_acceptable_divisor = (prev_layer_channel_count//min_channels_per_group)
298
+ group_count = get_max_acceptable_common_divisor(prev_layer_channel_count, output_channel_count, max_acceptable = max_acceptable_divisor)
299
+ if group_count is None: group_count=1
300
+ self.output_group_size = output_channel_count // group_count
301
+
302
+ if (group_count>1):
303
+ self.grouped = True
304
+ self.first_pointwise_conv = GroupedLinearFast(in_features=in_features, out_features=out_features, num_groups=group_count, bias=use_bias)
305
+ if self.output_group_size > 1:
306
+ self.has_interleaving = True
307
+ self.interleave_layer = InterleaveChannelsFast(self.output_group_size, last_dim=last_dim)
308
+ if (prev_layer_channel_count >= output_channel_count):
309
+ # print('Has intergroup')
310
+ self.second_conv = True
311
+ self.second_pointwise_conv = GroupedLinearFast(in_features=out_features, out_features=out_features, num_groups=group_count, bias=use_bias)
312
+ else:
313
+ #print ('Dismissed groups:', group_count, 'Input channels:', prev_layer_channel_count, 'Output Channels:', output_channel_count, 'Input channels per group:', input_group_size, 'Output channels per group:', output_group_size)
314
+ self.first_pointwise_conv = GroupedLinear(in_features=in_features, out_features=out_features, num_groups=1, bias=use_bias)
315
+
316
+ def forward(self, x):
317
+ if (self.grouped):
318
+ output_tensor = self.first_pointwise_conv(x)
319
+ if self.activation is not None:
320
+ output_tensor = self.activation(output_tensor)
321
+ compression_tensor = output_tensor
322
+ if self.has_interleaving:
323
+ output_tensor = self.interleave_layer(output_tensor)
324
+ if self.second_conv:
325
+ output_tensor = self.second_pointwise_conv(output_tensor)
326
+ if self.activation is not None:
327
+ output_tensor = self.activation(output_tensor)
328
+ output_tensor = output_tensor + compression_tensor
329
+ else:
330
+ output_tensor = self.first_pointwise_conv(x)
331
+ if self.activation is not None:
332
+ output_tensor = self.activation(output_tensor)
333
+ return output_tensor
334
+
335
+
336
+ logger = logging.get_logger(__name__)
337
+
338
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
339
+ # if is_flash_attn_2_available():
340
+ _flash_supports_window_size = False
341
+ try:
342
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
343
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
344
+
345
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
346
+ except ImportError as error:
347
+ logger.warning(
348
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
349
+ )
350
+ if not _flash_supports_window_size:
351
+ logger.warning(
352
+ "Current `flash-attention` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
353
+ )
354
+
355
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
356
+ _CONFIG_FOR_DOC = "KPhi3Config"
357
+
358
+ # Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
359
+ def _prepare_4d_causal_attention_mask_with_cache_position(
360
+ attention_mask: torch.Tensor,
361
+ sequence_length: int,
362
+ target_length: int,
363
+ dtype: torch.dtype,
364
+ device: torch.device,
365
+ min_dtype: float,
366
+ cache_position: torch.Tensor,
367
+ batch_size: int,
368
+ ):
369
+ """
370
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
371
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
372
+
373
+ Args:
374
+ attention_mask (`torch.Tensor`):
375
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
376
+ sequence_length (`int`):
377
+ The sequence length being processed.
378
+ target_length (`int`):
379
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
380
+ dtype (`torch.dtype`):
381
+ The dtype to use for the 4D attention mask.
382
+ device (`torch.device`):
383
+ The device to plcae the 4D attention mask on.
384
+ min_dtype (`float`):
385
+ The minimum value representable with the dtype `dtype`.
386
+ cache_position (`torch.Tensor`):
387
+ Indices depicting the position of the input sequence tokens in the sequence.
388
+ batch_size (`torch.Tensor`):
389
+ Batch size.
390
+ """
391
+ if attention_mask is not None and attention_mask.dim() == 4:
392
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
393
+ causal_mask = attention_mask
394
+ else:
395
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
396
+ if sequence_length != 1:
397
+ causal_mask = torch.triu(causal_mask, diagonal=1)
398
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
399
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
400
+ if attention_mask is not None:
401
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
402
+ mask_length = attention_mask.shape[-1]
403
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
404
+ padding_mask = padding_mask == 0
405
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
406
+ padding_mask, min_dtype
407
+ )
408
+
409
+ return causal_mask
410
+
411
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
412
+ class Phi3RMSNorm(nn.Module):
413
+ def __init__(self, hidden_size, eps=1e-6):
414
+ """
415
+ Phi3RMSNorm is equivalent to T5LayerNorm
416
+ """
417
+ super().__init__()
418
+ self.weight = nn.Parameter(torch.ones(hidden_size))
419
+ self.variance_epsilon = eps
420
+
421
+ def forward(self, hidden_states):
422
+ input_dtype = hidden_states.dtype
423
+ hidden_states = hidden_states.to(torch.float32)
424
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
425
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
426
+ return self.weight * hidden_states.to(input_dtype)
427
+
428
+ def extra_repr(self):
429
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
430
+
431
+
432
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
433
+ class Phi3RotaryEmbedding(nn.Module):
434
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
435
+ super().__init__()
436
+
437
+ self.dim = dim
438
+ self.max_position_embeddings = max_position_embeddings
439
+ self.base = base
440
+
441
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float() / self.dim))
442
+ self.register_buffer("inv_freq", tensor=inv_freq, persistent=False)
443
+
444
+ @torch.no_grad()
445
+ def forward(self, x, position_ids, seq_len=None):
446
+ # x: [bs, num_attention_heads, seq_len, head_size]
447
+ self.inv_freq.to(x.device)
448
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
449
+ position_ids_expanded = position_ids[:, None, :].float()
450
+ # Force float32 since bfloat16 loses precision on long contexts
451
+ # See https://github.com/huggingface/transformers/pull/29285
452
+ device_type = x.device.type
453
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
454
+ with torch.autocast(device_type=device_type, enabled=False):
455
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
456
+ emb = torch.cat((freqs, freqs), dim=-1)
457
+ cos = emb.cos()
458
+ sin = emb.sin()
459
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
460
+
461
+
462
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
463
+ def __init__(self, dim, config, device=None):
464
+ warnings.warn(
465
+ "The class Phi3SuScaledRotaryEmbedding is deprecated and will be removed in version 5 of Transformers. Please"
466
+ " use Phi3LongRoPEScaledRotaryEmbedding instead.",
467
+ FutureWarning,
468
+ )
469
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
470
+
471
+ self.short_factor = config.rope_scaling["short_factor"]
472
+ self.long_factor = config.rope_scaling["long_factor"]
473
+ self.original_max_position_embeddings = config.original_max_position_embeddings
474
+
475
+ @torch.no_grad()
476
+ def forward(self, x, position_ids, seq_len=None):
477
+ seq_len = torch.max(position_ids) + 1
478
+ if seq_len > self.original_max_position_embeddings:
479
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
480
+ else:
481
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
482
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
483
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
484
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
485
+ position_ids_expanded = position_ids[:, None, :].float()
486
+ # Force float32 since bfloat16 loses precision on long contexts
487
+ # See https://github.com/huggingface/transformers/pull/29285
488
+ device_type = x.device.type
489
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
490
+ with torch.autocast(device_type=device_type, enabled=False):
491
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
492
+ emb = torch.cat((freqs, freqs), dim=-1)
493
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
494
+ if scale <= 1.0:
495
+ scaling_factor = 1.0
496
+ else:
497
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
498
+ cos = emb.cos() * scaling_factor
499
+ sin = emb.sin() * scaling_factor
500
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
501
+
502
+
503
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
504
+ def __init__(self, dim, config, device=None):
505
+ warnings.warn(
506
+ "The class Phi3YarnScaledRotaryEmbedding is deprecated and will be removed in version 5 of Transformers",
507
+ FutureWarning,
508
+ )
509
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
510
+
511
+ self.short_factor = config.rope_scaling["short_factor"]
512
+ self.long_factor = config.rope_scaling["long_factor"]
513
+ self.original_max_position_embeddings = config.original_max_position_embeddings
514
+
515
+ @torch.no_grad()
516
+ def forward(self, x, position_ids, seq_len=None):
517
+ seq_len = torch.max(position_ids) + 1
518
+ if seq_len > self.original_max_position_embeddings:
519
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
520
+ else:
521
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
522
+
523
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
524
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
525
+
526
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
527
+ position_ids_expanded = position_ids[:, None, :].float()
528
+
529
+ # Force float32 since bfloat16 loses precision on long contexts
530
+ # See https://github.com/huggingface/transformers/pull/29285
531
+ device_type = x.device.type
532
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
533
+ with torch.autocast(device_type=device_type, enabled=False):
534
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
535
+ emb = torch.cat((freqs, freqs), dim=-1)
536
+
537
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
538
+ if scale <= 1.0:
539
+ scaling_factor = 1.0
540
+ else:
541
+ scaling_factor = 0.1 * math.log(scale) + 1.0
542
+
543
+ cos = emb.cos() * scaling_factor
544
+ sin = emb.sin() * scaling_factor
545
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
546
+
547
+
548
+ class Phi3LongRoPEScaledRotaryEmbedding(Phi3RotaryEmbedding):
549
+ def __init__(self, dim, config, device=None):
550
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
551
+
552
+ self.short_factor = config.rope_scaling["short_factor"]
553
+ self.long_factor = config.rope_scaling["long_factor"]
554
+ self.original_max_position_embeddings = config.original_max_position_embeddings
555
+
556
+ @torch.no_grad()
557
+ def forward(self, x, position_ids, seq_len=None):
558
+ seq_len = torch.max(position_ids) + 1
559
+ if seq_len > self.original_max_position_embeddings:
560
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
561
+ else:
562
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
563
+
564
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
565
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
566
+
567
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
568
+ position_ids_expanded = position_ids[:, None, :].float()
569
+
570
+ # Force float32 since bfloat16 loses precision on long contexts
571
+ # See https://github.com/huggingface/transformers/pull/29285
572
+ device_type = x.device.type
573
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
574
+ with torch.autocast(device_type=device_type, enabled=False):
575
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
576
+ emb = torch.cat((freqs, freqs), dim=-1)
577
+
578
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
579
+ if scale <= 1.0:
580
+ scaling_factor = 1.0
581
+ else:
582
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
583
+
584
+ cos = emb.cos() * scaling_factor
585
+ sin = emb.sin() * scaling_factor
586
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
587
+
588
+
589
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
590
+ def rotate_half(x):
591
+ """Rotates half the hidden dims of the input."""
592
+ x1 = x[..., : x.shape[-1] // 2]
593
+ x2 = x[..., x.shape[-1] // 2 :]
594
+ return torch.cat((-x2, x1), dim=-1)
595
+
596
+
597
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
598
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
599
+ """Applies Rotary Position Embedding to the query and key tensors.
600
+
601
+ Args:
602
+ q (`torch.Tensor`): The query tensor.
603
+ k (`torch.Tensor`): The key tensor.
604
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
605
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
606
+ position_ids (`torch.Tensor`, *optional*):
607
+ Deprecated and unused.
608
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
609
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
610
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
611
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
612
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
613
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
614
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
615
+ Returns:
616
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
617
+ """
618
+ cos = cos.unsqueeze(unsqueeze_dim)
619
+ sin = sin.unsqueeze(unsqueeze_dim)
620
+ q_embed = (q * cos) + (rotate_half(q) * sin)
621
+ k_embed = (k * cos) + (rotate_half(k) * sin)
622
+ return q_embed, k_embed
623
+
624
+
625
+ class KPhi3MLP(nn.Module):
626
+ def __init__(self, config):
627
+ super().__init__()
628
+ self.config = config
629
+ self.activation_fn = ACT2FN[config.hidden_act]
630
+ if self.config.min_channels_per_group >= 0:
631
+ self.gate_up_proj = GroupedPointwiseConvolutionBlock(in_features=config.hidden_size, out_features=(2*config.intermediate_size), min_channels_per_group=self.config.min_channels_per_group , last_dim=2, use_bias=False)
632
+ self.down_proj = GroupedPointwiseConvolutionBlock(in_features=config.intermediate_size, out_features=config.hidden_size, min_channels_per_group=self.config.min_channels_per_group, last_dim=2, use_bias=False)
633
+ else:
634
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
635
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
636
+
637
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
638
+ up_states = self.gate_up_proj(hidden_states)
639
+
640
+ gate, up_states = up_states.chunk(2, dim=-1)
641
+ up_states = up_states * self.activation_fn(gate)
642
+
643
+ return self.down_proj(up_states)
644
+
645
+
646
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
647
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
648
+ """
649
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
650
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
651
+ """
652
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
653
+ if n_rep == 1:
654
+ return hidden_states
655
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
656
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
657
+
658
+
659
+ class KPhi3Attention(nn.Module):
660
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
661
+
662
+ def __init__(self, config: KPhi3Config, layer_idx: Optional[int] = None):
663
+ super().__init__()
664
+ self.config = config
665
+ self.layer_idx = layer_idx
666
+ if layer_idx is None:
667
+ logger.warning_once(
668
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
669
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
670
+ "when creating this class."
671
+ )
672
+
673
+ self.attention_dropout = config.attention_dropout
674
+ self.hidden_size = config.hidden_size
675
+ self.num_heads = config.num_attention_heads
676
+ self.head_dim = self.hidden_size // self.num_heads
677
+ self.num_key_value_heads = config.num_key_value_heads
678
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
679
+ self.max_position_embeddings = config.max_position_embeddings
680
+ self.original_max_position_embeddings = config.original_max_position_embeddings
681
+ self.rope_theta = config.rope_theta
682
+ self.rope_scaling = config.rope_scaling
683
+ self.is_causal = True
684
+
685
+ if (self.head_dim * self.num_heads) != self.hidden_size:
686
+ raise ValueError(
687
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
688
+ f" and `num_heads`: {self.num_heads})."
689
+ )
690
+
691
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
692
+ if self.config.min_channels_per_group >= 0:
693
+ self.o_proj = GroupedPointwiseConvolutionBlock(in_features=self.num_heads * self.head_dim, out_features=self.hidden_size, min_channels_per_group=self.config.min_channels_per_group, last_dim=2, use_bias=False)
694
+ self.qkv_proj = GroupedPointwiseConvolutionBlock(in_features=self.hidden_size, out_features=op_size, min_channels_per_group=self.config.min_channels_per_group, last_dim=2, use_bias=False)
695
+ else:
696
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
697
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
698
+ self._init_rope()
699
+
700
+ def _init_rope(self):
701
+ if self.rope_scaling is None:
702
+ self.rotary_emb = Phi3RotaryEmbedding(
703
+ self.head_dim,
704
+ max_position_embeddings=self.max_position_embeddings,
705
+ base=self.rope_theta,
706
+ )
707
+ else:
708
+ scaling_type = self.config.rope_scaling["type"]
709
+ if scaling_type == "longrope":
710
+ self.rotary_emb = Phi3LongRoPEScaledRotaryEmbedding(self.head_dim, self.config)
711
+ else:
712
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
713
+
714
+ def forward(
715
+ self,
716
+ hidden_states: torch.Tensor,
717
+ attention_mask: Optional[torch.Tensor] = None,
718
+ position_ids: Optional[torch.LongTensor] = None,
719
+ past_key_value: Optional[Cache] = None,
720
+ output_attentions: bool = False,
721
+ use_cache: bool = False,
722
+ cache_position: Optional[torch.LongTensor] = None,
723
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
724
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
725
+
726
+ bsz, q_len, _ = hidden_states.size()
727
+
728
+ qkv = self.qkv_proj(hidden_states)
729
+ query_pos = self.num_heads * self.head_dim
730
+ query_states = qkv[..., :query_pos]
731
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
732
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
733
+
734
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
735
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
737
+
738
+ kv_seq_len = key_states.shape[-2]
739
+ if past_key_value is not None:
740
+ if self.layer_idx is None:
741
+ raise ValueError(
742
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
743
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
744
+ "with a layer index."
745
+ )
746
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
747
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
748
+
749
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
750
+
751
+ if past_key_value is not None:
752
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
753
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
754
+
755
+ # repeat k/v heads if n_kv_heads < n_heads
756
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
757
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
758
+
759
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
760
+
761
+ if attention_mask is not None:
762
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
763
+ attn_weights += causal_mask
764
+
765
+ # upcast attention to fp32
766
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
767
+ # attn_weights = SignedSquareRoot1(attn_weights.to(value_states.dtype))
768
+ # value_states = SignedSquareRoot1(value_states)
769
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
770
+
771
+ attn_output = torch.matmul(attn_weights, value_states)
772
+ # attn_output = SignedSquareRoot1(attn_output)
773
+
774
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
775
+ raise ValueError(
776
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
777
+ f" {attn_output.size()}"
778
+ )
779
+
780
+ attn_output = attn_output.transpose(1, 2).contiguous()
781
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
782
+
783
+ attn_output = self.o_proj(attn_output)
784
+ # attn_output = SignedSquareRoot1(attn_output)
785
+
786
+ if not output_attentions:
787
+ attn_weights = None
788
+
789
+ return attn_output, attn_weights, past_key_value
790
+
791
+
792
+ class KPhi3FlashAttention2(KPhi3Attention):
793
+ """
794
+ KPhi-3 flash attention module. This module inherits from `KPhi3Attention` as the weights of the module stays
795
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
796
+ flash attention and deal with padding tokens in case the input contains any of them.
797
+ """
798
+
799
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
800
+ def __init__(self, *args, **kwargs):
801
+ super().__init__(*args, **kwargs)
802
+
803
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
804
+ # 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.
805
+ # 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).
806
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
807
+
808
+ def forward(
809
+ self,
810
+ hidden_states: torch.Tensor,
811
+ attention_mask: Optional[torch.LongTensor] = None,
812
+ position_ids: Optional[torch.LongTensor] = None,
813
+ past_key_value: Optional[Cache] = None,
814
+ output_attentions: bool = False,
815
+ use_cache: bool = False,
816
+ cache_position: Optional[torch.LongTensor] = None,
817
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
818
+ # Phi3FlashAttention2 attention does not support output_attentions
819
+
820
+ output_attentions = False
821
+
822
+ bsz, q_len, _ = hidden_states.size()
823
+
824
+ qkv = self.qkv_proj(hidden_states)
825
+ query_pos = self.num_heads * self.head_dim
826
+ query_states = qkv[..., :query_pos]
827
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
828
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
829
+
830
+ # Flash attention requires the input to have the shape
831
+ # batch_size x seq_length x head_dim x hidden_dim
832
+ # therefore we just need to keep the original shape
833
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
834
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
835
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
836
+
837
+ kv_seq_len = key_states.shape[-2]
838
+ if past_key_value is not None:
839
+ if self.layer_idx is None:
840
+ raise ValueError(
841
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
842
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
843
+ "with a layer index."
844
+ )
845
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
846
+
847
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
848
+ rotary_seq_len = (
849
+ max(kv_seq_len, position_ids[:, -1].max().item() + 1) if position_ids is not None else kv_seq_len
850
+ )
851
+
852
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len, position_ids=position_ids)
853
+
854
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
855
+
856
+ if past_key_value is not None:
857
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
858
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
859
+ if (
860
+ getattr(self.config, "sliding_window", None) is not None
861
+ and kv_seq_len > self.config.sliding_window
862
+ and cache_has_contents
863
+ ):
864
+ slicing_tokens = 1 - self.config.sliding_window
865
+
866
+ past_key = past_key_value[self.layer_idx][0]
867
+ past_value = past_key_value[self.layer_idx][1]
868
+
869
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
870
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
871
+
872
+ if past_key.shape[-2] != self.config.sliding_window - 1:
873
+ raise ValueError(
874
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
875
+ f" {past_key.shape}"
876
+ )
877
+
878
+ if attention_mask is not None:
879
+ attention_mask = attention_mask[:, slicing_tokens:]
880
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
881
+
882
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
883
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
884
+
885
+ # repeat k/v heads if n_kv_heads < n_heads
886
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
887
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
888
+
889
+ attn_dropout = self.attention_dropout if self.training else 0.0
890
+
891
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
892
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
893
+ # cast them back in the correct dtype just to be sure everything works as expected.
894
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
895
+ # in fp32.
896
+
897
+ if query_states.dtype == torch.float32:
898
+ if torch.is_autocast_enabled():
899
+ target_dtype = torch.get_autocast_gpu_dtype()
900
+ # Handle the case where the model is quantized
901
+ elif hasattr(self.config, "_pre_quantization_dtype"):
902
+ target_dtype = self.config._pre_quantization_dtype
903
+ else:
904
+ target_dtype = self.qkv_proj.weight.dtype
905
+
906
+ logger.warning_once(
907
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
908
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
909
+ f" {target_dtype}."
910
+ )
911
+
912
+ query_states = query_states.to(target_dtype)
913
+ key_states = key_states.to(target_dtype)
914
+ value_states = value_states.to(target_dtype)
915
+
916
+ # Reashape to the expected shape for Flash Attention
917
+ query_states = query_states.transpose(1, 2)
918
+ key_states = key_states.transpose(1, 2)
919
+ value_states = value_states.transpose(1, 2)
920
+
921
+ attn_output = _flash_attention_forward(
922
+ query_states,
923
+ key_states,
924
+ value_states,
925
+ attention_mask,
926
+ q_len,
927
+ position_ids=position_ids,
928
+ dropout=attn_dropout,
929
+ sliding_window=getattr(self.config, "sliding_window", None),
930
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
931
+ is_causal=self.is_causal,
932
+ )
933
+
934
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
935
+ attn_output = self.o_proj(attn_output)
936
+
937
+ if not output_attentions:
938
+ attn_weights = None
939
+
940
+ return attn_output, attn_weights, past_key_value
941
+
942
+
943
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
944
+ # TODO @Arthur no longer copied from LLama after static cache
945
+ class KPhi3SdpaAttention(KPhi3Attention):
946
+ """
947
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
948
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
949
+ SDPA API.
950
+ """
951
+
952
+ # Adapted from Phi3Attention.forward
953
+ def forward(
954
+ self,
955
+ hidden_states: torch.Tensor,
956
+ attention_mask: Optional[torch.Tensor] = None,
957
+ position_ids: Optional[torch.LongTensor] = None,
958
+ past_key_value: Optional[Cache] = None,
959
+ output_attentions: bool = False,
960
+ use_cache: bool = False,
961
+ cache_position: Optional[torch.LongTensor] = None,
962
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
963
+ if output_attentions:
964
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
965
+ logger.warning_once(
966
+ "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, "
967
+ '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.'
968
+ )
969
+ return super().forward(
970
+ hidden_states=hidden_states,
971
+ attention_mask=attention_mask,
972
+ position_ids=position_ids,
973
+ past_key_value=past_key_value,
974
+ output_attentions=output_attentions,
975
+ use_cache=use_cache,
976
+ )
977
+
978
+ bsz, q_len, _ = hidden_states.size()
979
+
980
+ qkv = self.qkv_proj(hidden_states)
981
+ query_pos = self.num_heads * self.head_dim
982
+ query_states = qkv[..., :query_pos]
983
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
984
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
985
+
986
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
987
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
988
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
989
+
990
+ kv_seq_len = key_states.shape[-2]
991
+ if past_key_value is not None:
992
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
993
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
994
+
995
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
996
+
997
+ if past_key_value is not None:
998
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
999
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
1000
+
1001
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1002
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1003
+
1004
+ causal_mask = attention_mask
1005
+ if attention_mask is not None:
1006
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
1007
+
1008
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1009
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1010
+ if query_states.device.type == "cuda" and attention_mask is not None:
1011
+ query_states = query_states.contiguous()
1012
+ key_states = key_states.contiguous()
1013
+ value_states = value_states.contiguous()
1014
+
1015
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
1016
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
1017
+ # 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.
1018
+ is_causal = True if causal_mask is None and q_len > 1 else False
1019
+
1020
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1021
+ query_states,
1022
+ key_states,
1023
+ value_states,
1024
+ attn_mask=causal_mask,
1025
+ dropout_p=self.attention_dropout if self.training else 0.0,
1026
+ is_causal=is_causal,
1027
+ )
1028
+
1029
+ attn_output = attn_output.transpose(1, 2).contiguous()
1030
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
1031
+
1032
+ attn_output = self.o_proj(attn_output)
1033
+
1034
+ return attn_output, None, past_key_value
1035
+
1036
+
1037
+ KPHI3_ATTENTION_CLASSES = {
1038
+ "eager": KPhi3Attention,
1039
+ "flash_attention_2": KPhi3FlashAttention2,
1040
+ "sdpa": KPhi3SdpaAttention,
1041
+ }
1042
+
1043
+
1044
+ class KPhi3DecoderLayer(nn.Module):
1045
+ def __init__(self, config: KPhi3Config, layer_idx: int):
1046
+ super().__init__()
1047
+
1048
+ self.config = config
1049
+ self.self_attn = KPHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
1050
+
1051
+ self.mlp = KPhi3MLP(config)
1052
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1053
+
1054
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
1055
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
1056
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1057
+
1058
+ def forward(
1059
+ self,
1060
+ hidden_states: torch.Tensor,
1061
+ attention_mask: Optional[torch.Tensor] = None,
1062
+ position_ids: Optional[torch.LongTensor] = None,
1063
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1064
+ output_attentions: Optional[bool] = False,
1065
+ use_cache: Optional[bool] = False,
1066
+ cache_position: Optional[torch.LongTensor] = None,
1067
+ **kwargs,
1068
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1069
+ """
1070
+ Args:
1071
+ hidden_states (`torch.FloatTensor`):
1072
+ input to the layer of shape `(batch, seq_len, embed_dim)`
1073
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1074
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
1075
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
1076
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
1077
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
1078
+ output_attentions (`bool`, *optional*):
1079
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1080
+ returned tensors for more detail.
1081
+ use_cache (`bool`, *optional*):
1082
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1083
+ (see `past_key_values`).
1084
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1085
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1086
+ Indices depicting the position of the input sequence tokens in the sequence
1087
+ kwargs (`dict`, *optional*):
1088
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
1089
+ into the model
1090
+ """
1091
+
1092
+ residual = hidden_states
1093
+
1094
+ hidden_states = self.input_layernorm(hidden_states)
1095
+
1096
+ # Self Attention
1097
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
1098
+ hidden_states=hidden_states,
1099
+ attention_mask=attention_mask,
1100
+ position_ids=position_ids,
1101
+ past_key_value=past_key_value,
1102
+ output_attentions=output_attentions,
1103
+ use_cache=use_cache,
1104
+ cache_position=cache_position,
1105
+ )
1106
+
1107
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
1108
+
1109
+ residual = hidden_states
1110
+ hidden_states = self.post_attention_layernorm(hidden_states)
1111
+ hidden_states = self.mlp(hidden_states)
1112
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
1113
+
1114
+ outputs = (hidden_states,)
1115
+
1116
+ if output_attentions:
1117
+ outputs += (self_attn_weights,)
1118
+
1119
+ if use_cache:
1120
+ outputs += (present_key_value,)
1121
+
1122
+ return outputs
1123
+
1124
+
1125
+ KPHI3_START_DOCSTRING = r"""
1126
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1127
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1128
+ etc.)
1129
+
1130
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1131
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1132
+ and behavior.
1133
+
1134
+ Parameters:
1135
+ config ([`KPhi3Config`]):
1136
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1137
+ load the weights associated with the model, only the configuration. Check out the
1138
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1139
+ """
1140
+
1141
+
1142
+ @add_start_docstrings(
1143
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
1144
+ KPHI3_START_DOCSTRING,
1145
+ )
1146
+ class KPhi3PreTrainedModel(PreTrainedModel, GenerationMixin):
1147
+ config_class = KPhi3Config
1148
+ base_model_prefix = "model"
1149
+ supports_gradient_checkpointing = True
1150
+ _no_split_modules = ["KPhi3DecoderLayer"]
1151
+ _skip_keys_device_placement = "past_key_values"
1152
+ _supports_flash_attn_2 = True
1153
+ _supports_sdpa = False
1154
+ _supports_cache_class = True
1155
+
1156
+ _version = "1.0.0"
1157
+
1158
+ def _init_weights(self, module):
1159
+ std = self.config.initializer_range
1160
+ if isinstance(module, nn.Linear):
1161
+ module.weight.data.normal_(mean=0.0, std=std)
1162
+ if module.bias is not None:
1163
+ module.bias.data.zero_()
1164
+ elif isinstance(module, nn.Embedding):
1165
+ module.weight.data.normal_(mean=0.0, std=std)
1166
+ if module.padding_idx is not None:
1167
+ module.weight.data[module.padding_idx].zero_()
1168
+
1169
+
1170
+ KPHI3_INPUTS_DOCSTRING = r"""
1171
+ Args:
1172
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1173
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1174
+ it.
1175
+
1176
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1177
+ [`PreTrainedTokenizer.__call__`] for details.
1178
+
1179
+ [What are input IDs?](../glossary#input-ids)
1180
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1181
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1182
+
1183
+ - 1 for tokens that are **not masked**,
1184
+ - 0 for tokens that are **masked**.
1185
+
1186
+ [What are attention masks?](../glossary#attention-mask)
1187
+
1188
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1189
+ [`PreTrainedTokenizer.__call__`] for details.
1190
+
1191
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1192
+ `past_key_values`).
1193
+
1194
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1195
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1196
+ information on the default strategy.
1197
+
1198
+ - 1 indicates the head is **not masked**,
1199
+ - 0 indicates the head is **masked**.
1200
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1201
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1202
+ config.n_positions - 1]`.
1203
+
1204
+ [What are position IDs?](../glossary#position-ids)
1205
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1206
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1207
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1208
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1209
+
1210
+ Two formats are allowed:
1211
+ - a [`~cache_utils.Cache`] instance;
1212
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1213
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1214
+ cache format.
1215
+
1216
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1217
+ legacy cache format will be returned.
1218
+
1219
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1220
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1221
+ of shape `(batch_size, sequence_length)`.
1222
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1223
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1224
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1225
+ model's internal embedding lookup matrix.
1226
+ use_cache (`bool`, *optional*):
1227
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1228
+ `past_key_values`).
1229
+ output_attentions (`bool`, *optional*):
1230
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1231
+ tensors for more detail.
1232
+ output_hidden_states (`bool`, *optional*):
1233
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1234
+ more detail.
1235
+ return_dict (`bool`, *optional*):
1236
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1237
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1238
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1239
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1240
+ the complete sequence length.
1241
+ """
1242
+
1243
+
1244
+ @add_start_docstrings(
1245
+ "The bare KPhi-3 model outputting raw hidden-states without any specific head on top.",
1246
+ KPHI3_START_DOCSTRING,
1247
+ )
1248
+ class KPhi3Model(KPhi3PreTrainedModel):
1249
+ """
1250
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`KPhi3DecoderLayer`]
1251
+
1252
+ Args:
1253
+ config: KPhi3Config
1254
+ """
1255
+
1256
+ def __init__(self, config: KPhi3Config):
1257
+ super().__init__(config)
1258
+ self.padding_idx = config.pad_token_id
1259
+ self.vocab_size = config.vocab_size
1260
+ self.activation_fn = ACT2FN[config.hidden_act]
1261
+
1262
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.embed_size, self.padding_idx)
1263
+ if config.embed_size != config.hidden_size:
1264
+ self.embed_to_hidden = GroupedPointwiseConvolutionBlock(config.embed_size, config.hidden_size, config.min_channels_per_group)
1265
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1266
+ self.layers = nn.ModuleList(
1267
+ [KPhi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1268
+ )
1269
+ self._attn_implementation = config._attn_implementation
1270
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1271
+
1272
+ self.gradient_checkpointing = False
1273
+ # Initialize weights and apply final processing
1274
+ self.post_init()
1275
+
1276
+ def get_input_embeddings(self):
1277
+ return self.embed_tokens
1278
+
1279
+ def set_input_embeddings(self, value):
1280
+ self.embed_tokens = value
1281
+
1282
+ @add_start_docstrings_to_model_forward(KPHI3_INPUTS_DOCSTRING)
1283
+ def forward(
1284
+ self,
1285
+ input_ids: torch.LongTensor = None,
1286
+ attention_mask: Optional[torch.Tensor] = None,
1287
+ position_ids: Optional[torch.LongTensor] = None,
1288
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1289
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1290
+ use_cache: Optional[bool] = None,
1291
+ output_attentions: Optional[bool] = None,
1292
+ output_hidden_states: Optional[bool] = None,
1293
+ return_dict: Optional[bool] = None,
1294
+ cache_position: Optional[torch.LongTensor] = None,
1295
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1296
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1297
+ output_hidden_states = (
1298
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1299
+ )
1300
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1301
+
1302
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1303
+
1304
+ if (input_ids is None) ^ (inputs_embeds is not None):
1305
+ raise ValueError(
1306
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1307
+ )
1308
+
1309
+ if self.gradient_checkpointing and self.training:
1310
+ if use_cache:
1311
+ logger.warning_once(
1312
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1313
+ )
1314
+ use_cache = False
1315
+
1316
+ use_legacy_cache = False
1317
+ if use_cache and not isinstance(past_key_values, Cache) and not self.training:
1318
+ use_legacy_cache = True
1319
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1320
+ logger.warning_once(
1321
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
1322
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
1323
+ )
1324
+
1325
+ if inputs_embeds is None:
1326
+ inputs_embeds = self.embed_tokens(input_ids)
1327
+
1328
+ if cache_position is None:
1329
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1330
+ cache_position = torch.arange(
1331
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1332
+ )
1333
+ if position_ids is None:
1334
+ position_ids = cache_position.unsqueeze(0)
1335
+
1336
+ causal_mask = self._update_causal_mask(
1337
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1338
+ )
1339
+ inputs_embeds = self.embed_dropout(inputs_embeds)
1340
+
1341
+ if self.config.embed_size != self.config.hidden_size:
1342
+ hidden_states = self.embed_to_hidden(inputs_embeds)
1343
+ # hidden_states = self.activation_fn(self.embed_to_hidden(inputs_embeds))
1344
+ else:
1345
+ hidden_states = inputs_embeds
1346
+
1347
+ # decoder layers
1348
+ all_hidden_states = () if output_hidden_states else None
1349
+ all_self_attns = () if output_attentions else None
1350
+ next_decoder_cache = None
1351
+
1352
+ for decoder_layer in self.layers:
1353
+ if output_hidden_states:
1354
+ all_hidden_states += (hidden_states,)
1355
+
1356
+ if self.gradient_checkpointing and self.training:
1357
+ layer_outputs = self._gradient_checkpointing_func(
1358
+ decoder_layer.__call__,
1359
+ hidden_states,
1360
+ causal_mask,
1361
+ position_ids,
1362
+ past_key_values,
1363
+ output_attentions,
1364
+ use_cache,
1365
+ cache_position,
1366
+ )
1367
+ else:
1368
+ layer_outputs = decoder_layer(
1369
+ hidden_states,
1370
+ attention_mask=causal_mask,
1371
+ position_ids=position_ids,
1372
+ past_key_value=past_key_values,
1373
+ output_attentions=output_attentions,
1374
+ use_cache=use_cache,
1375
+ cache_position=cache_position,
1376
+ )
1377
+
1378
+ hidden_states = layer_outputs[0]
1379
+
1380
+ if use_cache:
1381
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1382
+
1383
+ if output_attentions:
1384
+ all_self_attns += (layer_outputs[1],)
1385
+
1386
+ hidden_states = self.norm(hidden_states)
1387
+
1388
+ # add hidden states from the last decoder layer
1389
+ if output_hidden_states:
1390
+ all_hidden_states += (hidden_states,)
1391
+
1392
+ next_cache = None
1393
+ if use_cache:
1394
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1395
+ if not return_dict:
1396
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1397
+ return BaseModelOutputWithPast(
1398
+ last_hidden_state=hidden_states,
1399
+ past_key_values=next_cache,
1400
+ hidden_states=all_hidden_states,
1401
+ attentions=all_self_attns,
1402
+ )
1403
+
1404
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
1405
+ def _update_causal_mask(
1406
+ self,
1407
+ attention_mask: torch.Tensor,
1408
+ input_tensor: torch.Tensor,
1409
+ cache_position: torch.Tensor,
1410
+ past_key_values: Cache,
1411
+ output_attentions: bool,
1412
+ ):
1413
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1414
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1415
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1416
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1417
+
1418
+ if self.config._attn_implementation == "flash_attention_2":
1419
+ if attention_mask is not None and 0.0 in attention_mask:
1420
+ return attention_mask
1421
+ return None
1422
+
1423
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1424
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1425
+ # to infer the attention mask.
1426
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1427
+ using_static_cache = isinstance(past_key_values, StaticCache)
1428
+
1429
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1430
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1431
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1432
+ attention_mask,
1433
+ inputs_embeds=input_tensor,
1434
+ past_key_values_length=past_seen_tokens,
1435
+ is_training=self.training,
1436
+ ):
1437
+ return None
1438
+
1439
+ dtype, device = input_tensor.dtype, input_tensor.device
1440
+ min_dtype = torch.finfo(dtype).min
1441
+ sequence_length = input_tensor.shape[1]
1442
+ if using_static_cache:
1443
+ target_length = past_key_values.get_max_length()
1444
+ else:
1445
+ target_length = (
1446
+ attention_mask.shape[-1]
1447
+ if isinstance(attention_mask, torch.Tensor)
1448
+ else past_seen_tokens + sequence_length + 1
1449
+ )
1450
+
1451
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1452
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1453
+ attention_mask,
1454
+ sequence_length=sequence_length,
1455
+ target_length=target_length,
1456
+ dtype=dtype,
1457
+ device=device,
1458
+ min_dtype=min_dtype,
1459
+ cache_position=cache_position,
1460
+ batch_size=input_tensor.shape[0],
1461
+ )
1462
+
1463
+ if (
1464
+ self.config._attn_implementation == "sdpa"
1465
+ and attention_mask is not None
1466
+ and attention_mask.device.type == "cuda"
1467
+ and not output_attentions
1468
+ ):
1469
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1470
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1471
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1472
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1473
+
1474
+ return causal_mask
1475
+
1476
+
1477
+ class KPhi3ForCausalLM(KPhi3PreTrainedModel):
1478
+ _tied_weights_keys = ["lm_head.weight"]
1479
+
1480
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1481
+ def __init__(self, config):
1482
+ super().__init__(config)
1483
+ self.model = KPhi3Model(config)
1484
+ self.vocab_size = config.vocab_size
1485
+ if config.embed_size != config.hidden_size:
1486
+ self.hidden_to_embed = GroupedPointwiseConvolutionBlock(config.hidden_size, config.embed_size, config.min_channels_per_group)
1487
+ self.lm_head = nn.Linear(config.embed_size, config.vocab_size, bias=False)
1488
+
1489
+ # Initialize weights and apply final processing
1490
+ self.post_init()
1491
+
1492
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1493
+ def get_input_embeddings(self):
1494
+ return self.model.embed_tokens
1495
+
1496
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1497
+ def set_input_embeddings(self, value):
1498
+ self.model.embed_tokens = value
1499
+
1500
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1501
+ def get_output_embeddings(self):
1502
+ return self.lm_head
1503
+
1504
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1505
+ def set_output_embeddings(self, new_embeddings):
1506
+ self.lm_head = new_embeddings
1507
+
1508
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1509
+ def set_decoder(self, decoder):
1510
+ self.model = decoder
1511
+
1512
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1513
+ def get_decoder(self):
1514
+ return self.model
1515
+
1516
+ # Ignore copy
1517
+ @add_start_docstrings_to_model_forward(KPHI3_INPUTS_DOCSTRING)
1518
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1519
+ def forward(
1520
+ self,
1521
+ input_ids: torch.LongTensor = None,
1522
+ attention_mask: Optional[torch.Tensor] = None,
1523
+ position_ids: Optional[torch.LongTensor] = None,
1524
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1525
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1526
+ labels: Optional[torch.LongTensor] = None,
1527
+ use_cache: Optional[bool] = None,
1528
+ output_attentions: Optional[bool] = None,
1529
+ output_hidden_states: Optional[bool] = None,
1530
+ return_dict: Optional[bool] = None,
1531
+ cache_position: Optional[torch.LongTensor] = None,
1532
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1533
+ r"""
1534
+ Args:
1535
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1536
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1537
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1538
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1539
+
1540
+ Returns:
1541
+
1542
+ Example:
1543
+
1544
+ ```python
1545
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1546
+
1547
+ >>> model = KPhi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1548
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1549
+
1550
+ >>> prompt = "This is an example script ."
1551
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1552
+
1553
+ >>> # Generate
1554
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1555
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1556
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1557
+ ```"""
1558
+
1559
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1560
+ output_hidden_states = (
1561
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1562
+ )
1563
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1564
+
1565
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1566
+ outputs = self.model(
1567
+ input_ids=input_ids,
1568
+ attention_mask=attention_mask,
1569
+ position_ids=position_ids,
1570
+ past_key_values=past_key_values,
1571
+ inputs_embeds=inputs_embeds,
1572
+ use_cache=use_cache,
1573
+ output_attentions=output_attentions,
1574
+ output_hidden_states=output_hidden_states,
1575
+ return_dict=return_dict,
1576
+ )
1577
+
1578
+ hidden_states = outputs[0]
1579
+ if self.config.embed_size != self.config.hidden_size:
1580
+ hidden_states = self.hidden_to_embed(hidden_states)
1581
+ logits = self.lm_head(hidden_states)
1582
+ logits = logits.float()
1583
+
1584
+ loss = None
1585
+ if labels is not None:
1586
+ # Shift so that tokens < n predict n
1587
+ shift_logits = logits[..., :-1, :].contiguous()
1588
+ shift_labels = labels[..., 1:].contiguous()
1589
+ # Flatten the tokens
1590
+ loss_fct = CrossEntropyLoss()
1591
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1592
+ shift_labels = shift_labels.view(-1)
1593
+ # Enable model parallelism
1594
+ shift_labels = shift_labels.to(shift_logits.device)
1595
+ loss = loss_fct(shift_logits, shift_labels)
1596
+
1597
+ if not return_dict:
1598
+ output = (logits,) + outputs[1:]
1599
+ return (loss,) + output if loss is not None else output
1600
+
1601
+ return CausalLMOutputWithPast(
1602
+ loss=loss,
1603
+ logits=logits,
1604
+ past_key_values=outputs.past_key_values,
1605
+ hidden_states=outputs.hidden_states,
1606
+ attentions=outputs.attentions,
1607
+ )
1608
+
1609
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1610
+ def prepare_inputs_for_generation(
1611
+ self,
1612
+ input_ids,
1613
+ past_key_values=None,
1614
+ attention_mask=None,
1615
+ inputs_embeds=None,
1616
+ cache_position=None,
1617
+ position_ids=None,
1618
+ use_cache=True,
1619
+ **kwargs,
1620
+ ):
1621
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1622
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1623
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1624
+ if past_key_values is not None:
1625
+ if inputs_embeds is not None: # Exception 1
1626
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1627
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1628
+ input_ids = input_ids[:, cache_position]
1629
+
1630
+ if attention_mask is not None and position_ids is None:
1631
+ # create position_ids on the fly for batch generation
1632
+ position_ids = attention_mask.long().cumsum(-1) - 1
1633
+ position_ids.masked_fill_(attention_mask == 0, 1)
1634
+ if past_key_values:
1635
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1636
+
1637
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1638
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1639
+
1640
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1641
+ if inputs_embeds is not None and cache_position[0] == 0:
1642
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1643
+ else:
1644
+ # The clone here is for the same reason as for `position_ids`.
1645
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1646
+
1647
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1648
+ if model_inputs["inputs_embeds"] is not None:
1649
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1650
+ device = model_inputs["inputs_embeds"].device
1651
+ else:
1652
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1653
+ device = model_inputs["input_ids"].device
1654
+
1655
+ dtype = self.lm_head.weight.dtype
1656
+ min_dtype = torch.finfo(dtype).min
1657
+
1658
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1659
+ attention_mask,
1660
+ sequence_length=sequence_length,
1661
+ target_length=past_key_values.get_max_length(),
1662
+ dtype=dtype,
1663
+ device=device,
1664
+ min_dtype=min_dtype,
1665
+ cache_position=cache_position,
1666
+ batch_size=batch_size,
1667
+ )
1668
+
1669
+ model_inputs.update(
1670
+ {
1671
+ "position_ids": position_ids,
1672
+ "cache_position": cache_position,
1673
+ "past_key_values": past_key_values,
1674
+ "use_cache": use_cache,
1675
+ "attention_mask": attention_mask,
1676
+ }
1677
+ )
1678
+ return model_inputs
1679
+
1680
+
1681
+ @add_start_docstrings(
1682
+ """
1683
+ The [`KPhi3Model`] with a sequence classification head on top (linear layer).
1684
+
1685
+ [`KPhi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1686
+ (e.g. GPT-2) do.
1687
+
1688
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1689
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1690
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1691
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1692
+ each row of the batch).
1693
+ """,
1694
+ KPHI3_START_DOCSTRING,
1695
+ )
1696
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1697
+ class KPhi3ForSequenceClassification(KPhi3PreTrainedModel):
1698
+ def __init__(self, config):
1699
+ super().__init__(config)
1700
+ self.num_labels = config.num_labels
1701
+ self.model = KPhi3Model(config)
1702
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1703
+
1704
+ # Initialize weights and apply final processing
1705
+ self.post_init()
1706
+
1707
+ def get_input_embeddings(self):
1708
+ return self.model.embed_tokens
1709
+
1710
+ def set_input_embeddings(self, value):
1711
+ self.model.embed_tokens = value
1712
+
1713
+ @add_start_docstrings_to_model_forward(KPHI3_INPUTS_DOCSTRING)
1714
+ def forward(
1715
+ self,
1716
+ input_ids: Optional[torch.LongTensor] = None,
1717
+ attention_mask: Optional[torch.Tensor] = None,
1718
+ position_ids: Optional[torch.LongTensor] = None,
1719
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1720
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1721
+ labels: Optional[torch.LongTensor] = None,
1722
+ use_cache: Optional[bool] = None,
1723
+ output_attentions: Optional[bool] = None,
1724
+ output_hidden_states: Optional[bool] = None,
1725
+ return_dict: Optional[bool] = None,
1726
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1727
+ r"""
1728
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1729
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1730
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1731
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1732
+ """
1733
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1734
+
1735
+ model_outputs = self.model(
1736
+ input_ids,
1737
+ attention_mask=attention_mask,
1738
+ position_ids=position_ids,
1739
+ past_key_values=past_key_values,
1740
+ inputs_embeds=inputs_embeds,
1741
+ use_cache=use_cache,
1742
+ output_attentions=output_attentions,
1743
+ output_hidden_states=output_hidden_states,
1744
+ return_dict=return_dict,
1745
+ )
1746
+ hidden_states = model_outputs[0]
1747
+ logits = self.score(hidden_states)
1748
+
1749
+ if input_ids is not None:
1750
+ batch_size = input_ids.shape[0]
1751
+ else:
1752
+ batch_size = inputs_embeds.shape[0]
1753
+
1754
+ if self.config.pad_token_id is None and batch_size != 1:
1755
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1756
+ if self.config.pad_token_id is None:
1757
+ sequence_lengths = -1
1758
+ else:
1759
+ if input_ids is not None:
1760
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1761
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1762
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1763
+ sequence_lengths = sequence_lengths.to(logits.device)
1764
+ else:
1765
+ sequence_lengths = -1
1766
+
1767
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1768
+
1769
+ loss = None
1770
+ if labels is not None:
1771
+ labels = labels.to(logits.device)
1772
+ if self.config.problem_type is None:
1773
+ if self.num_labels == 1:
1774
+ self.config.problem_type = "regression"
1775
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1776
+ self.config.problem_type = "single_label_classification"
1777
+ else:
1778
+ self.config.problem_type = "multi_label_classification"
1779
+
1780
+ if self.config.problem_type == "regression":
1781
+ loss_fct = MSELoss()
1782
+ if self.num_labels == 1:
1783
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1784
+ else:
1785
+ loss = loss_fct(pooled_logits, labels)
1786
+ elif self.config.problem_type == "single_label_classification":
1787
+ loss_fct = CrossEntropyLoss()
1788
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1789
+ elif self.config.problem_type == "multi_label_classification":
1790
+ loss_fct = BCEWithLogitsLoss()
1791
+ loss = loss_fct(pooled_logits, labels)
1792
+ if not return_dict:
1793
+ output = (pooled_logits,) + model_outputs[1:]
1794
+ return ((loss,) + output) if loss is not None else output
1795
+
1796
+ return SequenceClassifierOutputWithPast(
1797
+ loss=loss,
1798
+ logits=pooled_logits,
1799
+ past_key_values=model_outputs.past_key_values,
1800
+ hidden_states=model_outputs.hidden_states,
1801
+ attentions=model_outputs.attentions,
1802
+ )
1803
+
1804
+
1805
+ @add_start_docstrings(
1806
+ """
1807
+ [`KPhi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1808
+ Named-Entity-Recognition (NER) tasks.
1809
+ """,
1810
+ KPHI3_START_DOCSTRING,
1811
+ )
1812
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1813
+ class KPhi3ForTokenClassification(KPhi3PreTrainedModel):
1814
+ def __init__(self, config: KPhi3Config):
1815
+ super().__init__(config)
1816
+ self.num_labels = config.num_labels
1817
+
1818
+ self.model = KPhi3Model(config)
1819
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1820
+ classifier_dropout = config.classifier_dropout
1821
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1822
+ classifier_dropout = config.hidden_dropout
1823
+ else:
1824
+ classifier_dropout = 0.1
1825
+ self.dropout = nn.Dropout(classifier_dropout)
1826
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1827
+
1828
+ # Initialize weights and apply final processing
1829
+ self.post_init()
1830
+
1831
+ @add_start_docstrings_to_model_forward(KPHI3_INPUTS_DOCSTRING)
1832
+ @add_code_sample_docstrings(
1833
+ checkpoint=_CHECKPOINT_FOR_DOC,
1834
+ output_type=TokenClassifierOutput,
1835
+ config_class=_CONFIG_FOR_DOC,
1836
+ )
1837
+ def forward(
1838
+ self,
1839
+ input_ids: Optional[torch.LongTensor] = None,
1840
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1841
+ attention_mask: Optional[torch.Tensor] = None,
1842
+ inputs_embeds: Optional[torch.Tensor] = None,
1843
+ labels: Optional[torch.Tensor] = None,
1844
+ use_cache: Optional[bool] = None,
1845
+ output_attentions: Optional[bool] = None,
1846
+ output_hidden_states: Optional[bool] = None,
1847
+ return_dict: Optional[bool] = None,
1848
+ **deprecated_arguments,
1849
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1850
+ r"""
1851
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1852
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1853
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1854
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1855
+ """
1856
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1857
+
1858
+ model_outputs = self.model(
1859
+ input_ids,
1860
+ past_key_values=past_key_values,
1861
+ attention_mask=attention_mask,
1862
+ inputs_embeds=inputs_embeds,
1863
+ use_cache=use_cache,
1864
+ output_attentions=output_attentions,
1865
+ output_hidden_states=output_hidden_states,
1866
+ return_dict=return_dict,
1867
+ )
1868
+
1869
+ hidden_states = model_outputs[0]
1870
+ hidden_states = self.dropout(hidden_states)
1871
+ logits = self.classifier(hidden_states)
1872
+
1873
+ loss = None
1874
+ if labels is not None:
1875
+ # move labels to correct device to enable model parallelism
1876
+ labels = labels.to(logits.device)
1877
+ batch_size, seq_length = labels.shape
1878
+ loss_fct = CrossEntropyLoss()
1879
+ loss = loss_fct(
1880
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1881
+ )
1882
+
1883
+ if not return_dict:
1884
+ output = (logits,) + model_outputs[2:]
1885
+ return ((loss,) + output) if loss is not None else output
1886
+
1887
+ return TokenClassifierOutput(
1888
+ loss=loss,
1889
+ logits=logits,
1890
+ hidden_states=model_outputs.hidden_states,
1891
+ attentions=model_outputs.attentions,
1892
+ )