Update sample_finetune.py

#8
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Microsoft Open Source Code of Conduct
2
+
3
+ This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
4
+
5
+ Resources:
6
+
7
+ - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
8
+ - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
9
+ - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Microsoft.
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ MIT License
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
NOTICE.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NOTICES AND INFORMATION
2
+ Do Not Translate or Localize
3
+
4
+ This software incorporates material from third parties.
5
+
6
+ **Component.** https://github.com/Dao-AILab/flash-attention
7
+
8
+ **Open Source License/Copyright Notice.**
9
+
10
+ BSD 3-Clause License
11
+
12
+ Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file.
13
+ All rights reserved.
14
+
15
+ Redistribution and use in source and binary forms, with or without
16
+ modification, are permitted provided that the following conditions are met:
17
+
18
+ * Redistributions of source code must retain the above copyright notice, this
19
+ list of conditions and the following disclaimer.
20
+
21
+ * Redistributions in binary form must reproduce the above copyright notice,
22
+ this list of conditions and the following disclaimer in the documentation
23
+ and/or other materials provided with the distribution.
24
+
25
+ * Neither the name of the copyright holder nor the names of its
26
+ contributors may be used to endorse or promote products derived from
27
+ this software without specific prior written permission.
28
+
29
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
30
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
32
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
33
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
36
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
37
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
README.md ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ license_link: https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/LICENSE
4
+
5
+ language:
6
+ - en
7
+ pipeline_tag: text-generation
8
+ tags:
9
+ - nlp
10
+ - code
11
+ ---
12
+
13
+ ## Model Summary
14
+
15
+ The Phi-3-Mini-4K-Instruct is a 3.8B parameters, lightweight, state-of-the-art open model trained with the Phi-3 datasets that includes both synthetic data and the filtered websites data with a focus on high-quality and reasoning dense properties. The model belongs to the Phi-3 family with the Mini version in two variants [4K](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct) and [128K](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct) which is the context length (in tokens) that it can support.
16
+
17
+ The model has underwent a post-training process that incorporates both supervised fine-tuning and direct preference optimization for the instruction following and safety measures.
18
+ When assessed against benchmarks testing common sense, language understanding, math, code, long context and logical reasoning, Phi-3 Mini-4K-Instruct showcased a robust and state-of-the-art performance among models with less than 13 billion parameters.
19
+
20
+ Resources and Technical Documentation:
21
+
22
+ + [Phi-3 Microsoft Blog](https://aka.ms/phi3blog-april)
23
+ + [Phi-3 Technical Report](https://aka.ms/phi3-tech-report)
24
+ + [Phi-3 on Azure AI Studio](https://aka.ms/phi3-azure-ai)
25
+ + Phi-3 GGUF: [4K](https://aka.ms/Phi3-mini-4k-instruct-gguf)
26
+ + Phi-3 ONNX: [4K](https://aka.ms/Phi3-mini-4k-instruct-onnx)
27
+
28
+ ## Intended Uses
29
+
30
+ **Primary use cases**
31
+
32
+ The model is intended for commercial and research use in English. The model provides uses for applications which require:
33
+
34
+ 1) Memory/compute constrained environments
35
+ 2) Latency bound scenarios
36
+ 3) Strong reasoning (especially code, math and logic)
37
+
38
+ Our model is designed to accelerate research on language and multimodal models, for use as a building block for generative AI powered features.
39
+
40
+ **Use case considerations**
41
+
42
+ Our models are not specifically designed or evaluated for all downstream purposes. Developers should consider common limitations of language models as they select use cases, and evaluate and mitigate for accuracy, safety, and fariness before using within a specific downstream use case, particularly for high risk scenarios. Developers should be aware of and adhere to applicable laws or regulations (including privacy, trade compliance laws, etc.) that are relevant to their use case.
43
+
44
+ Nothing contained in this Model Card should be interpreted as or deemed a restriction or modification to the license the model is released under.
45
+
46
+ ## How to Use
47
+
48
+ Phi-3 Mini-4K-Instruct has been integrated in the development version (4.40.0) of `transformers`. Until the official version is released through `pip`, ensure that you are doing one of the following:
49
+
50
+ * When loading the model, ensure that `trust_remote_code=True` is passed as an argument of the `from_pretrained()` function.
51
+
52
+ * Update your local `transformers` to the development version: `pip uninstall -y transformers && pip install git+https://github.com/huggingface/transformers`. The previous command is an alternative to cloning and installing from the source.
53
+
54
+ The current `transformers` version can be verified with: `pip list | grep transformers`.
55
+
56
+ ### Chat Format:
57
+
58
+ Given the nature of the training data, the Phi-3 Mini-4K-Instruct model is best suited for prompts using the chat format as follows.
59
+ You can provide the prompt as a question with a generic template as follow:
60
+ ```markdown
61
+ <|user|>/nQuestion <|end|>/n <|assistant|>
62
+ ```
63
+ For example:
64
+ ```markdown
65
+ <|system|>
66
+ You are a helpful AI assistant.<|end|>
67
+ <|user|>
68
+ How to explain Internet for a medieval knight?<|end|>
69
+ <|assistant|>
70
+ ```
71
+
72
+ where the model generates the text after `<|assistant|>` . In case of few-shots prompt, the prompt can be formatted as the following:
73
+
74
+ ```markdown
75
+ <|system|>
76
+ You are a helpful AI assistant.<|end|>
77
+ <|user|>
78
+ I am going to Paris, what should I see?<|end|>
79
+ <|assistant|>
80
+ Paris, the capital of France, is known for its stunning architecture, art museums, historical landmarks, and romantic atmosphere. Here are some of the top attractions to see in Paris:\n\n1. The Eiffel Tower: The iconic Eiffel Tower is one of the most recognizable landmarks in the world and offers breathtaking views of the city.\n2. The Louvre Museum: The Louvre is one of the world's largest and most famous museums, housing an impressive collection of art and artifacts, including the Mona Lisa.\n3. Notre-Dame Cathedral: This beautiful cathedral is one of the most famous landmarks in Paris and is known for its Gothic architecture and stunning stained glass windows.\n\nThese are just a few of the many attractions that Paris has to offer. With so much to see and do, it's no wonder that Paris is one of the most popular tourist destinations in the world."<|end|>
81
+ <|user|>
82
+ What is so great about #1?
83
+ <|assistant|>
84
+ ```
85
+
86
+ ### Sample inference code
87
+
88
+ This code snippets show how to get quickly started with running the model on a GPU:
89
+
90
+ ```python
91
+ import torch
92
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
93
+
94
+ torch.random.manual_seed(0)
95
+
96
+ model = AutoModelForCausalLM.from_pretrained(
97
+ "microsoft/Phi-3-mini-4k-instruct",
98
+ device_map="cuda",
99
+ torch_dtype="auto",
100
+ trust_remote_code=True,
101
+ )
102
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
103
+
104
+ messages = [
105
+ {"role": "system", "content": "You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user."},
106
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
107
+ {"role": "assistant", "content": "Sure! Here are some ways to eat bananas and dragonfruits together: 1. Banana and dragonfruit smoothie: Blend bananas and dragonfruits together with some milk and honey. 2. Banana and dragonfruit salad: Mix sliced bananas and dragonfruits together with some lemon juice and honey."},
108
+ {"role": "user", "content": "What about solving an 2x + 3 = 7 equation?"},
109
+ ]
110
+
111
+ pipe = pipeline(
112
+ "text-generation",
113
+ model=model,
114
+ tokenizer=tokenizer,
115
+ )
116
+
117
+ generation_args = {
118
+ "max_new_tokens": 500,
119
+ "return_full_text": False,
120
+ "temperature": 0.0,
121
+ "do_sample": False,
122
+ }
123
+
124
+ output = pipe(messages, **generation_args)
125
+ print(output[0]['generated_text'])
126
+ ```
127
+
128
+ ## Responsible AI Considerations
129
+
130
+ Like other language models, the Phi series models can potentially behave in ways that are unfair, unreliable, or offensive. Some of the limiting behaviors to be aware of include:
131
+
132
+ + Quality of Service: the Phi models are trained primarily on English text. Languages other than English will experience worse performance. English language varieties with less representation in the training data might experience worse performance than standard American English.
133
+ + Representation of Harms & Perpetuation of Stereotypes: These models can over- or under-represent groups of people, erase representation of some groups, or reinforce demeaning or negative stereotypes. Despite safety post-training, these limitations may still be present due to differing levels of representation of different groups or prevalence of examples of negative stereotypes in training data that reflect real-world patterns and societal biases.
134
+ + Inappropriate or Offensive Content: these models may produce other types of inappropriate or offensive content, which may make it inappropriate to deploy for sensitive contexts without additional mitigations that are specific to the use case.
135
+ + Information Reliability: Language models can generate nonsensical content or fabricate content that might sound reasonable but is inaccurate or outdated.
136
+ + Limited Scope for Code: Majority of Phi-3 training data is based in Python and use common packages such as "typing, math, random, collections, datetime, itertools". If the model generates Python scripts that utilize other packages or scripts in other languages, we strongly recommend users manually verify all API uses.
137
+
138
+ Developers should apply responsible AI best practices and are responsible for ensuring that a specific use case complies with relevant laws and regulations (e.g. privacy, trade, etc.). Important areas for consideration include:
139
+
140
+ + Allocation: Models may not be suitable for scenarios that could have consequential impact on legal status or the allocation of resources or life opportunities (ex: housing, employment, credit, etc.) without further assessments and additional debiasing techniques.
141
+ + High-Risk Scenarios: Developers should assess suitability of using models in high-risk scenarios where unfair, unreliable or offensive outputs might be extremely costly or lead to harm. This includes providing advice in sensitive or expert domains where accuracy and reliability are critical (ex: legal or health advice). Additional safeguards should be implemented at the application level according to the deployment context.
142
+ + Misinformation: Models may produce inaccurate information. Developers should follow transparency best practices and inform end-users they are interacting with an AI system. At the application level, developers can build feedback mechanisms and pipelines to ground responses in use-case specific, contextual information, a technique known as Retrieval Augmented Generation (RAG).
143
+ + Generation of Harmful Content: Developers should assess outputs for their context and use available safety classifiers or custom solutions appropriate for their use case.
144
+ + Misuse: Other forms of misuse such as fraud, spam, or malware production may be possible, and developers should ensure that their applications do not violate applicable laws and regulations.
145
+
146
+
147
+ ## Training
148
+
149
+ ### Model
150
+
151
+ * Architecture: Phi-3 Mini-4K-Instruct has 3.8B parameters and is a dense decoder-only Transformer model. The model is fine-tuned with Supervised fine-tuning (SFT) and Direct Preference Optimization (DPO) to ensure alignment with human preferences and safety guidlines.
152
+ * Inputs: Text. It is best suited for prompts using chat format.
153
+ * Context length: 4K tokens
154
+ * GPUs: 512 H100-80G
155
+ * Training time: 7 days
156
+ * Training data: 3.3T tokens
157
+ * Outputs: Generated text in response to the input
158
+ * Dates: Our models were trained between February and April 2024
159
+ * Status: This is a static model trained on an offline dataset with cutoff date October 2023. Future versions of the tuned models may be released as we improve models.
160
+
161
+ ### Datasets
162
+
163
+ Our training data includes a wide variety of sources, totaling 3.3 trillion tokens, and is a combination of
164
+ 1) Publicly available documents filtered rigorously for quality, selected high-quality educational data, and code;
165
+ 2) Newly created synthetic, “textbook-like” data for the purpose of teaching math, coding, common sense reasoning, general knowledge of the world (science, daily activities, theory of mind, etc.);
166
+ 3) High quality chat format supervised data covering various topics to reflect human preferences on different aspects such as instruct-following, truthfulness, honesty and helpfulness.
167
+
168
+ ### Fine-tuning
169
+
170
+ A basic example of multi-GPUs supervised fine-tuning (SFT) with TRL and Accelerate modules is provided [here](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/sample_finetune.py).
171
+
172
+ ## Benchmarks
173
+
174
+ We report the results for Phi-3-Mini-4K-Instruct on standard open-source benchmarks measuring the model's reasoning ability (both common sense reasoning and logical reasoning). We compare to Phi-2, Mistral-7b-v0.1, Mixtral-8x7b, Gemma 7B, Llama-3-8B-Instruct, and GPT-3.5.
175
+
176
+ All the reported numbers are produced with the exact same pipeline to ensure that the numbers are comparable. These numbers might differ from other published numbers due to slightly different choices in the evaluation.
177
+
178
+ As is now standard, we use few-shot prompts to evaluate the models, at temperature 0.
179
+ The prompts and number of shots are part of a Microsoft internal tool to evaluate language models, and in particular we did no optimization to the pipeline for Phi-3.
180
+ More specifically, we do not change prompts, pick different few-shot examples, change prompt format, or do any other form of optimization for the model.
181
+
182
+ The number of k–shot examples is listed per-benchmark.
183
+
184
+ | | Phi-3-Mini-4K-In<br>3.8b | Phi-3-Small<br>7b (preview) | Phi-3-Medium<br>14b (preview) | Phi-2<br>2.7b | Mistral<br>7b | Gemma<br>7b | Llama-3-In<br>8b | Mixtral<br>8x7b | GPT-3.5<br>version 1106 |
185
+ |---|---|---|---|---|---|---|---|---|---|
186
+ | MMLU <br>5-Shot | 68.8 | 75.3 | 78.2 | 56.3 | 61.7 | 63.6 | 66.0 | 68.4 | 71.4 |
187
+ | HellaSwag <br> 5-Shot | 76.7 | 78.7 | 83.2 | 53.6 | 58.5 | 49.8 | 69.5 | 70.4 | 78.8 |
188
+ | ANLI <br> 7-Shot | 52.8 | 55.0 | 58.7 | 42.5 | 47.1 | 48.7 | 54.8 | 55.2 | 58.1 |
189
+ | GSM-8K <br> 0-Shot; CoT | 82.5 | 86.4 | 90.8 | 61.1 | 46.4 | 59.8 | 77.4 | 64.7 | 78.1 |
190
+ | MedQA <br> 2-Shot | 53.8 | 58.2 | 69.8 | 40.9 | 49.6 | 50.0 | 58.9 | 62.2 | 63.4 |
191
+ | AGIEval <br> 0-Shot | 37.5 | 45.0 | 49.7 | 29.8 | 35.1 | 42.1 | 42.0 | 45.2 | 48.4 |
192
+ | TriviaQA <br> 5-Shot | 64.0 | 59.1 | 73.3 | 45.2 | 72.3 | 75.2 | 73.6 | 82.2 | 85.8 |
193
+ | Arc-C <br> 10-Shot | 84.9 | 90.7 | 91.9 | 75.9 | 78.6 | 78.3 | 80.5 | 87.3 | 87.4 |
194
+ | Arc-E <br> 10-Shot | 94.6 | 97.1 | 98.0 | 88.5 | 90.6 | 91.4 | 92.3 | 95.6 | 96.3 |
195
+ | PIQA <br> 5-Shot | 84.2 | 87.8 | 88.2 | 60.2 | 77.7 | 78.1 | 77.1 | 86.0 | 86.6 |
196
+ | SociQA <br> 5-Shot | 76.6 | 79.0 | 79.4 | 68.3 | 74.6 | 65.5 | 73.2 | 75.9 | 68.3 |
197
+ | BigBench-Hard <br> 0-Shot | 71.7 | 75.0 | 82.5 | 59.4 | 57.3 | 59.6 | 68.9 | 69.7 | 68.32 |
198
+ | WinoGrande <br> 5-Shot | 70.8 | 82.5 | 81.2 | 54.7 | 54.2 | 55.6 | 58.0 | 62.0 | 68.8 |
199
+ | OpenBookQA <br> 10-Shot | 83.2 | 88.4 | 86.6 | 73.6 | 79.8 | 78.6 | 81.6 | 85.8 | 86.0 |
200
+ | BoolQ <br> 0-Shot | 77.2 | 82.9 | 86.5 | -- | 72.2 | 66.0 | 78.3 | 77.6 | 79.1 |
201
+ | CommonSenseQA <br> 10-Shot | 80.2 | 80.3 | 82.6 | 69.3 | 72.6 | 76.2 | 73.6 | 78.1 | 79.6 |
202
+ | TruthfulQA <br> 10-Shot | 65.0 | 68.1 | 74.8 | -- | 52.1 | 53.0 | 62.0 | 60.1 | 85.8 |
203
+ | HumanEval <br> 0-Shot | 58.5 | 59.1 | 54.7 | 59.0 | 28.0 | 34.1 | 38.4 | 37.8 | 62.2 |
204
+ | MBPP <br> 3-Shot | 70.0 | 71.4 | 73.7 | 60.6 | 50.8 | 51.5 | 65.3 | 60.2 | 77.8 |
205
+
206
+ ## Software
207
+
208
+ * [PyTorch](https://github.com/pytorch/pytorch)
209
+ * [DeepSpeed](https://github.com/microsoft/DeepSpeed)
210
+ * [Transformers](https://github.com/huggingface/transformers)
211
+ * [Flash-Attention](https://github.com/HazyResearch/flash-attention)
212
+
213
+ ## Hardware
214
+ Note that by default, the Phi-3-mini model uses flash attention, which requires certain types of GPU hardware to run. We have tested on the following GPU types:
215
+ * NVIDIA A100
216
+ * NVIDIA A6000
217
+ * NVIDIA H100
218
+
219
+ If you want to run the model on:
220
+ * NVIDIA V100 or earlier generation GPUs: call AutoModelForCausalLM.from_pretrained() with attn_implementation="eager"
221
+ * CPU: use the **GGUF** quantized models [4K](https://aka.ms/Phi3-mini-4k-instruct-gguf)
222
+ + Optimized inference on GPU, CPU, and Mobile: use the **ONNX** models [4K](https://aka.ms/Phi3-mini-4k-instruct-onnx)
223
+
224
+
225
+ ## Cross Platform Support
226
+
227
+ ONNX runtime ecosystem now supports Phi-3 Mini models across platforms and hardware. You can find the optimized ONNX models [here](https://aka.ms/Phi3-ONNX-HF).
228
+
229
+ Optimized Phi-3 models are also published here in ONNX format, to run with ONNX Runtime on CPU and GPU across devices, including server platforms, Windows, Linux and Mac desktops, and mobile CPUs, with the precision best suited to each of these targets. DirectML support lets developers bring hardware acceleration to Windows devices at scale across AMD, Intel, and NVIDIA GPUs.
230
+ Along with DirectML, ONNX Runtime provides cross platform support for Phi-3 across a range of devices CPU, GPU, and mobile.
231
+
232
+ Here are some of the optimized configurations we have added:
233
+
234
+ 1. ONNX models for int4 DML: Quantized to int4 via AWQ
235
+ 2. ONNX model for fp16 CUDA
236
+ 3. ONNX model for int4 CUDA: Quantized to int4 via RTN
237
+ 4. ONNX model for int4 CPU and Mobile: Quantized to int4 via RTN
238
+
239
+ ## License
240
+
241
+ The model is licensed under the [MIT license](https://huggingface.co/microsoft/Phi-3-mini-4k/resolve/main/LICENSE).
242
+
243
+ ## Trademarks
244
+
245
+ This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft’s Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party’s policies.
SECURITY.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BEGIN MICROSOFT SECURITY.MD V0.0.9 BLOCK -->
2
+
3
+ ## Security
4
+
5
+ Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin).
6
+
7
+ If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below.
8
+
9
+ ## Reporting Security Issues
10
+
11
+ **Please do not report security vulnerabilities through public GitHub issues.**
12
+
13
+ Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report).
14
+
15
+ If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp).
16
+
17
+ You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
18
+
19
+ Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
20
+
21
+ * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
22
+ * Full paths of source file(s) related to the manifestation of the issue
23
+ * The location of the affected source code (tag/branch/commit or direct URL)
24
+ * Any special configuration required to reproduce the issue
25
+ * Step-by-step instructions to reproduce the issue
26
+ * Proof-of-concept or exploit code (if possible)
27
+ * Impact of the issue, including how an attacker might exploit the issue
28
+
29
+ This information will help us triage your report more quickly.
30
+
31
+ If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs.
32
+
33
+ ## Preferred Languages
34
+
35
+ We prefer all communications to be in English.
36
+
37
+ ## Policy
38
+
39
+ Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd).
40
+
41
+ <!-- END MICROSOFT SECURITY.MD BLOCK -->
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,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Phi-3-mini-4k-instruct",
3
+ "architectures": [
4
+ "Phi3ForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3.Phi3Config",
9
+ "AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "embd_pdrop": 0.0,
13
+ "eos_token_id": 32000,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 3072,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 8192,
18
+ "max_position_embeddings": 4096,
19
+ "model_type": "phi3",
20
+ "num_attention_heads": 32,
21
+ "num_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": null,
28
+ "rope_theta": 10000.0,
29
+ "sliding_window": 2047,
30
+ "tie_word_embeddings": false,
31
+ "torch_dtype": "bfloat16",
32
+ "transformers_version": "4.39.3",
33
+ "use_cache": true,
34
+ "vocab_size": 32064
35
+ }
configuration_phi3.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 factor for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ 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.sliding_window = sliding_window
162
+
163
+ super().__init__(
164
+ eos_token_id=eos_token_id,
165
+ pad_token_id=pad_token_id,
166
+ tie_word_embeddings=tie_word_embeddings,
167
+ **kwargs,
168
+ )
169
+
170
+ def _rope_scaling_validation(self):
171
+ if self.rope_scaling is None:
172
+ return
173
+
174
+ assert (
175
+ (isinstance(self.rope_scaling, dict))
176
+ and ("type" in self.rope_scaling)
177
+ and ("short_factor" in self.rope_scaling)
178
+ and ("long_factor" in self.rope_scaling)
179
+ ), (
180
+ "`rope_scaling` must be a dictionary with three keys: `type`, `short_factor` and `long_factor`, "
181
+ f"got {self.rope_scaling}."
182
+ )
183
+
184
+ assert self.rope_scaling["type"].lower() == "longrope", "RoPE scaling type must be `longrope`."
185
+
186
+ short_factor = self.rope_scaling["short_factor"]
187
+ assert isinstance(short_factor, list) and all(
188
+ isinstance(x, (int, float)) for x in short_factor
189
+ ), f"RoPE scaling factor must be a list of numbers, got {short_factor}."
190
+ assert (
191
+ len(short_factor) == self.hidden_size // self.num_attention_heads // 2
192
+ ), f"Length of RoPE scaling factor must be half of the attention head, got {short_factor}."
193
+
194
+ long_factor = self.rope_scaling["long_factor"]
195
+ assert isinstance(long_factor, list) and all(
196
+ isinstance(x, (int, float)) for x in long_factor
197
+ ), f"RoPE scaling factor must be a list of numbers, got {long_factor}."
198
+ assert (
199
+ len(long_factor) == self.hidden_size // self.num_attention_heads // 2
200
+ ), f"Length of RoPE scaling factor must be half of the attention head, got {long_factor}."
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.39.3"
10
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f95c89449ba404df51c3f633df65c52cabea9dbfae7e21977d32b5daa397cc91
3
+ size 4972489328
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5de695669421c1e12d2d1588a4795de6a5900bd1513c06be357b65a041b3590e
3
+ size 2669692552
model.safetensors.index.json ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 7642159104
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00002-of-00002.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.1.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.10.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.11.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.11.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.12.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.12.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.13.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.13.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.14.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.14.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.15.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.15.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.16.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.16.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.17.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.17.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.18.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.18.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.19.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.19.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.2.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.2.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
88
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
90
+ "model.layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.20.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
93
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
94
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
95
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
96
+ "model.layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.21.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
98
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
99
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
100
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
101
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
102
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
103
+ "model.layers.22.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
104
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
105
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
106
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
107
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
108
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
109
+ "model.layers.23.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
110
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
111
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
112
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
113
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
114
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
115
+ "model.layers.24.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
116
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
117
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
118
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
119
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
120
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
121
+ "model.layers.25.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
122
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
123
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
124
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
125
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
126
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
127
+ "model.layers.26.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
128
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
129
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
130
+ "model.layers.27.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
131
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
132
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
133
+ "model.layers.27.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
134
+ "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
135
+ "model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
136
+ "model.layers.28.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
137
+ "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
138
+ "model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
139
+ "model.layers.28.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
140
+ "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
141
+ "model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
142
+ "model.layers.29.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
143
+ "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
144
+ "model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
145
+ "model.layers.29.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
146
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.3.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.3.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
153
+ "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
154
+ "model.layers.30.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
155
+ "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
156
+ "model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
157
+ "model.layers.30.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
158
+ "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
159
+ "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
160
+ "model.layers.31.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
161
+ "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
162
+ "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
163
+ "model.layers.31.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
164
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
165
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
166
+ "model.layers.4.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
167
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
168
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
169
+ "model.layers.4.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
170
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
171
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
172
+ "model.layers.5.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
173
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
174
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
175
+ "model.layers.5.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
176
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
177
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
178
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
179
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
180
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
181
+ "model.layers.6.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
182
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
183
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
184
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
185
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
186
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
187
+ "model.layers.7.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
188
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.8.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.8.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.9.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
199
+ "model.layers.9.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
200
+ "model.norm.weight": "model-00002-of-00002.safetensors"
201
+ }
202
+ }
modeling_phi3.py ADDED
@@ -0,0 +1,1626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
58
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
59
+
60
+ if not _flash_supports_window_size:
61
+ raise ValueError("Please update flash-attention to support window size.")
62
+
63
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
64
+ from flash_attn.ops.activations import swiglu
65
+ from flash_attn.ops.rms_norm import RMSNorm as Phi3FlashRMSNorm
66
+ # else:
67
+ except ImportError as error:
68
+ logger.warning(
69
+ f"Flash Attention or Flash Attention Submodules not found, consider installing for better performance: {error}."
70
+ )
71
+ if not _flash_supports_window_size:
72
+ logger.warning(
73
+ "This version of flash does not support window size. Please use `attn_implementation='eager'` or upgrade flash-attn library."
74
+ )
75
+ swiglu = None
76
+ Phi3FlashRMSNorm = None
77
+
78
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
79
+ _CONFIG_FOR_DOC = "Phi3Config"
80
+
81
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
82
+ "microsoft/Phi-3-mini-4k-instruct",
83
+ "microsoft/Phi-3-mini-128k-instruct",
84
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
85
+ ]
86
+
87
+
88
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
89
+ class Phi3RMSNorm(nn.Module):
90
+ def __init__(self, hidden_size, eps=1e-6):
91
+ """
92
+ Phi3RMSNorm is equivalent to T5LayerNorm
93
+ """
94
+ super().__init__()
95
+ self.weight = nn.Parameter(torch.ones(hidden_size))
96
+ self.variance_epsilon = eps
97
+
98
+ def forward(self, hidden_states):
99
+ input_dtype = hidden_states.dtype
100
+ hidden_states = hidden_states.to(torch.float32)
101
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
102
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
103
+ return self.weight * hidden_states.to(input_dtype)
104
+
105
+
106
+ PHI3_NORM_CLASS = Phi3RMSNorm if Phi3FlashRMSNorm is None else Phi3FlashRMSNorm
107
+
108
+
109
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
110
+ def _get_unpad_data(attention_mask):
111
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
112
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
113
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
114
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
115
+ return (
116
+ indices,
117
+ cu_seqlens,
118
+ max_seqlen_in_batch,
119
+ )
120
+
121
+
122
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Phi3
123
+ class Phi3RotaryEmbedding(nn.Module):
124
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
125
+ super().__init__()
126
+
127
+ self.dim = dim
128
+ self.max_position_embeddings = max_position_embeddings
129
+ self.base = base
130
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
131
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
132
+
133
+ # Build here to make `torch.jit.trace` work.
134
+ self._set_cos_sin_cache(
135
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
136
+ )
137
+
138
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
139
+ self.max_seq_len_cached = seq_len
140
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
141
+
142
+ freqs = torch.outer(t, self.inv_freq)
143
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
146
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
147
+
148
+ def forward(self, x, seq_len=None):
149
+ # x: [bs, num_attention_heads, seq_len, head_size]
150
+ if seq_len > self.max_seq_len_cached:
151
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
152
+
153
+ return (
154
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
155
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
156
+ )
157
+
158
+
159
+ class Phi3LongScaledRotaryEmbedding(nn.Module):
160
+ def __init__(
161
+ self,
162
+ dim,
163
+ short_factor,
164
+ long_factor,
165
+ max_position_embeddings=4096,
166
+ original_max_position_embeddings=4096,
167
+ base=10000,
168
+ magnitude_scaling_policy="su",
169
+ ):
170
+ super().__init__()
171
+
172
+ self.dim = dim
173
+ self.max_position_embeddings = max_position_embeddings
174
+ self.original_max_position_embeddings = original_max_position_embeddings
175
+ self.base = base
176
+
177
+ if magnitude_scaling_policy == "su":
178
+ self._calc_mscale = self._calc_mscale_su
179
+ elif magnitude_scaling_policy == "yarn":
180
+ self._calc_mscale = self._calc_mscale_yarn
181
+ else:
182
+ self._calc_mscale = lambda scale: float(scale)
183
+
184
+ self.short_factor = short_factor
185
+ self.long_factor = long_factor
186
+
187
+ def _calc_mscale_su(self, scale):
188
+ if scale <= 1.0:
189
+ return 1.0
190
+ return math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
191
+
192
+ def _calc_mscale_yarn(self, scale):
193
+ if scale <= 1.0:
194
+ return 1.0
195
+ return 0.1 * math.log(scale) + 1.0
196
+
197
+ @torch.no_grad()
198
+ def forward(self, x, seq_len=None):
199
+ if seq_len is None:
200
+ seq_len = x.shape[-2]
201
+ t = torch.arange(seq_len, device=x.device, dtype=torch.float32)
202
+
203
+ if seq_len > self.original_max_position_embeddings:
204
+ t = torch.arange(seq_len, device=x.device, dtype=torch.float32)
205
+ rescale_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
206
+ else:
207
+ t = torch.arange(self.original_max_position_embeddings, device=x.device, dtype=torch.float32)
208
+ rescale_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
209
+ assert rescale_factors.shape == (
210
+ self.dim // 2,
211
+ ), f"misaligned shape for LongRoPE rescale factors: {rescale_factors.shape}"
212
+
213
+ inv_freq = 1.0 / (
214
+ rescale_factors * (self.base ** (torch.arange(0, self.dim, 2).float().to(x.device) / self.dim))
215
+ )
216
+
217
+ freqs = torch.outer(t, inv_freq)
218
+ mscale = self._calc_mscale(self.max_position_embeddings / self.original_max_position_embeddings)
219
+ emb = torch.cat((freqs, freqs), dim=-1)
220
+
221
+ return (emb.cos() * mscale).to(x.dtype), (emb.sin() * mscale).to(x.dtype)
222
+
223
+
224
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
225
+ def rotate_half(x):
226
+ """Rotates half the hidden dims of the input."""
227
+ x1 = x[..., : x.shape[-1] // 2]
228
+ x2 = x[..., x.shape[-1] // 2 :]
229
+ return torch.cat((-x2, x1), dim=-1)
230
+
231
+
232
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
233
+ """Applies Rotary Position Embedding to the query and key tensors.
234
+
235
+ Args:
236
+ q (`torch.Tensor`): The query tensor.
237
+ k (`torch.Tensor`): The key tensor.
238
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
239
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
240
+ position_ids (`torch.Tensor`):
241
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
242
+ used to pass offsetted position ids when working with a KV-cache.
243
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
244
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
245
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
246
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
247
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
248
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
249
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
250
+ Returns:
251
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
252
+ """
253
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
254
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
255
+ # Need fp32 here to match logits
256
+ q_embed = (q.to(dtype=torch.float32) * cos.to(dtype=torch.float32)) + (
257
+ rotate_half(q).to(dtype=torch.float32) * sin.to(dtype=torch.float32)
258
+ )
259
+ k_embed = (k.to(dtype=torch.float32) * cos.to(dtype=torch.float32)) + (
260
+ rotate_half(k).to(dtype=torch.float32) * sin.to(dtype=torch.float32)
261
+ )
262
+ return q_embed.to(q.dtype), k_embed.to(k.dtype)
263
+
264
+
265
+ class Phi3MLP(nn.Module):
266
+ """Gated Linear Unit.
267
+
268
+ Reference:
269
+ Language Modeling with Gated Convolutional Networks.
270
+ https://arxiv.org/pdf/1612.08083v3.pdf.
271
+
272
+ """
273
+
274
+ def __init__(self, config):
275
+ super().__init__()
276
+
277
+ self.config = config
278
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
279
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
280
+
281
+ self.activation_fn = ACT2FN[config.hidden_act]
282
+
283
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
284
+ y = self.gate_up_proj(hidden_states)
285
+
286
+ # Special case for SwiGLU
287
+ if self.config.hidden_act == "silu" and swiglu is not None:
288
+ gate, y = y.chunk(2, dim=-1)
289
+ y = swiglu(gate, y)
290
+ else:
291
+ gate, y = y.chunk(2, dim=-1)
292
+ y = y * self.activation_fn(gate)
293
+
294
+ return self.down_proj(y)
295
+
296
+
297
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
298
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
299
+ """
300
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
301
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
302
+ """
303
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
304
+ if n_rep == 1:
305
+ return hidden_states
306
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
307
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
308
+
309
+
310
+ class Phi3Attention(nn.Module):
311
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
312
+
313
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
314
+ super().__init__()
315
+ self.config = config
316
+ self.layer_idx = layer_idx
317
+ if layer_idx is None:
318
+ logger.warning_once(
319
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
320
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
321
+ "when creating this class."
322
+ )
323
+
324
+ self.attention_dropout = config.attention_dropout
325
+ self.hidden_size = config.hidden_size
326
+ self.num_heads = config.num_attention_heads
327
+ self.head_dim = self.hidden_size // self.num_heads
328
+ self.num_key_value_heads = config.num_key_value_heads
329
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
330
+ self.max_position_embeddings = config.max_position_embeddings
331
+ self.original_max_position_embeddings = config.original_max_position_embeddings
332
+ self.rope_theta = config.rope_theta
333
+ self.rope_scaling = config.rope_scaling
334
+ self.is_causal = True
335
+
336
+ if (self.head_dim * self.num_heads) != self.hidden_size:
337
+ raise ValueError(
338
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
339
+ f" and `num_heads`: {self.num_heads})."
340
+ )
341
+
342
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
343
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
344
+
345
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
346
+
347
+ if self.rope_scaling is None:
348
+ self.rotary_emb = Phi3RotaryEmbedding(
349
+ self.head_dim,
350
+ max_position_embeddings=self.max_position_embeddings,
351
+ base=self.rope_theta,
352
+ )
353
+ else:
354
+ self.rotary_emb = Phi3LongScaledRotaryEmbedding(
355
+ self.head_dim,
356
+ self.config.rope_scaling["short_factor"],
357
+ self.config.rope_scaling["long_factor"],
358
+ max_position_embeddings=self.config.max_position_embeddings,
359
+ original_max_position_embeddings=self.config.original_max_position_embeddings,
360
+ base=self.config.rope_theta,
361
+ )
362
+
363
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
364
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
365
+
366
+ def forward(
367
+ self,
368
+ hidden_states: torch.Tensor,
369
+ attention_mask: Optional[torch.Tensor] = None,
370
+ position_ids: Optional[torch.LongTensor] = None,
371
+ past_key_value: Optional[Cache] = None,
372
+ output_attentions: bool = False,
373
+ use_cache: bool = False,
374
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
375
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
376
+
377
+ bsz, q_len, _ = hidden_states.size()
378
+
379
+ qkv = self.qkv_proj(hidden_states)
380
+ query_pos = self.num_heads * self.head_dim
381
+ query_states = qkv[..., :query_pos]
382
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
383
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
384
+
385
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
386
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
387
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
388
+
389
+ kv_seq_len = key_states.shape[-2]
390
+ if past_key_value is not None:
391
+ if self.layer_idx is None:
392
+ raise ValueError(
393
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
394
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
395
+ "with a layer index."
396
+ )
397
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
398
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
399
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
400
+
401
+ if past_key_value is not None:
402
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
403
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
404
+
405
+ # repeat k/v heads if n_kv_heads < n_heads
406
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
407
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
408
+
409
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
410
+
411
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
412
+ raise ValueError(
413
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
414
+ f" {attn_weights.size()}"
415
+ )
416
+
417
+ if attention_mask is not None:
418
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
419
+ raise ValueError(
420
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
421
+ )
422
+ attn_weights = attn_weights + attention_mask
423
+
424
+ # upcast attention to fp32
425
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
426
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
427
+
428
+ attn_output = torch.matmul(attn_weights, value_states)
429
+
430
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
431
+ raise ValueError(
432
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
433
+ f" {attn_output.size()}"
434
+ )
435
+
436
+ attn_output = attn_output.transpose(1, 2).contiguous()
437
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
438
+
439
+ attn_output = self.o_proj(attn_output)
440
+
441
+ if not output_attentions:
442
+ attn_weights = None
443
+
444
+ return attn_output, attn_weights, past_key_value
445
+
446
+
447
+ class Phi3FlashAttention2(Phi3Attention):
448
+ """
449
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
450
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
451
+ flash attention and deal with padding tokens in case the input contains any of them.
452
+ """
453
+
454
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
455
+ def __init__(self, *args, **kwargs):
456
+ super().__init__(*args, **kwargs)
457
+
458
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
459
+ # 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.
460
+ # 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).
461
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
462
+
463
+ def forward(
464
+ self,
465
+ hidden_states: torch.Tensor,
466
+ attention_mask: Optional[torch.LongTensor] = None,
467
+ position_ids: Optional[torch.LongTensor] = None,
468
+ past_key_value: Optional[Cache] = None,
469
+ output_attentions: bool = False,
470
+ use_cache: bool = False,
471
+ **kwargs,
472
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
473
+ # Phi3FlashAttention2 attention does not support output_attentions
474
+
475
+ if not _flash_supports_window_size:
476
+ logger.warning_once(
477
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
478
+ )
479
+ raise ValueError("The current flash attention version does not support sliding window attention.")
480
+
481
+ output_attentions = False
482
+
483
+ if "padding_mask" in kwargs:
484
+ warnings.warn(
485
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
486
+ )
487
+
488
+ # overwrite attention_mask with padding_mask
489
+ attention_mask = kwargs.pop("padding_mask")
490
+
491
+ bsz, q_len, _ = hidden_states.size()
492
+
493
+ qkv = self.qkv_proj(hidden_states)
494
+ query_pos = self.num_heads * self.head_dim
495
+ query_states = qkv[..., :query_pos]
496
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
497
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
498
+
499
+ # Flash attention requires the input to have the shape
500
+ # batch_size x seq_length x head_dim x hidden_dim
501
+ # therefore we just need to keep the original shape
502
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
503
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
504
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
505
+
506
+ kv_seq_len = key_states.shape[-2]
507
+ if past_key_value is not None:
508
+ if self.layer_idx is None:
509
+ raise ValueError(
510
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
511
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
512
+ "with a layer index."
513
+ )
514
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
515
+
516
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
517
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
518
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
519
+
520
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
521
+
522
+ use_sliding_windows = (
523
+ _flash_supports_window_size
524
+ and getattr(self.config, "sliding_window", None) is not None
525
+ and kv_seq_len > self.config.sliding_window
526
+ )
527
+
528
+ if past_key_value is not None:
529
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
530
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
531
+ if (
532
+ getattr(self.config, "sliding_window", None) is not None
533
+ and kv_seq_len > self.config.sliding_window
534
+ and cache_has_contents
535
+ ):
536
+ slicing_tokens = 1 - self.config.sliding_window
537
+
538
+ past_key = past_key_value[self.layer_idx][0]
539
+ past_value = past_key_value[self.layer_idx][1]
540
+
541
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
542
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
543
+
544
+ if past_key.shape[-2] != self.config.sliding_window - 1:
545
+ raise ValueError(
546
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
547
+ f" {past_key.shape}"
548
+ )
549
+
550
+ if attention_mask is not None:
551
+ attention_mask = attention_mask[:, slicing_tokens:]
552
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
553
+
554
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
555
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
556
+
557
+ # repeat k/v heads if n_kv_heads < n_heads
558
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
559
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
560
+
561
+ attn_dropout = self.attention_dropout if self.training else 0.0
562
+
563
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
564
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
565
+ # cast them back in the correct dtype just to be sure everything works as expected.
566
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
567
+ # in fp32.
568
+
569
+ if query_states.dtype == torch.float32:
570
+ if torch.is_autocast_enabled():
571
+ target_dtype = torch.get_autocast_gpu_dtype()
572
+ # Handle the case where the model is quantized
573
+ elif hasattr(self.config, "_pre_quantization_dtype"):
574
+ target_dtype = self.config._pre_quantization_dtype
575
+ else:
576
+ target_dtype = self.qkv_proj.weight.dtype
577
+
578
+ logger.warning_once(
579
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
580
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
581
+ f" {target_dtype}."
582
+ )
583
+
584
+ query_states = query_states.to(target_dtype)
585
+ key_states = key_states.to(target_dtype)
586
+ value_states = value_states.to(target_dtype)
587
+
588
+ # Reashape to the expected shape for Flash Attention
589
+ query_states = query_states.transpose(1, 2)
590
+ key_states = key_states.transpose(1, 2)
591
+ value_states = value_states.transpose(1, 2)
592
+
593
+ attn_output = self._flash_attention_forward(
594
+ query_states,
595
+ key_states,
596
+ value_states,
597
+ attention_mask,
598
+ q_len,
599
+ dropout=attn_dropout,
600
+ use_sliding_windows=use_sliding_windows,
601
+ )
602
+
603
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
604
+ attn_output = self.o_proj(attn_output)
605
+
606
+ if not output_attentions:
607
+ attn_weights = None
608
+
609
+ return attn_output, attn_weights, past_key_value
610
+
611
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
612
+ def _flash_attention_forward(
613
+ self,
614
+ query_states,
615
+ key_states,
616
+ value_states,
617
+ attention_mask,
618
+ query_length,
619
+ dropout=0.0,
620
+ softmax_scale=None,
621
+ use_sliding_windows=False,
622
+ ):
623
+ """
624
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
625
+ first unpad the input, then computes the attention scores and pad the final attention scores.
626
+
627
+ Args:
628
+ query_states (`torch.Tensor`):
629
+ Input query states to be passed to Flash Attention API
630
+ key_states (`torch.Tensor`):
631
+ Input key states to be passed to Flash Attention API
632
+ value_states (`torch.Tensor`):
633
+ Input value states to be passed to Flash Attention API
634
+ attention_mask (`torch.Tensor`):
635
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
636
+ position of padding tokens and 1 for the position of non-padding tokens.
637
+ dropout (`float`):
638
+ Attention dropout
639
+ softmax_scale (`float`, *optional*):
640
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
641
+ use_sliding_windows (`bool`, *optional*):
642
+ Whether to activate sliding window attention.
643
+ """
644
+ if not self._flash_attn_uses_top_left_mask:
645
+ causal = self.is_causal
646
+ else:
647
+ # 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__.
648
+ causal = self.is_causal and query_length != 1
649
+
650
+ # Contains at least one padding token in the sequence
651
+ if attention_mask is not None:
652
+ batch_size = query_states.shape[0]
653
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
654
+ query_states, key_states, value_states, attention_mask, query_length
655
+ )
656
+
657
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
658
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
659
+
660
+ if not use_sliding_windows:
661
+ attn_output_unpad = flash_attn_varlen_func(
662
+ query_states,
663
+ key_states,
664
+ value_states,
665
+ cu_seqlens_q=cu_seqlens_q,
666
+ cu_seqlens_k=cu_seqlens_k,
667
+ max_seqlen_q=max_seqlen_in_batch_q,
668
+ max_seqlen_k=max_seqlen_in_batch_k,
669
+ dropout_p=dropout,
670
+ softmax_scale=softmax_scale,
671
+ causal=causal,
672
+ )
673
+ else:
674
+ attn_output_unpad = flash_attn_varlen_func(
675
+ query_states,
676
+ key_states,
677
+ value_states,
678
+ cu_seqlens_q=cu_seqlens_q,
679
+ cu_seqlens_k=cu_seqlens_k,
680
+ max_seqlen_q=max_seqlen_in_batch_q,
681
+ max_seqlen_k=max_seqlen_in_batch_k,
682
+ dropout_p=dropout,
683
+ softmax_scale=softmax_scale,
684
+ causal=causal,
685
+ window_size=(self.config.sliding_window, self.config.sliding_window),
686
+ )
687
+
688
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
689
+ else:
690
+ if not use_sliding_windows:
691
+ attn_output = flash_attn_func(
692
+ query_states,
693
+ key_states,
694
+ value_states,
695
+ dropout,
696
+ softmax_scale=softmax_scale,
697
+ causal=causal,
698
+ )
699
+ else:
700
+ attn_output = flash_attn_func(
701
+ query_states,
702
+ key_states,
703
+ value_states,
704
+ dropout,
705
+ softmax_scale=softmax_scale,
706
+ causal=causal,
707
+ window_size=(self.config.sliding_window, self.config.sliding_window),
708
+ )
709
+
710
+ return attn_output
711
+
712
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
713
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
714
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
715
+
716
+ # On the first iteration we need to properly re-create the padding mask
717
+ # by slicing it on the proper place
718
+ if kv_seq_len != attention_mask.shape[-1]:
719
+ attention_mask_num_tokens = attention_mask.shape[-1]
720
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
721
+
722
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
723
+
724
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
725
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
726
+
727
+ if query_length == kv_seq_len:
728
+ query_layer = index_first_axis(
729
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
730
+ )
731
+ cu_seqlens_q = cu_seqlens_k
732
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
733
+ indices_q = indices_k
734
+ elif query_length == 1:
735
+ max_seqlen_in_batch_q = 1
736
+ cu_seqlens_q = torch.arange(
737
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
738
+ ) # There is a memcpy here, that is very bad.
739
+ indices_q = cu_seqlens_q[:-1]
740
+ query_layer = query_layer.squeeze(1)
741
+ else:
742
+ # The -q_len: slice assumes left padding.
743
+ attention_mask = attention_mask[:, -query_length:]
744
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
745
+
746
+ return (
747
+ query_layer,
748
+ key_layer,
749
+ value_layer,
750
+ indices_q,
751
+ (cu_seqlens_q, cu_seqlens_k),
752
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
753
+ )
754
+
755
+
756
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
757
+ # TODO @Arthur no longer copied from LLama after static cache
758
+ class Phi3SdpaAttention(Phi3Attention):
759
+ """
760
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
761
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
762
+ SDPA API.
763
+ """
764
+
765
+ # Adapted from Phi3Attention.forward
766
+ def forward(
767
+ self,
768
+ hidden_states: torch.Tensor,
769
+ attention_mask: Optional[torch.Tensor] = None,
770
+ position_ids: Optional[torch.LongTensor] = None,
771
+ past_key_value: Optional[Cache] = None,
772
+ output_attentions: bool = False,
773
+ use_cache: bool = False,
774
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
775
+ if output_attentions:
776
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
777
+ logger.warning_once(
778
+ "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, "
779
+ '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.'
780
+ )
781
+ return super().forward(
782
+ hidden_states=hidden_states,
783
+ attention_mask=attention_mask,
784
+ position_ids=position_ids,
785
+ past_key_value=past_key_value,
786
+ output_attentions=output_attentions,
787
+ use_cache=use_cache,
788
+ )
789
+
790
+ bsz, q_len, _ = hidden_states.size()
791
+
792
+ qkv = self.qkv_proj(hidden_states)
793
+ query_pos = self.num_heads * self.head_dim
794
+ query_states = qkv[..., :query_pos]
795
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
796
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
797
+
798
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
799
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
800
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
801
+
802
+ kv_seq_len = key_states.shape[-2]
803
+ if past_key_value is not None:
804
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
805
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
806
+
807
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
808
+
809
+ if past_key_value is not None:
810
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
811
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
812
+
813
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
814
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
815
+
816
+ if attention_mask is not None:
817
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
818
+ raise ValueError(
819
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
820
+ )
821
+
822
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
823
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
824
+ if query_states.device.type == "cuda" and attention_mask is not None:
825
+ query_states = query_states.contiguous()
826
+ key_states = key_states.contiguous()
827
+ value_states = value_states.contiguous()
828
+
829
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
830
+ query_states,
831
+ key_states,
832
+ value_states,
833
+ attn_mask=attention_mask,
834
+ dropout_p=self.attention_dropout if self.training else 0.0,
835
+ # 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.
836
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
837
+ )
838
+
839
+ attn_output = attn_output.transpose(1, 2).contiguous()
840
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
841
+
842
+ attn_output = self.o_proj(attn_output)
843
+
844
+ return attn_output, None, past_key_value
845
+
846
+
847
+ PHI3_ATTENTION_CLASSES = {
848
+ "eager": Phi3Attention,
849
+ "flash_attention_2": Phi3FlashAttention2,
850
+ "sdpa": Phi3SdpaAttention,
851
+ }
852
+
853
+
854
+ class Phi3DecoderLayer(nn.Module):
855
+ def __init__(self, config: Phi3Config, layer_idx: int):
856
+ super().__init__()
857
+
858
+ self.config = config
859
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
860
+
861
+ self.mlp = Phi3MLP(config)
862
+ self.input_layernorm = PHI3_NORM_CLASS(config.hidden_size, eps=config.rms_norm_eps)
863
+
864
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
865
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
866
+ self.post_attention_layernorm = PHI3_NORM_CLASS(config.hidden_size, eps=config.rms_norm_eps)
867
+
868
+ def forward(
869
+ self,
870
+ hidden_states: torch.Tensor,
871
+ attention_mask: Optional[torch.Tensor] = None,
872
+ position_ids: Optional[torch.LongTensor] = None,
873
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
874
+ output_attentions: Optional[bool] = False,
875
+ use_cache: Optional[bool] = False,
876
+ **kwargs,
877
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
878
+ if "padding_mask" in kwargs:
879
+ warnings.warn(
880
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
881
+ )
882
+ """
883
+ Args:
884
+ hidden_states (`torch.FloatTensor`):
885
+ input to the layer of shape `(batch, seq_len, embed_dim)`
886
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
887
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
888
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
889
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
890
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
891
+ output_attentions (`bool`, *optional*):
892
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
893
+ returned tensors for more detail.
894
+ use_cache (`bool`, *optional*):
895
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
896
+ (see `past_key_values`).
897
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
898
+ """
899
+
900
+ residual = hidden_states
901
+
902
+ hidden_states = self.input_layernorm(hidden_states)
903
+
904
+ # Self Attention
905
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
906
+ hidden_states=hidden_states,
907
+ attention_mask=attention_mask,
908
+ position_ids=position_ids,
909
+ past_key_value=past_key_value,
910
+ output_attentions=output_attentions,
911
+ use_cache=use_cache,
912
+ )
913
+
914
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
915
+
916
+ residual = hidden_states
917
+ hidden_states = self.post_attention_layernorm(hidden_states)
918
+ hidden_states = self.mlp(hidden_states)
919
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
920
+
921
+ outputs = (hidden_states,)
922
+
923
+ if output_attentions:
924
+ outputs += (self_attn_weights,)
925
+
926
+ if use_cache:
927
+ outputs += (present_key_value,)
928
+
929
+ return outputs
930
+
931
+
932
+ PHI3_START_DOCSTRING = r"""
933
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
934
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
935
+ etc.)
936
+
937
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
938
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
939
+ and behavior.
940
+
941
+ Parameters:
942
+ config ([`Phi3Config`]):
943
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
944
+ load the weights associated with the model, only the configuration. Check out the
945
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
946
+ """
947
+
948
+
949
+ @add_start_docstrings(
950
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
951
+ PHI3_START_DOCSTRING,
952
+ )
953
+ class Phi3PreTrainedModel(PreTrainedModel):
954
+ config_class = Phi3Config
955
+ base_model_prefix = "model"
956
+ supports_gradient_checkpointing = True
957
+ _no_split_modules = ["Phi3DecoderLayer"]
958
+ _skip_keys_device_placement = "past_key_values"
959
+ _supports_flash_attn_2 = True
960
+ _supports_sdpa = False
961
+ _supports_cache_class = True
962
+
963
+ _version = "0.0.5"
964
+
965
+ def _init_weights(self, module):
966
+ std = self.config.initializer_range
967
+ if isinstance(module, nn.Linear):
968
+ module.weight.data.normal_(mean=0.0, std=std)
969
+ if module.bias is not None:
970
+ module.bias.data.zero_()
971
+ elif isinstance(module, nn.Embedding):
972
+ module.weight.data.normal_(mean=0.0, std=std)
973
+ if module.padding_idx is not None:
974
+ module.weight.data[module.padding_idx].zero_()
975
+
976
+
977
+ PHI3_INPUTS_DOCSTRING = r"""
978
+ Args:
979
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
980
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
981
+ it.
982
+
983
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
984
+ [`PreTrainedTokenizer.__call__`] for details.
985
+
986
+ [What are input IDs?](../glossary#input-ids)
987
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
988
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
989
+
990
+ - 1 for tokens that are **not masked**,
991
+ - 0 for tokens that are **masked**.
992
+
993
+ [What are attention masks?](../glossary#attention-mask)
994
+
995
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
996
+ [`PreTrainedTokenizer.__call__`] for details.
997
+
998
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
999
+ `past_key_values`).
1000
+
1001
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1002
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1003
+ information on the default strategy.
1004
+
1005
+ - 1 indicates the head is **not masked**,
1006
+ - 0 indicates the head is **masked**.
1007
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1008
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1009
+ config.n_positions - 1]`.
1010
+
1011
+ [What are position IDs?](../glossary#position-ids)
1012
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1013
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1014
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1015
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1016
+
1017
+ Two formats are allowed:
1018
+ - a [`~cache_utils.Cache`] instance;
1019
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1020
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1021
+ cache format.
1022
+
1023
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1024
+ legacy cache format will be returned.
1025
+
1026
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1027
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1028
+ of shape `(batch_size, sequence_length)`.
1029
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1030
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1031
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1032
+ model's internal embedding lookup matrix.
1033
+ use_cache (`bool`, *optional*):
1034
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1035
+ `past_key_values`).
1036
+ output_attentions (`bool`, *optional*):
1037
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1038
+ tensors for more detail.
1039
+ output_hidden_states (`bool`, *optional*):
1040
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1041
+ more detail.
1042
+ return_dict (`bool`, *optional*):
1043
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1044
+ """
1045
+
1046
+
1047
+ @add_start_docstrings(
1048
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
1049
+ PHI3_START_DOCSTRING,
1050
+ )
1051
+ class Phi3Model(Phi3PreTrainedModel):
1052
+ """
1053
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1054
+
1055
+ Args:
1056
+ config: Phi3Config
1057
+ """
1058
+
1059
+ def __init__(self, config: Phi3Config):
1060
+ super().__init__(config)
1061
+ self.padding_idx = config.pad_token_id
1062
+ self.vocab_size = config.vocab_size
1063
+
1064
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1065
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1066
+ self.layers = nn.ModuleList(
1067
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1068
+ )
1069
+ self.norm = PHI3_NORM_CLASS(config.hidden_size, eps=config.rms_norm_eps)
1070
+
1071
+ self._attn_implementation = config._attn_implementation
1072
+
1073
+ self.gradient_checkpointing = False
1074
+ # Initialize weights and apply final processing
1075
+ self.post_init()
1076
+
1077
+ def get_input_embeddings(self):
1078
+ return self.embed_tokens
1079
+
1080
+ def set_input_embeddings(self, value):
1081
+ self.embed_tokens = value
1082
+
1083
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1084
+ def forward(
1085
+ self,
1086
+ input_ids: torch.LongTensor = None,
1087
+ attention_mask: Optional[torch.Tensor] = None,
1088
+ position_ids: Optional[torch.LongTensor] = None,
1089
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1090
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1091
+ use_cache: Optional[bool] = None,
1092
+ output_attentions: Optional[bool] = None,
1093
+ output_hidden_states: Optional[bool] = None,
1094
+ return_dict: Optional[bool] = None,
1095
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1096
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1097
+ output_hidden_states = (
1098
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1099
+ )
1100
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1101
+
1102
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1103
+
1104
+ # retrieve input_ids and inputs_embeds
1105
+ if input_ids is not None and inputs_embeds is not None:
1106
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1107
+ elif input_ids is not None:
1108
+ batch_size, seq_length = input_ids.shape[:2]
1109
+ elif inputs_embeds is not None:
1110
+ batch_size, seq_length = inputs_embeds.shape[:2]
1111
+ else:
1112
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1113
+
1114
+ past_key_values_length = 0
1115
+
1116
+ if self.gradient_checkpointing and self.training:
1117
+ if use_cache:
1118
+ logger.warning_once(
1119
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1120
+ )
1121
+ use_cache = False
1122
+
1123
+ if use_cache:
1124
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1125
+ if use_legacy_cache:
1126
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1127
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1128
+
1129
+ if position_ids is None:
1130
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1131
+ position_ids = torch.arange(
1132
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1133
+ )
1134
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1135
+ else:
1136
+ position_ids = position_ids.view(-1, seq_length).long()
1137
+
1138
+ if inputs_embeds is None:
1139
+ inputs_embeds = self.embed_tokens(input_ids)
1140
+
1141
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1142
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1143
+ if is_padding_right:
1144
+ raise ValueError(
1145
+ "You are attempting to perform batched generation with padding_side='right'"
1146
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1147
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1148
+ )
1149
+
1150
+ if self._attn_implementation == "flash_attention_2":
1151
+ # 2d mask is passed through the layers
1152
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1153
+ else:
1154
+ # 4d mask is passed through the layers
1155
+ attention_mask = _prepare_4d_causal_attention_mask(
1156
+ attention_mask,
1157
+ (batch_size, seq_length),
1158
+ inputs_embeds,
1159
+ past_key_values_length,
1160
+ sliding_window=self.config.sliding_window,
1161
+ )
1162
+
1163
+ hidden_states = inputs_embeds
1164
+
1165
+ # decoder layers
1166
+ all_hidden_states = () if output_hidden_states else None
1167
+ all_self_attns = () if output_attentions else None
1168
+ next_decoder_cache = None
1169
+
1170
+ for decoder_layer in self.layers:
1171
+ if output_hidden_states:
1172
+ all_hidden_states += (hidden_states,)
1173
+
1174
+ if self.gradient_checkpointing and self.training:
1175
+ layer_outputs = self._gradient_checkpointing_func(
1176
+ decoder_layer.__call__,
1177
+ hidden_states,
1178
+ attention_mask,
1179
+ position_ids,
1180
+ past_key_values,
1181
+ output_attentions,
1182
+ use_cache,
1183
+ )
1184
+ else:
1185
+ layer_outputs = decoder_layer(
1186
+ hidden_states,
1187
+ attention_mask=attention_mask,
1188
+ position_ids=position_ids,
1189
+ past_key_value=past_key_values,
1190
+ output_attentions=output_attentions,
1191
+ use_cache=use_cache,
1192
+ )
1193
+
1194
+ hidden_states = layer_outputs[0]
1195
+
1196
+ if use_cache:
1197
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1198
+
1199
+ if output_attentions:
1200
+ all_self_attns += (layer_outputs[1],)
1201
+
1202
+ hidden_states = self.norm(hidden_states)
1203
+
1204
+ # add hidden states from the last decoder layer
1205
+ if output_hidden_states:
1206
+ all_hidden_states += (hidden_states,)
1207
+
1208
+ next_cache = None
1209
+ if use_cache:
1210
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1211
+ if not return_dict:
1212
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1213
+ return BaseModelOutputWithPast(
1214
+ last_hidden_state=hidden_states,
1215
+ past_key_values=next_cache,
1216
+ hidden_states=all_hidden_states,
1217
+ attentions=all_self_attns,
1218
+ )
1219
+
1220
+
1221
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1222
+ _tied_weights_keys = ["lm_head.weight"]
1223
+
1224
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1225
+ def __init__(self, config):
1226
+ super().__init__(config)
1227
+ self.model = Phi3Model(config)
1228
+ self.vocab_size = config.vocab_size
1229
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1230
+
1231
+ # Initialize weights and apply final processing
1232
+ self.post_init()
1233
+
1234
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1235
+ def get_input_embeddings(self):
1236
+ return self.model.embed_tokens
1237
+
1238
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1239
+ def set_input_embeddings(self, value):
1240
+ self.model.embed_tokens = value
1241
+
1242
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1243
+ def get_output_embeddings(self):
1244
+ return self.lm_head
1245
+
1246
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1247
+ def set_output_embeddings(self, new_embeddings):
1248
+ self.lm_head = new_embeddings
1249
+
1250
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1251
+ def set_decoder(self, decoder):
1252
+ self.model = decoder
1253
+
1254
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1255
+ def get_decoder(self):
1256
+ return self.model
1257
+
1258
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1259
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1260
+ def forward(
1261
+ self,
1262
+ input_ids: torch.LongTensor = None,
1263
+ attention_mask: Optional[torch.Tensor] = None,
1264
+ position_ids: Optional[torch.LongTensor] = None,
1265
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1266
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1267
+ labels: Optional[torch.LongTensor] = None,
1268
+ use_cache: Optional[bool] = None,
1269
+ output_attentions: Optional[bool] = None,
1270
+ output_hidden_states: Optional[bool] = None,
1271
+ return_dict: Optional[bool] = None,
1272
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1273
+ r"""
1274
+ Args:
1275
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1276
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1277
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1278
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1279
+
1280
+ Returns:
1281
+
1282
+ Example:
1283
+
1284
+ ```python
1285
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1286
+
1287
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3")
1288
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3")
1289
+
1290
+ >>> prompt = "This is an example script ."
1291
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1292
+
1293
+ >>> # Generate
1294
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1295
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1296
+ 'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
1297
+ ```"""
1298
+
1299
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1300
+ output_hidden_states = (
1301
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1302
+ )
1303
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1304
+
1305
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1306
+ outputs = self.model(
1307
+ input_ids=input_ids,
1308
+ attention_mask=attention_mask,
1309
+ position_ids=position_ids,
1310
+ past_key_values=past_key_values,
1311
+ inputs_embeds=inputs_embeds,
1312
+ use_cache=use_cache,
1313
+ output_attentions=output_attentions,
1314
+ output_hidden_states=output_hidden_states,
1315
+ return_dict=return_dict,
1316
+ )
1317
+
1318
+ hidden_states = outputs[0]
1319
+ logits = self.lm_head(hidden_states)
1320
+ logits = logits.float()
1321
+
1322
+ loss = None
1323
+ if labels is not None:
1324
+ # Shift so that tokens < n predict n
1325
+ shift_logits = logits[..., :-1, :].contiguous()
1326
+ shift_labels = labels[..., 1:].contiguous()
1327
+ # Flatten the tokens
1328
+ loss_fct = CrossEntropyLoss()
1329
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1330
+ shift_labels = shift_labels.view(-1)
1331
+ # Enable model parallelism
1332
+ shift_labels = shift_labels.to(shift_logits.device)
1333
+ loss = loss_fct(shift_logits, shift_labels)
1334
+
1335
+ if not return_dict:
1336
+ output = (logits,) + outputs[1:]
1337
+ return (loss,) + output if loss is not None else output
1338
+
1339
+ return CausalLMOutputWithPast(
1340
+ loss=loss,
1341
+ logits=logits,
1342
+ past_key_values=outputs.past_key_values,
1343
+ hidden_states=outputs.hidden_states,
1344
+ attentions=outputs.attentions,
1345
+ )
1346
+
1347
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1348
+ def prepare_inputs_for_generation(
1349
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1350
+ ):
1351
+ if past_key_values is not None:
1352
+ if isinstance(past_key_values, Cache):
1353
+ cache_length = past_key_values.get_seq_length()
1354
+ past_length = past_key_values.seen_tokens
1355
+ max_cache_length = past_key_values.get_max_length()
1356
+ else:
1357
+ cache_length = past_length = past_key_values[0][0].shape[2]
1358
+ max_cache_length = None
1359
+
1360
+ # Keep only the unprocessed tokens:
1361
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1362
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1363
+ # input)
1364
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1365
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1366
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1367
+ # input_ids based on the past_length.
1368
+ elif past_length < input_ids.shape[1]:
1369
+ input_ids = input_ids[:, past_length:]
1370
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1371
+
1372
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1373
+ if (
1374
+ max_cache_length is not None
1375
+ and attention_mask is not None
1376
+ and cache_length + input_ids.shape[1] > max_cache_length
1377
+ ):
1378
+ attention_mask = attention_mask[:, -max_cache_length:]
1379
+
1380
+ position_ids = kwargs.get("position_ids", None)
1381
+ if attention_mask is not None and position_ids is None:
1382
+ # create position_ids on the fly for batch generation
1383
+ position_ids = attention_mask.long().cumsum(-1) - 1
1384
+ position_ids.masked_fill_(attention_mask == 0, 1)
1385
+ if past_key_values:
1386
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1387
+
1388
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1389
+ if inputs_embeds is not None and past_key_values is None:
1390
+ model_inputs = {"inputs_embeds": inputs_embeds}
1391
+ else:
1392
+ model_inputs = {"input_ids": input_ids}
1393
+
1394
+ model_inputs.update(
1395
+ {
1396
+ "position_ids": position_ids,
1397
+ "past_key_values": past_key_values,
1398
+ "use_cache": kwargs.get("use_cache"),
1399
+ "attention_mask": attention_mask,
1400
+ }
1401
+ )
1402
+ return model_inputs
1403
+
1404
+ @staticmethod
1405
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1406
+ def _reorder_cache(past_key_values, beam_idx):
1407
+ reordered_past = ()
1408
+ for layer_past in past_key_values:
1409
+ reordered_past += (
1410
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1411
+ )
1412
+ return reordered_past
1413
+
1414
+
1415
+ @add_start_docstrings(
1416
+ """
1417
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1418
+
1419
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1420
+ (e.g. GPT-2) do.
1421
+
1422
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1423
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1424
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1425
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1426
+ each row of the batch).
1427
+ """,
1428
+ PHI3_START_DOCSTRING,
1429
+ )
1430
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1431
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1432
+ def __init__(self, config):
1433
+ super().__init__(config)
1434
+ self.num_labels = config.num_labels
1435
+ self.model = Phi3Model(config)
1436
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1437
+
1438
+ # Initialize weights and apply final processing
1439
+ self.post_init()
1440
+
1441
+ def get_input_embeddings(self):
1442
+ return self.model.embed_tokens
1443
+
1444
+ def set_input_embeddings(self, value):
1445
+ self.model.embed_tokens = value
1446
+
1447
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1448
+ def forward(
1449
+ self,
1450
+ input_ids: torch.LongTensor = None,
1451
+ attention_mask: Optional[torch.Tensor] = None,
1452
+ position_ids: Optional[torch.LongTensor] = None,
1453
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1454
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1455
+ labels: Optional[torch.LongTensor] = None,
1456
+ use_cache: Optional[bool] = None,
1457
+ output_attentions: Optional[bool] = None,
1458
+ output_hidden_states: Optional[bool] = None,
1459
+ return_dict: Optional[bool] = None,
1460
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1461
+ r"""
1462
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1463
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1464
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1465
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1466
+ """
1467
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1468
+
1469
+ model_outputs = self.model(
1470
+ input_ids,
1471
+ attention_mask=attention_mask,
1472
+ position_ids=position_ids,
1473
+ past_key_values=past_key_values,
1474
+ inputs_embeds=inputs_embeds,
1475
+ use_cache=use_cache,
1476
+ output_attentions=output_attentions,
1477
+ output_hidden_states=output_hidden_states,
1478
+ return_dict=return_dict,
1479
+ )
1480
+ hidden_states = model_outputs[0]
1481
+ logits = self.score(hidden_states)
1482
+
1483
+ if input_ids is not None:
1484
+ batch_size = input_ids.shape[0]
1485
+ else:
1486
+ batch_size = inputs_embeds.shape[0]
1487
+
1488
+ if self.config.pad_token_id is None and batch_size != 1:
1489
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1490
+ if self.config.pad_token_id is None:
1491
+ sequence_lengths = -1
1492
+ else:
1493
+ if input_ids is not None:
1494
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1495
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1496
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1497
+ sequence_lengths = sequence_lengths.to(logits.device)
1498
+ else:
1499
+ sequence_lengths = -1
1500
+
1501
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1502
+
1503
+ loss = None
1504
+ if labels is not None:
1505
+ labels = labels.to(logits.device)
1506
+ if self.config.problem_type is None:
1507
+ if self.num_labels == 1:
1508
+ self.config.problem_type = "regression"
1509
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1510
+ self.config.problem_type = "single_label_classification"
1511
+ else:
1512
+ self.config.problem_type = "multi_label_classification"
1513
+
1514
+ if self.config.problem_type == "regression":
1515
+ loss_fct = MSELoss()
1516
+ if self.num_labels == 1:
1517
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1518
+ else:
1519
+ loss = loss_fct(pooled_logits, labels)
1520
+ elif self.config.problem_type == "single_label_classification":
1521
+ loss_fct = CrossEntropyLoss()
1522
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1523
+ elif self.config.problem_type == "multi_label_classification":
1524
+ loss_fct = BCEWithLogitsLoss()
1525
+ loss = loss_fct(pooled_logits, labels)
1526
+ if not return_dict:
1527
+ output = (pooled_logits,) + model_outputs[1:]
1528
+ return ((loss,) + output) if loss is not None else output
1529
+
1530
+ return SequenceClassifierOutputWithPast(
1531
+ loss=loss,
1532
+ logits=pooled_logits,
1533
+ past_key_values=model_outputs.past_key_values,
1534
+ hidden_states=model_outputs.hidden_states,
1535
+ attentions=model_outputs.attentions,
1536
+ )
1537
+
1538
+
1539
+ @add_start_docstrings(
1540
+ """
1541
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1542
+ Named-Entity-Recognition (NER) tasks.
1543
+ """,
1544
+ PHI3_START_DOCSTRING,
1545
+ )
1546
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1547
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1548
+ def __init__(self, config: Phi3Config):
1549
+ super().__init__(config)
1550
+ self.num_labels = config.num_labels
1551
+
1552
+ self.model = Phi3Model(config)
1553
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1554
+ classifier_dropout = config.classifier_dropout
1555
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1556
+ classifier_dropout = config.hidden_dropout
1557
+ else:
1558
+ classifier_dropout = 0.1
1559
+ self.dropout = nn.Dropout(classifier_dropout)
1560
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1561
+
1562
+ # Initialize weights and apply final processing
1563
+ self.post_init()
1564
+
1565
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1566
+ @add_code_sample_docstrings(
1567
+ checkpoint=_CHECKPOINT_FOR_DOC,
1568
+ output_type=TokenClassifierOutput,
1569
+ config_class=_CONFIG_FOR_DOC,
1570
+ )
1571
+ def forward(
1572
+ self,
1573
+ input_ids: Optional[torch.LongTensor] = None,
1574
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1575
+ attention_mask: Optional[torch.Tensor] = None,
1576
+ inputs_embeds: Optional[torch.Tensor] = None,
1577
+ labels: Optional[torch.Tensor] = None,
1578
+ use_cache: Optional[bool] = None,
1579
+ output_attentions: Optional[bool] = None,
1580
+ output_hidden_states: Optional[bool] = None,
1581
+ return_dict: Optional[bool] = None,
1582
+ **deprecated_arguments,
1583
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1584
+ r"""
1585
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1586
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1587
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1588
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1589
+ """
1590
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1591
+
1592
+ model_outputs = self.model(
1593
+ input_ids,
1594
+ past_key_values=past_key_values,
1595
+ attention_mask=attention_mask,
1596
+ inputs_embeds=inputs_embeds,
1597
+ use_cache=use_cache,
1598
+ output_attentions=output_attentions,
1599
+ output_hidden_states=output_hidden_states,
1600
+ return_dict=return_dict,
1601
+ )
1602
+
1603
+ hidden_states = model_outputs[0]
1604
+ hidden_states = self.dropout(hidden_states)
1605
+ logits = self.classifier(hidden_states)
1606
+
1607
+ loss = None
1608
+ if labels is not None:
1609
+ # move labels to correct device to enable model parallelism
1610
+ labels = labels.to(logits.device)
1611
+ batch_size, seq_length = labels.shape
1612
+ loss_fct = CrossEntropyLoss()
1613
+ loss = loss_fct(
1614
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1615
+ )
1616
+
1617
+ if not return_dict:
1618
+ output = (logits,) + model_outputs[2:]
1619
+ return ((loss,) + output) if loss is not None else output
1620
+
1621
+ return TokenClassifierOutput(
1622
+ loss=loss,
1623
+ logits=logits,
1624
+ hidden_states=model_outputs.hidden_states,
1625
+ attentions=model_outputs.attentions,
1626
+ )
sample_finetune.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from datasets import load_dataset
3
+ from trl import SFTTrainer
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments
5
+
6
+ """
7
+ A simple example on using SFTTrainer and Accelerate to finetune Phi-3 models. For
8
+ a more advanced example, please follow HF alignment-handbook/scripts/run_sft.py
9
+
10
+ 1. Install accelerate:
11
+ conda install -c conda-forge accelerate
12
+ 2. Setup accelerate config:
13
+ accelerate config
14
+ to simply use all the GPUs available:
15
+ python -c "from accelerate.utils import write_basic_config; write_basic_config(mixed_precision='bf16')"
16
+ check accelerate config:
17
+ accelerate env
18
+ 3. Run the code:
19
+ accelerate launch sample_finetune.py
20
+ """
21
+
22
+ ###################
23
+ # Hyper-parameters
24
+ ###################
25
+ args = {
26
+ "bf16": True,
27
+ "do_eval": False,
28
+ "eval_strategy": "no",
29
+ "learning_rate": 5.0e-06,
30
+ "log_level": "info",
31
+ "logging_steps": 20,
32
+ "logging_strategy": "steps",
33
+ "lr_scheduler_type": "cosine",
34
+ "num_train_epochs": 1,
35
+ "max_steps": -1,
36
+ "output_dir": "./checkpoint_dir",
37
+ "overwrite_output_dir": True,
38
+ "per_device_eval_batch_size": 4,
39
+ "per_device_train_batch_size": 8,
40
+ "remove_unused_columns": True,
41
+ "save_steps": 100,
42
+ "save_total_limit": 1,
43
+ "seed": 0,
44
+ "gradient_checkpointing": True,
45
+ "gradient_checkpointing_kwargs":{"use_reentrant": False},
46
+ "gradient_accumulation_steps": 1,
47
+ "warmup_ratio": 0.2,
48
+ }
49
+
50
+ training_args = TrainingArguments(**args)
51
+
52
+ ################
53
+ # Modle Loading
54
+ ################
55
+ checkpoint_path = "microsoft/Phi-3-mini-4k-instruct"
56
+ # checkpoint_path = "microsoft/Phi-3-mini-128k-instruct"
57
+ model_kwargs = dict(
58
+ use_cache=False,
59
+ trust_remote_code=True,
60
+ attn_implementation="flash_attention_2", # loading the model with flash-attenstion support
61
+ torch_dtype=torch.bfloat16,
62
+ device_map="cuda",
63
+ )
64
+ model = AutoModelForCausalLM.from_pretrained(checkpoint_path, **model_kwargs)
65
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
66
+ tokenizer.pad_token = tokenizer.unk_token # use unk rather than eos token to prevent endless generation
67
+ tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token)
68
+ tokenizer.padding_side = 'right'
69
+
70
+ ##################
71
+ # Data Processing
72
+ ##################
73
+ def apply_chat_template(
74
+ example,
75
+ tokenizer,
76
+ ):
77
+ messages = example["messages"]
78
+ # Add an empty system message if there is none
79
+ if messages[0]["role"] != "system":
80
+ messages.insert(0, {"role": "system", "content": ""})
81
+ example["text"] = tokenizer.apply_chat_template(
82
+ messages, tokenize=False, add_generation_prompt=False)
83
+ return example
84
+
85
+ raw_dataset = load_dataset("HuggingFaceH4/ultrachat_200k")
86
+ column_names = list(raw_dataset["train_sft"].features)
87
+
88
+ processed_dataset = raw_dataset.map(
89
+ apply_chat_template,
90
+ fn_kwargs={"tokenizer": tokenizer},
91
+ num_proc=12,
92
+ remove_columns=column_names,
93
+ desc="Applying chat template",
94
+ )
95
+ train_dataset = processed_dataset["train_sft"]
96
+ eval_dataset = processed_dataset["test_sft"]
97
+
98
+ ###########
99
+ # Training
100
+ ###########
101
+ trainer = SFTTrainer(
102
+ model=model,
103
+ args=training_args,
104
+ train_dataset=train_dataset,
105
+ eval_dataset=eval_dataset,
106
+ max_seq_length=2048,
107
+ dataset_text_field="text",
108
+ tokenizer=tokenizer,
109
+ packing=True
110
+ )
111
+ train_result = trainer.train()
112
+ metrics = train_result.metrics
113
+ trainer.log_metrics("train", metrics)
114
+ trainer.save_metrics("train", metrics)
115
+ trainer.save_state()
116
+
117
+ #############
118
+ # Evaluation
119
+ #############
120
+ tokenizer.padding_side = 'left'
121
+ metrics = trainer.evaluate()
122
+ metrics["eval_samples"] = len(eval_dataset)
123
+ trainer.log_metrics("eval", metrics)
124
+ trainer.save_metrics("eval", metrics)
125
+
126
+ ############
127
+ # Save model
128
+ ############
129
+ trainer.save_model(training_args.output_dir)
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.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": true,
26
+ "single_word": false,
27
+ "special": false
28
+ },
29
+ "32000": {
30
+ "content": "<|endoftext|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "32001": {
38
+ "content": "<|assistant|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": true,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "32002": {
46
+ "content": "<|step|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": true,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "32003": {
54
+ "content": "<|function_output|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": true,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "32004": {
62
+ "content": "<|tag|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": true,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "32005": {
70
+ "content": "<|function_call|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": true,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "32006": {
78
+ "content": "<|system|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": true,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "32007": {
86
+ "content": "<|end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": true,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "32008": {
94
+ "content": "<|raw|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": true,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "32009": {
102
+ "content": "<|continue|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": true,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "32010": {
110
+ "content": "<|user|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": true,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "32011": {
118
+ "content": "<|function_list|>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": true,
122
+ "single_word": false,
123
+ "special": true
124
+ },
125
+ "32012": {
126
+ "content": "<|calc|>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": true,
130
+ "single_word": false,
131
+ "special": true
132
+ },
133
+ "32013": {
134
+ "content": "<|code|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": true,
138
+ "single_word": false,
139
+ "special": true
140
+ },
141
+ "32014": {
142
+ "content": "<|/code|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": true,
146
+ "single_word": false,
147
+ "special": true
148
+ },
149
+ "32015": {
150
+ "content": "<|summary|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": true,
154
+ "single_word": false,
155
+ "special": true
156
+ },
157
+ "32016": {
158
+ "content": "<|resource|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": true,
162
+ "single_word": false,
163
+ "special": true
164
+ },
165
+ "32017": {
166
+ "content": "<|assistant_mask|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": true,
170
+ "single_word": false,
171
+ "special": true
172
+ },
173
+ "32018": {
174
+ "content": "<|start|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": true,
178
+ "single_word": false,
179
+ "special": true
180
+ },
181
+ "32019": {
182
+ "content": "<|message|>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": true,
186
+ "single_word": false,
187
+ "special": true
188
+ },
189
+ "32020": {
190
+ "content": "<|fim_prefix|>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": true,
194
+ "single_word": false,
195
+ "special": true
196
+ },
197
+ "32021": {
198
+ "content": "<|fim_middle|>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": true,
202
+ "single_word": false,
203
+ "special": true
204
+ },
205
+ "32022": {
206
+ "content": "<|fim_suffix|>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": true,
210
+ "single_word": false,
211
+ "special": true
212
+ },
213
+ "32023": {
214
+ "content": "<|meta_start|>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": true,
218
+ "single_word": false,
219
+ "special": true
220
+ },
221
+ "32024": {
222
+ "content": "<|ipynb_marker|>",
223
+ "lstrip": false,
224
+ "normalized": false,
225
+ "rstrip": true,
226
+ "single_word": false,
227
+ "special": true
228
+ },
229
+ "32025": {
230
+ "content": "<|diff_marker|>",
231
+ "lstrip": false,
232
+ "normalized": false,
233
+ "rstrip": true,
234
+ "single_word": false,
235
+ "special": true
236
+ },
237
+ "32026": {
238
+ "content": "<|ghissue|>",
239
+ "lstrip": false,
240
+ "normalized": false,
241
+ "rstrip": true,
242
+ "single_word": false,
243
+ "special": true
244
+ },
245
+ "32027": {
246
+ "content": "<|ghreview|>",
247
+ "lstrip": false,
248
+ "normalized": false,
249
+ "rstrip": true,
250
+ "single_word": false,
251
+ "special": true
252
+ },
253
+ "32028": {
254
+ "content": "<|disc_start|>",
255
+ "lstrip": false,
256
+ "normalized": false,
257
+ "rstrip": true,
258
+ "single_word": false,
259
+ "special": true
260
+ },
261
+ "32029": {
262
+ "content": "<|disc_sep|>",
263
+ "lstrip": false,
264
+ "normalized": false,
265
+ "rstrip": true,
266
+ "single_word": false,
267
+ "special": true
268
+ },
269
+ "32030": {
270
+ "content": "<|disc_thread|><|query|>",
271
+ "lstrip": false,
272
+ "normalized": false,
273
+ "rstrip": true,
274
+ "single_word": false,
275
+ "special": true
276
+ },
277
+ "32031": {
278
+ "content": "<|/query|>",
279
+ "lstrip": false,
280
+ "normalized": false,
281
+ "rstrip": true,
282
+ "single_word": false,
283
+ "special": true
284
+ },
285
+ "32032": {
286
+ "content": "<|data|>",
287
+ "lstrip": false,
288
+ "normalized": false,
289
+ "rstrip": true,
290
+ "single_word": false,
291
+ "special": true
292
+ },
293
+ "32033": {
294
+ "content": "<|/data|>",
295
+ "lstrip": false,
296
+ "normalized": false,
297
+ "rstrip": true,
298
+ "single_word": false,
299
+ "special": true
300
+ },
301
+ "32034": {
302
+ "content": "<|sys|>",
303
+ "lstrip": false,
304
+ "normalized": false,
305
+ "rstrip": true,
306
+ "single_word": false,
307
+ "special": true
308
+ },
309
+ "32035": {
310
+ "content": "<|/sys|>",
311
+ "lstrip": false,
312
+ "normalized": false,
313
+ "rstrip": true,
314
+ "single_word": false,
315
+ "special": true
316
+ },
317
+ "32036": {
318
+ "content": "<|inst|>",
319
+ "lstrip": false,
320
+ "normalized": false,
321
+ "rstrip": true,
322
+ "single_word": false,
323
+ "special": true
324
+ },
325
+ "32037": {
326
+ "content": "<|/inst|>",
327
+ "lstrip": false,
328
+ "normalized": false,
329
+ "rstrip": true,
330
+ "single_word": false,
331
+ "special": true
332
+ }
333
+ },
334
+ "additional_special_tokens": [
335
+ "<|/inst|>"
336
+ ],
337
+ "bos_token": "<s>",
338
+ "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 %}",
339
+ "clean_up_tokenization_spaces": false,
340
+ "eos_token": "<|endoftext|>",
341
+ "legacy": false,
342
+ "model_max_length": 4096,
343
+ "pad_token": "<|endoftext|>",
344
+ "padding_side": "left",
345
+ "sp_model_kwargs": {},
346
+ "tokenizer_class": "LlamaTokenizer",
347
+ "unk_token": "<unk>",
348
+ "use_default_system_prompt": false
349
+ }