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