schuler commited on
Commit
9dfde3b
·
verified ·
1 Parent(s): 07f3440

Upload 2 files

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