Update README.md
#3
by
wwwaj
- opened
- CODE_OF_CONDUCT.md +9 -0
- LICENSE +22 -0
- NOTICE.md +38 -0
- README.md +240 -0
- SECURITY.md +41 -0
- added_tokens.json +40 -0
- config.json +35 -0
- configuration_phi3.py +193 -0
- generation_config.json +10 -0
- model-00001-of-00002.safetensors +3 -0
- model-00002-of-00002.safetensors +3 -0
- model.safetensors.index.json +202 -0
- modeling_phi3.py +1636 -0
- sample_finetune.py +93 -0
- special_tokens_map.json +33 -0
- tokenizer.json +0 -0
- tokenizer.model +3 -0
- tokenizer_config.json +349 -0
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,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
Phi-3 Mini-4K-Instruct is a 3.8B parameters, lightweight, state-of-the-art open model built upon datasets used for Phi-2 - synthetic data and filtered websites - with a focus on very high-quality, reasoning dense data. The model belongs to the Phi-3 model family, and the Mini version comes 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) it can support.
|
16 |
+
|
17 |
+
The model underwent a rigorous enhancement process, incorporating both supervised fine-tuning and direct preference optimization to ensure precise instruction adherence and robust 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 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. You can provide the prompt as a question:
|
59 |
+
|
60 |
+
```markdown
|
61 |
+
<|system|>
|
62 |
+
You are a helpful AI assistant.
|
63 |
+
<|end|>
|
64 |
+
<|user|>
|
65 |
+
How to explain Internet for a medieval knight?
|
66 |
+
<|end|>
|
67 |
+
<|assistant|>
|
68 |
+
```
|
69 |
+
|
70 |
+
where the model generates the text after `<|assistant|>` . In case of few-shots prompt, the prompt can be formatted as the following:
|
71 |
+
|
72 |
+
```markdown
|
73 |
+
<|system|>
|
74 |
+
You are a helpful AI assistant.
|
75 |
+
<|end|>
|
76 |
+
<|user|>
|
77 |
+
I am going to Paris, what should I see?
|
78 |
+
<|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."
|
81 |
+
<|end|>
|
82 |
+
<|user|>
|
83 |
+
What is so great about #1?
|
84 |
+
<|assistant|>
|
85 |
+
```
|
86 |
+
|
87 |
+
### Sample inference code
|
88 |
+
|
89 |
+
This code snippets show how to get quickly started with running the model on a GPU:
|
90 |
+
|
91 |
+
```python
|
92 |
+
import torch
|
93 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
94 |
+
|
95 |
+
torch.random.manual_seed(0)
|
96 |
+
|
97 |
+
model = AutoModelForCausalLM.from_pretrained(
|
98 |
+
"microsoft/Phi-3-mini-4k-instruct",
|
99 |
+
device_map="cuda",
|
100 |
+
torch_dtype="auto",
|
101 |
+
trust_remote_code=True,
|
102 |
+
)
|
103 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
|
104 |
+
|
105 |
+
messages = [
|
106 |
+
{"role": "system", "content": "You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user."},
|
107 |
+
{"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
|
108 |
+
{"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."},
|
109 |
+
{"role": "user", "content": "What about solving an 2x + 3 = 7 equation?"},
|
110 |
+
]
|
111 |
+
|
112 |
+
pipe = pipeline(
|
113 |
+
"text-generation",
|
114 |
+
model=model,
|
115 |
+
tokenizer=tokenizer,
|
116 |
+
)
|
117 |
+
|
118 |
+
generation_args = {
|
119 |
+
"max_new_tokens": 500,
|
120 |
+
"return_full_text": False,
|
121 |
+
"temperature": 0.0,
|
122 |
+
"do_sample": False,
|
123 |
+
}
|
124 |
+
|
125 |
+
output = pipe(messages, **generation_args)
|
126 |
+
print(output[0]['generated_text'])
|
127 |
+
```
|
128 |
+
|
129 |
+
Note that by default the model use flash attention which requires certain types of GPU to run. If you want to run the model on:
|
130 |
+
|
131 |
+
+ V100 or earlier generation GPUs: call `AutoModelForCausalLM.from_pretrained()` with `attn_implementation="eager"`
|
132 |
+
+ CPU: use the **GGUF** quantized models [4K](https://aka.ms/Phi3-mini-4k-instruct-gguf)
|
133 |
+
+ Optimized inference on GPU, CPU, and Mobile: use the **ONNX** models [4K](https://aka.ms/Phi3-mini-4k-instruct-onnx)
|
134 |
+
|
135 |
+
## Responsible AI Considerations
|
136 |
+
|
137 |
+
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:
|
138 |
+
|
139 |
+
+ 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.
|
140 |
+
+ 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.
|
141 |
+
+ 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.
|
142 |
+
+ Information Reliability: Language models can generate nonsensical content or fabricate content that might sound reasonable but is inaccurate or outdated.
|
143 |
+
+ 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.
|
144 |
+
|
145 |
+
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:
|
146 |
+
|
147 |
+
+ 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.
|
148 |
+
+ 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.
|
149 |
+
+ 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).
|
150 |
+
+ Generation of Harmful Content: Developers should assess outputs for their context and use available safety classifiers or custom solutions appropriate for their use case.
|
151 |
+
+ 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.
|
152 |
+
|
153 |
+
|
154 |
+
## Training
|
155 |
+
|
156 |
+
### Model
|
157 |
+
|
158 |
+
* 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.
|
159 |
+
* Inputs: Text. It is best suited for prompts using chat format.
|
160 |
+
* Context length: 4K tokens
|
161 |
+
* GPUs: 512 H100-80G
|
162 |
+
* Training time: 7 days
|
163 |
+
* Training data: 3.3T tokens
|
164 |
+
* Outputs: Generated text in response to the input
|
165 |
+
* Dates: Our models were trained between February and April 2024
|
166 |
+
* 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.
|
167 |
+
|
168 |
+
### Datasets
|
169 |
+
|
170 |
+
Our training data includes a wide variety of sources, totaling 3.3 trillion tokens, and is a combination of
|
171 |
+
1) Publicly available documents filtered rigorously for quality, selected high-quality educational data, and code;
|
172 |
+
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.);
|
173 |
+
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.
|
174 |
+
|
175 |
+
### Fine-tuning
|
176 |
+
|
177 |
+
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).
|
178 |
+
|
179 |
+
## Benchmarks
|
180 |
+
|
181 |
+
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.
|
182 |
+
|
183 |
+
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.
|
184 |
+
|
185 |
+
As is now standard, we use few-shot prompts to evaluate the models, at temperature 0.
|
186 |
+
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.
|
187 |
+
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.
|
188 |
+
|
189 |
+
The number of k–shot examples is listed per-benchmark.
|
190 |
+
|
191 |
+
| | 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 |
|
192 |
+
|---|---|---|---|---|---|---|---|---|---|
|
193 |
+
| MMLU <br>5-Shot | 68.8 | 75.3 | 78.2 | 56.3 | 61.7 | 63.6 | 66.0 | 68.4 | 71.4 |
|
194 |
+
| HellaSwag <br> 5-Shot | 76.7 | 78.7 | 83.2 | 53.6 | 58.5 | 49.8 | 69.5 | 70.4 | 78.8 |
|
195 |
+
| ANLI <br> 7-Shot | 52.8 | 55.0 | 58.7 | 42.5 | 47.1 | 48.7 | 54.8 | 55.2 | 58.1 |
|
196 |
+
| GSM-8K <br> 0-Shot; CoT | 82.5 | 86.4 | 90.8 | 61.1 | 46.4 | 59.8 | 77.4 | 64.7 | 78.1 |
|
197 |
+
| MedQA <br> 2-Shot | 53.8 | 58.2 | 69.8 | 40.9 | 49.6 | 50.0 | 58.9 | 62.2 | 63.4 |
|
198 |
+
| AGIEval <br> 0-Shot | 37.5 | 45.0 | 49.7 | 29.8 | 35.1 | 42.1 | 42.0 | 45.2 | 48.4 |
|
199 |
+
| TriviaQA <br> 5-Shot | 64.0 | 59.1 | 73.3 | 45.2 | 72.3 | 75.2 | 73.6 | 82.2 | 85.8 |
|
200 |
+
| Arc-C <br> 10-Shot | 84.9 | 90.7 | 91.9 | 75.9 | 78.6 | 78.3 | 80.5 | 87.3 | 87.4 |
|
201 |
+
| Arc-E <br> 10-Shot | 94.6 | 97.1 | 98.0 | 88.5 | 90.6 | 91.4 | 92.3 | 95.6 | 96.3 |
|
202 |
+
| PIQA <br> 5-Shot | 84.2 | 87.8 | 88.2 | 60.2 | 77.7 | 78.1 | 77.1 | 86.0 | 86.6 |
|
203 |
+
| SociQA <br> 5-Shot | 76.6 | 79.0 | 79.4 | 68.3 | 74.6 | 65.5 | 73.2 | 75.9 | 68.3 |
|
204 |
+
| BigBench-Hard <br> 0-Shot | 71.7 | 75.0 | 82.5 | 59.4 | 57.3 | 59.6 | 68.9 | 69.7 | 68.32 |
|
205 |
+
| WinoGrande <br> 5-Shot | 70.8 | 82.5 | 81.2 | 54.7 | 54.2 | 55.6 | 58.0 | 62.0 | 68.8 |
|
206 |
+
| OpenBookQA <br> 10-Shot | 83.2 | 88.4 | 86.6 | 73.6 | 79.8 | 78.6 | 81.6 | 85.8 | 86.0 |
|
207 |
+
| BoolQ <br> 0-Shot | 77.2 | 82.9 | 86.5 | -- | 72.2 | 66.0 | 78.3 | 77.6 | 79.1 |
|
208 |
+
| CommonSenseQA <br> 10-Shot | 80.2 | 80.3 | 82.6 | 69.3 | 72.6 | 76.2 | 73.6 | 78.1 | 79.6 |
|
209 |
+
| TruthfulQA <br> 10-Shot | 65.0 | 68.1 | 74.8 | -- | 52.1 | 53.0 | 62.0 | 60.1 | 85.8 |
|
210 |
+
| HumanEval <br> 0-Shot | 58.5 | 59.1 | 54.7 | 59.0 | 28.0 | 34.1 | 38.4 | 37.8 | 62.2 |
|
211 |
+
| MBPP <br> 3-Shot | 70.0 | 71.4 | 73.7 | 60.6 | 50.8 | 51.5 | 65.3 | 60.2 | 77.8 |
|
212 |
+
|
213 |
+
## Software
|
214 |
+
|
215 |
+
* [PyTorch](https://github.com/pytorch/pytorch)
|
216 |
+
* [DeepSpeed](https://github.com/microsoft/DeepSpeed)
|
217 |
+
* [Transformers](https://github.com/huggingface/transformers)
|
218 |
+
* [Flash-Attention](https://github.com/HazyResearch/flash-attention)
|
219 |
+
|
220 |
+
## Cross Platform Support
|
221 |
+
|
222 |
+
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).
|
223 |
+
|
224 |
+
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.
|
225 |
+
Along with DirectML, ONNX Runtime provides cross platform support for Phi-3 across a range of devices CPU, GPU, and mobile.
|
226 |
+
|
227 |
+
Here are some of the optimized configurations we have added:
|
228 |
+
|
229 |
+
1. ONNX models for int4 DML: Quantized to int4 via AWQ
|
230 |
+
2. ONNX model for fp16 CUDA
|
231 |
+
3. ONNX model for int4 CUDA: Quantized to int4 via RTN
|
232 |
+
4. ONNX model for int4 CPU and Mobile: Quantized to int4 via RTN
|
233 |
+
|
234 |
+
## License
|
235 |
+
|
236 |
+
The model is licensed under the [MIT license](https://huggingface.co/microsoft/Phi-3-mini-4k/resolve/main/LICENSE).
|
237 |
+
|
238 |
+
## Trademarks
|
239 |
+
|
240 |
+
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,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
logger = logging.get_logger(__name__)
|
23 |
+
|
24 |
+
PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
25 |
+
"microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json",
|
26 |
+
"microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",
|
27 |
+
}
|
28 |
+
|
29 |
+
|
30 |
+
class Phi3Config(PretrainedConfig):
|
31 |
+
r"""
|
32 |
+
This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
|
33 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
34 |
+
defaults will yield a similar configuration to that of the
|
35 |
+
[microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
|
36 |
+
|
37 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
38 |
+
documentation from [`PretrainedConfig`] for more information.
|
39 |
+
|
40 |
+
Args:
|
41 |
+
vocab_size (`int`, *optional*, defaults to 32064):
|
42 |
+
Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
|
43 |
+
`inputs_ids` passed when calling [`Phi3Model`].
|
44 |
+
hidden_size (`int`, *optional*, defaults to 3072):
|
45 |
+
Dimension of the hidden representations.
|
46 |
+
intermediate_size (`int`, *optional*, defaults to 8192):
|
47 |
+
Dimension of the MLP representations.
|
48 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
49 |
+
Number of hidden layers in the Transformer decoder.
|
50 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
51 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
52 |
+
num_key_value_heads (`int`, *optional*):
|
53 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
54 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
55 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
56 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
57 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
58 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
59 |
+
`num_attention_heads`.
|
60 |
+
resid_pdrop (`float`, *optional*, defaults to 0.0):
|
61 |
+
Dropout probability for mlp outputs.
|
62 |
+
embd_pdrop (`int`, *optional*, defaults to 0.0):
|
63 |
+
The dropout ratio for the embeddings.
|
64 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
65 |
+
The dropout ratio after computing the attention scores.
|
66 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
67 |
+
The non-linear activation function (function or string) in the decoder.
|
68 |
+
max_position_embeddings (`int`, *optional*, defaults to 4096):
|
69 |
+
The maximum sequence length that this model might ever be used with.
|
70 |
+
original_max_position_embeddings (`int`, *optional*, defaults to 4096):
|
71 |
+
The maximum sequence length that this model was trained with. This is used to determine the size of the
|
72 |
+
original RoPE embeddings when using long scaling.
|
73 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
74 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
75 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
76 |
+
The epsilon used by the rms normalization layers.
|
77 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
78 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
79 |
+
relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
|
80 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
81 |
+
Whether to tie weight embeddings
|
82 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
83 |
+
The base period of the RoPE embeddings.
|
84 |
+
rope_scaling (`dict`, *optional*, defaults to `None`):
|
85 |
+
The scaling factor for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
|
86 |
+
contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
|
87 |
+
the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
|
88 |
+
divided by the number of attention heads divided by 2.
|
89 |
+
|
90 |
+
Example:
|
91 |
+
|
92 |
+
```python
|
93 |
+
>>> from transformers import Phi3Model, Phi3Config
|
94 |
+
|
95 |
+
>>> # Initializing a Phi-3 style configuration
|
96 |
+
>>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
|
97 |
+
|
98 |
+
>>> # Initializing a model from the configuration
|
99 |
+
>>> model = Phi3Model(configuration)
|
100 |
+
|
101 |
+
>>> # Accessing the model configuration
|
102 |
+
>>> configuration = model.config
|
103 |
+
```"""
|
104 |
+
|
105 |
+
model_type = "phi3"
|
106 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
107 |
+
|
108 |
+
def __init__(
|
109 |
+
self,
|
110 |
+
vocab_size=32064,
|
111 |
+
hidden_size=3072,
|
112 |
+
intermediate_size=8192,
|
113 |
+
num_hidden_layers=32,
|
114 |
+
num_attention_heads=32,
|
115 |
+
num_key_value_heads=None,
|
116 |
+
resid_pdrop=0.0,
|
117 |
+
embd_pdrop=0.0,
|
118 |
+
attention_dropout=0.0,
|
119 |
+
hidden_act="silu",
|
120 |
+
max_position_embeddings=4096,
|
121 |
+
original_max_position_embeddings=4096,
|
122 |
+
initializer_range=0.02,
|
123 |
+
rms_norm_eps=1e-5,
|
124 |
+
use_cache=True,
|
125 |
+
tie_word_embeddings=False,
|
126 |
+
rope_theta=10000.0,
|
127 |
+
rope_scaling=None,
|
128 |
+
eos_token_id=32000,
|
129 |
+
pad_token_id=32000,
|
130 |
+
sliding_window=None,
|
131 |
+
**kwargs,
|
132 |
+
):
|
133 |
+
self.vocab_size = vocab_size
|
134 |
+
self.hidden_size = hidden_size
|
135 |
+
self.intermediate_size = intermediate_size
|
136 |
+
self.num_hidden_layers = num_hidden_layers
|
137 |
+
self.num_attention_heads = num_attention_heads
|
138 |
+
|
139 |
+
if num_key_value_heads is None:
|
140 |
+
num_key_value_heads = num_attention_heads
|
141 |
+
|
142 |
+
self.num_key_value_heads = num_key_value_heads
|
143 |
+
self.resid_pdrop = resid_pdrop
|
144 |
+
self.embd_pdrop = embd_pdrop
|
145 |
+
self.attention_dropout = attention_dropout
|
146 |
+
self.hidden_act = hidden_act
|
147 |
+
self.max_position_embeddings = max_position_embeddings
|
148 |
+
self.original_max_position_embeddings = original_max_position_embeddings
|
149 |
+
self.initializer_range = initializer_range
|
150 |
+
self.rms_norm_eps = rms_norm_eps
|
151 |
+
self.use_cache = use_cache
|
152 |
+
self.rope_theta = rope_theta
|
153 |
+
self.rope_scaling = rope_scaling
|
154 |
+
self.sliding_window = sliding_window
|
155 |
+
|
156 |
+
super().__init__(
|
157 |
+
eos_token_id=eos_token_id,
|
158 |
+
pad_token_id=pad_token_id,
|
159 |
+
tie_word_embeddings=tie_word_embeddings,
|
160 |
+
**kwargs,
|
161 |
+
)
|
162 |
+
|
163 |
+
def _rope_scaling_validation(self):
|
164 |
+
if self.rope_scaling is None:
|
165 |
+
return
|
166 |
+
|
167 |
+
assert (
|
168 |
+
(isinstance(self.rope_scaling, dict))
|
169 |
+
and ("type" in self.rope_scaling)
|
170 |
+
and ("short_factor" in self.rope_scaling)
|
171 |
+
and ("long_factor" in self.rope_scaling)
|
172 |
+
), (
|
173 |
+
"`rope_scaling` must be a dictionary with three keys: `type`, `short_factor` and `long_factor`, "
|
174 |
+
f"got {self.rope_scaling}."
|
175 |
+
)
|
176 |
+
|
177 |
+
assert self.rope_scaling["type"].lower() == "longrope", "RoPE scaling type must be `longrope`."
|
178 |
+
|
179 |
+
short_factor = self.rope_scaling["short_factor"]
|
180 |
+
assert isinstance(short_factor, list) and all(
|
181 |
+
[isinstance(x, (int, float)) for x in short_factor]
|
182 |
+
), f"RoPE scaling factor must be a list of numbers, got {short_factor}."
|
183 |
+
assert (
|
184 |
+
len(short_factor) == self.hidden_size // self.num_attention_heads // 2
|
185 |
+
), f"Length of RoPE scaling factor must be half of the attention head, got {short_factor}."
|
186 |
+
|
187 |
+
long_factor = self.rope_scaling["long_factor"]
|
188 |
+
assert isinstance(long_factor, list) and all(
|
189 |
+
[isinstance(x, (int, float)) for x in long_factor]
|
190 |
+
), f"RoPE scaling factor must be a list of numbers, got {long_factor}."
|
191 |
+
assert (
|
192 |
+
len(long_factor) == self.hidden_size // self.num_attention_heads // 2
|
193 |
+
), 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,1636 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from transformers.activations import ACT2FN
|
29 |
+
from transformers.cache_utils import Cache, DynamicCache
|
30 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
|
31 |
+
from transformers.modeling_outputs import (
|
32 |
+
BaseModelOutputWithPast,
|
33 |
+
CausalLMOutputWithPast,
|
34 |
+
SequenceClassifierOutputWithPast,
|
35 |
+
TokenClassifierOutput,
|
36 |
+
)
|
37 |
+
from transformers.modeling_utils import PreTrainedModel
|
38 |
+
from transformers.utils import (
|
39 |
+
add_code_sample_docstrings,
|
40 |
+
add_start_docstrings,
|
41 |
+
add_start_docstrings_to_model_forward,
|
42 |
+
is_flash_attn_greater_or_equal_2_10,
|
43 |
+
logging,
|
44 |
+
replace_return_docstrings,
|
45 |
+
)
|
46 |
+
|
47 |
+
from .configuration_phi3 import Phi3Config
|
48 |
+
|
49 |
+
logger = logging.get_logger(__name__)
|
50 |
+
|
51 |
+
# Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
|
52 |
+
# if is_flash_attn_2_available():
|
53 |
+
_flash_supports_window_size = False
|
54 |
+
try:
|
55 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
56 |
+
|
57 |
+
_flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
|
58 |
+
|
59 |
+
if not _flash_supports_window_size:
|
60 |
+
raise ValueError("Please update flash-attention to support window size.")
|
61 |
+
|
62 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
63 |
+
from flash_attn.ops.activations import swiglu
|
64 |
+
from flash_attn.ops.rms_norm import RMSNorm as Phi3FlashRMSNorm
|
65 |
+
# else:
|
66 |
+
except ImportError as error:
|
67 |
+
logger.warning(
|
68 |
+
f"Flash Attention or Flash Attention Submodules not found, consider installing for better performance: {error}."
|
69 |
+
)
|
70 |
+
if not _flash_supports_window_size:
|
71 |
+
logger.warning(
|
72 |
+
"This version of flash does not support window size. Please use `attn_implementation='eager'` or upgrade flash-attn library."
|
73 |
+
)
|
74 |
+
swiglu = None
|
75 |
+
Phi3FlashRMSNorm = None
|
76 |
+
|
77 |
+
_CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
|
78 |
+
_CONFIG_FOR_DOC = "Phi3Config"
|
79 |
+
|
80 |
+
PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
81 |
+
"microsoft/Phi-3-mini-4k-instruct",
|
82 |
+
"microsoft/Phi-3-mini-128k-instruct",
|
83 |
+
# See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
|
84 |
+
]
|
85 |
+
|
86 |
+
|
87 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
|
88 |
+
class Phi3RMSNorm(nn.Module):
|
89 |
+
def __init__(self, hidden_size, eps=1e-5):
|
90 |
+
"""
|
91 |
+
Phi3RMSNorm is equivalent to T5LayerNorm
|
92 |
+
"""
|
93 |
+
super().__init__()
|
94 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
95 |
+
self.variance_epsilon = eps
|
96 |
+
|
97 |
+
def forward(self, hidden_states):
|
98 |
+
input_dtype = hidden_states.dtype
|
99 |
+
hidden_states = hidden_states.to(torch.float32)
|
100 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
101 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
102 |
+
return self.weight * hidden_states.to(input_dtype)
|
103 |
+
|
104 |
+
|
105 |
+
PHI3_NORM_CLASS = Phi3RMSNorm if Phi3FlashRMSNorm is None else Phi3FlashRMSNorm
|
106 |
+
|
107 |
+
|
108 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
109 |
+
def _get_unpad_data(attention_mask):
|
110 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
111 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
112 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
113 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
|
114 |
+
return (
|
115 |
+
indices,
|
116 |
+
cu_seqlens,
|
117 |
+
max_seqlen_in_batch,
|
118 |
+
)
|
119 |
+
|
120 |
+
|
121 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Phi3
|
122 |
+
class Phi3RotaryEmbedding(nn.Module):
|
123 |
+
def __init__(self, dim, max_position_embeddings=4096, base=10000, device=None):
|
124 |
+
super().__init__()
|
125 |
+
|
126 |
+
self.dim = dim
|
127 |
+
self.max_position_embeddings = max_position_embeddings
|
128 |
+
self.base = base
|
129 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
130 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
131 |
+
|
132 |
+
# Build here to make `torch.jit.trace` work.
|
133 |
+
self._set_cos_sin_cache(
|
134 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
135 |
+
)
|
136 |
+
|
137 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
138 |
+
self.max_seq_len_cached = seq_len
|
139 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
|
140 |
+
|
141 |
+
freqs = torch.outer(t, self.inv_freq)
|
142 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
143 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
144 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
145 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
146 |
+
|
147 |
+
def forward(self, x, seq_len=None):
|
148 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
149 |
+
if seq_len > self.max_seq_len_cached:
|
150 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
151 |
+
|
152 |
+
return (
|
153 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
154 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
155 |
+
)
|
156 |
+
|
157 |
+
|
158 |
+
class Phi3LongScaledRotaryEmbedding(nn.Module):
|
159 |
+
def __init__(
|
160 |
+
self,
|
161 |
+
dim,
|
162 |
+
short_factor,
|
163 |
+
long_factor,
|
164 |
+
max_position_embeddings=4096,
|
165 |
+
original_max_position_embeddings=4096,
|
166 |
+
base=10000,
|
167 |
+
magnitude_scaling_policy="su",
|
168 |
+
):
|
169 |
+
super().__init__()
|
170 |
+
|
171 |
+
self.dim = dim
|
172 |
+
self.max_position_embeddings = max_position_embeddings
|
173 |
+
self.original_max_position_embeddings = original_max_position_embeddings
|
174 |
+
self.base = base
|
175 |
+
|
176 |
+
if magnitude_scaling_policy == "su":
|
177 |
+
self._calc_mscale = self._calc_mscale_su
|
178 |
+
elif magnitude_scaling_policy == "yarn":
|
179 |
+
self._calc_mscale = self._calc_mscale_yarn
|
180 |
+
else:
|
181 |
+
self._calc_mscale = lambda scale: float(scale)
|
182 |
+
|
183 |
+
self.short_factor = short_factor
|
184 |
+
self.long_factor = long_factor
|
185 |
+
|
186 |
+
def _calc_mscale_su(self, scale):
|
187 |
+
if scale <= 1.0:
|
188 |
+
return 1.0
|
189 |
+
return math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
|
190 |
+
|
191 |
+
def _calc_mscale_yarn(self, scale):
|
192 |
+
if scale <= 1.0:
|
193 |
+
return 1.0
|
194 |
+
return 0.1 * math.log(scale) + 1.0
|
195 |
+
|
196 |
+
@torch.no_grad()
|
197 |
+
def forward(self, x, seq_len=None):
|
198 |
+
if seq_len is None:
|
199 |
+
seq_len = x.shape[-2]
|
200 |
+
t = torch.arange(seq_len, device=x.device, dtype=torch.float32)
|
201 |
+
|
202 |
+
if seq_len > self.original_max_position_embeddings:
|
203 |
+
t = torch.arange(seq_len, device=x.device, dtype=torch.float32)
|
204 |
+
rescale_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
|
205 |
+
else:
|
206 |
+
t = torch.arange(self.original_max_position_embeddings, device=x.device, dtype=torch.float32)
|
207 |
+
rescale_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
|
208 |
+
assert rescale_factors.shape == (
|
209 |
+
self.dim // 2,
|
210 |
+
), f"misaligned shape for LongRoPE rescale factors: {rescale_factors.shape}"
|
211 |
+
|
212 |
+
inv_freq = 1.0 / (
|
213 |
+
rescale_factors * (self.base ** (torch.arange(0, self.dim, 2).float().to(x.device) / self.dim))
|
214 |
+
)
|
215 |
+
|
216 |
+
freqs = torch.outer(t, inv_freq)
|
217 |
+
mscale = self._calc_mscale(self.max_position_embeddings / self.original_max_position_embeddings)
|
218 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
219 |
+
|
220 |
+
return (emb.cos() * mscale).to(x.dtype), (emb.sin() * mscale).to(x.dtype)
|
221 |
+
|
222 |
+
|
223 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
224 |
+
def rotate_half(x):
|
225 |
+
"""Rotates half the hidden dims of the input."""
|
226 |
+
x1 = x[..., : x.shape[-1] // 2]
|
227 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
228 |
+
return torch.cat((-x2, x1), dim=-1)
|
229 |
+
|
230 |
+
|
231 |
+
# Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
|
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.llama.modeling_llama.LlamaFlashAttention2._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 |
+
(
|
654 |
+
query_states,
|
655 |
+
key_states,
|
656 |
+
value_states,
|
657 |
+
indices_q,
|
658 |
+
cu_seq_lens,
|
659 |
+
max_seq_lens,
|
660 |
+
) = self._upad_input(query_states, key_states, value_states, attention_mask, query_length)
|
661 |
+
|
662 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
663 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
664 |
+
|
665 |
+
if not use_sliding_windows:
|
666 |
+
attn_output_unpad = flash_attn_varlen_func(
|
667 |
+
query_states,
|
668 |
+
key_states,
|
669 |
+
value_states,
|
670 |
+
cu_seqlens_q=cu_seqlens_q,
|
671 |
+
cu_seqlens_k=cu_seqlens_k,
|
672 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
673 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
674 |
+
dropout_p=dropout,
|
675 |
+
softmax_scale=softmax_scale,
|
676 |
+
causal=causal,
|
677 |
+
)
|
678 |
+
else:
|
679 |
+
attn_output_unpad = flash_attn_varlen_func(
|
680 |
+
query_states,
|
681 |
+
key_states,
|
682 |
+
value_states,
|
683 |
+
cu_seqlens_q=cu_seqlens_q,
|
684 |
+
cu_seqlens_k=cu_seqlens_k,
|
685 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
686 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
687 |
+
dropout_p=dropout,
|
688 |
+
softmax_scale=softmax_scale,
|
689 |
+
causal=causal,
|
690 |
+
window_size=(
|
691 |
+
self.config.sliding_window,
|
692 |
+
self.config.sliding_window,
|
693 |
+
),
|
694 |
+
)
|
695 |
+
|
696 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
697 |
+
else:
|
698 |
+
if not use_sliding_windows:
|
699 |
+
attn_output = flash_attn_func(
|
700 |
+
query_states,
|
701 |
+
key_states,
|
702 |
+
value_states,
|
703 |
+
dropout,
|
704 |
+
softmax_scale=softmax_scale,
|
705 |
+
causal=causal,
|
706 |
+
)
|
707 |
+
else:
|
708 |
+
attn_output = flash_attn_func(
|
709 |
+
query_states,
|
710 |
+
key_states,
|
711 |
+
value_states,
|
712 |
+
dropout,
|
713 |
+
softmax_scale=softmax_scale,
|
714 |
+
causal=causal,
|
715 |
+
window_size=(
|
716 |
+
self.config.sliding_window,
|
717 |
+
self.config.sliding_window,
|
718 |
+
),
|
719 |
+
)
|
720 |
+
|
721 |
+
return attn_output
|
722 |
+
|
723 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
|
724 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
725 |
+
batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
|
726 |
+
|
727 |
+
# On the first iteration we need to properly re-create the padding mask
|
728 |
+
# by slicing it on the proper place
|
729 |
+
if kv_seq_len != attention_mask.shape[-1]:
|
730 |
+
attention_mask_num_tokens = attention_mask.shape[-1]
|
731 |
+
attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
|
732 |
+
|
733 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
734 |
+
|
735 |
+
key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
736 |
+
value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
737 |
+
|
738 |
+
if query_length == kv_seq_len:
|
739 |
+
query_layer = index_first_axis(
|
740 |
+
query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim),
|
741 |
+
indices_k,
|
742 |
+
)
|
743 |
+
cu_seqlens_q = cu_seqlens_k
|
744 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
745 |
+
indices_q = indices_k
|
746 |
+
elif query_length == 1:
|
747 |
+
max_seqlen_in_batch_q = 1
|
748 |
+
cu_seqlens_q = torch.arange(
|
749 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
750 |
+
) # There is a memcpy here, that is very bad.
|
751 |
+
indices_q = cu_seqlens_q[:-1]
|
752 |
+
query_layer = query_layer.squeeze(1)
|
753 |
+
else:
|
754 |
+
# The -q_len: slice assumes left padding.
|
755 |
+
attention_mask = attention_mask[:, -query_length:]
|
756 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
757 |
+
|
758 |
+
return (
|
759 |
+
query_layer,
|
760 |
+
key_layer,
|
761 |
+
value_layer,
|
762 |
+
indices_q,
|
763 |
+
(cu_seqlens_q, cu_seqlens_k),
|
764 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
765 |
+
)
|
766 |
+
|
767 |
+
|
768 |
+
# copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
|
769 |
+
# TODO @Arthur no longer copied from LLama after static cache
|
770 |
+
class Phi3SdpaAttention(Phi3Attention):
|
771 |
+
"""
|
772 |
+
Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
773 |
+
`Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
774 |
+
SDPA API.
|
775 |
+
"""
|
776 |
+
|
777 |
+
# Adapted from Phi3Attention.forward
|
778 |
+
def forward(
|
779 |
+
self,
|
780 |
+
hidden_states: torch.Tensor,
|
781 |
+
attention_mask: Optional[torch.Tensor] = None,
|
782 |
+
position_ids: Optional[torch.LongTensor] = None,
|
783 |
+
past_key_value: Optional[Cache] = None,
|
784 |
+
output_attentions: bool = False,
|
785 |
+
use_cache: bool = False,
|
786 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
787 |
+
if output_attentions:
|
788 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
789 |
+
logger.warning_once(
|
790 |
+
"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, "
|
791 |
+
'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.'
|
792 |
+
)
|
793 |
+
return super().forward(
|
794 |
+
hidden_states=hidden_states,
|
795 |
+
attention_mask=attention_mask,
|
796 |
+
position_ids=position_ids,
|
797 |
+
past_key_value=past_key_value,
|
798 |
+
output_attentions=output_attentions,
|
799 |
+
use_cache=use_cache,
|
800 |
+
)
|
801 |
+
|
802 |
+
bsz, q_len, _ = hidden_states.size()
|
803 |
+
|
804 |
+
qkv = self.qkv_proj(hidden_states)
|
805 |
+
query_pos = self.num_heads * self.head_dim
|
806 |
+
query_states = qkv[..., :query_pos]
|
807 |
+
key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
|
808 |
+
value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
|
809 |
+
|
810 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
811 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
812 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
813 |
+
|
814 |
+
kv_seq_len = key_states.shape[-2]
|
815 |
+
if past_key_value is not None:
|
816 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
817 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
818 |
+
|
819 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
820 |
+
|
821 |
+
if past_key_value is not None:
|
822 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
823 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
824 |
+
|
825 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
826 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
827 |
+
|
828 |
+
if attention_mask is not None:
|
829 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
830 |
+
raise ValueError(
|
831 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
832 |
+
)
|
833 |
+
|
834 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
835 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
836 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
837 |
+
query_states = query_states.contiguous()
|
838 |
+
key_states = key_states.contiguous()
|
839 |
+
value_states = value_states.contiguous()
|
840 |
+
|
841 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
842 |
+
query_states,
|
843 |
+
key_states,
|
844 |
+
value_states,
|
845 |
+
attn_mask=attention_mask,
|
846 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
847 |
+
# 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.
|
848 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
849 |
+
)
|
850 |
+
|
851 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
852 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
853 |
+
|
854 |
+
attn_output = self.o_proj(attn_output)
|
855 |
+
|
856 |
+
return attn_output, None, past_key_value
|
857 |
+
|
858 |
+
|
859 |
+
PHI3_ATTENTION_CLASSES = {
|
860 |
+
"eager": Phi3Attention,
|
861 |
+
"flash_attention_2": Phi3FlashAttention2,
|
862 |
+
"sdpa": Phi3SdpaAttention,
|
863 |
+
}
|
864 |
+
|
865 |
+
|
866 |
+
class Phi3DecoderLayer(nn.Module):
|
867 |
+
def __init__(self, config: Phi3Config, layer_idx: int):
|
868 |
+
super().__init__()
|
869 |
+
|
870 |
+
self.config = config
|
871 |
+
self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
|
872 |
+
|
873 |
+
self.mlp = Phi3MLP(config)
|
874 |
+
self.input_layernorm = PHI3_NORM_CLASS(config.hidden_size, eps=config.rms_norm_eps)
|
875 |
+
|
876 |
+
self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
|
877 |
+
self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
|
878 |
+
self.post_attention_layernorm = PHI3_NORM_CLASS(config.hidden_size, eps=config.rms_norm_eps)
|
879 |
+
|
880 |
+
def forward(
|
881 |
+
self,
|
882 |
+
hidden_states: torch.Tensor,
|
883 |
+
attention_mask: Optional[torch.Tensor] = None,
|
884 |
+
position_ids: Optional[torch.LongTensor] = None,
|
885 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
886 |
+
output_attentions: Optional[bool] = False,
|
887 |
+
use_cache: Optional[bool] = False,
|
888 |
+
**kwargs,
|
889 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
890 |
+
if "padding_mask" in kwargs:
|
891 |
+
warnings.warn(
|
892 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
893 |
+
)
|
894 |
+
"""
|
895 |
+
Args:
|
896 |
+
hidden_states (`torch.FloatTensor`):
|
897 |
+
input to the layer of shape `(batch, seq_len, embed_dim)`
|
898 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
899 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
900 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
901 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
|
902 |
+
`[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
903 |
+
output_attentions (`bool`, *optional*):
|
904 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
905 |
+
returned tensors for more detail.
|
906 |
+
use_cache (`bool`, *optional*):
|
907 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
908 |
+
(see `past_key_values`).
|
909 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
910 |
+
"""
|
911 |
+
|
912 |
+
residual = hidden_states
|
913 |
+
|
914 |
+
hidden_states = self.input_layernorm(hidden_states)
|
915 |
+
|
916 |
+
# Self Attention
|
917 |
+
attn_outputs, self_attn_weights, present_key_value = self.self_attn(
|
918 |
+
hidden_states=hidden_states,
|
919 |
+
attention_mask=attention_mask,
|
920 |
+
position_ids=position_ids,
|
921 |
+
past_key_value=past_key_value,
|
922 |
+
output_attentions=output_attentions,
|
923 |
+
use_cache=use_cache,
|
924 |
+
)
|
925 |
+
|
926 |
+
hidden_states = residual + self.resid_attn_dropout(attn_outputs)
|
927 |
+
|
928 |
+
residual = hidden_states
|
929 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
930 |
+
hidden_states = self.mlp(hidden_states)
|
931 |
+
hidden_states = residual + self.resid_mlp_dropout(hidden_states)
|
932 |
+
|
933 |
+
outputs = (hidden_states,)
|
934 |
+
|
935 |
+
if output_attentions:
|
936 |
+
outputs += (self_attn_weights,)
|
937 |
+
|
938 |
+
if use_cache:
|
939 |
+
outputs += (present_key_value,)
|
940 |
+
|
941 |
+
return outputs
|
942 |
+
|
943 |
+
|
944 |
+
PHI3_START_DOCSTRING = r"""
|
945 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
946 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
947 |
+
etc.)
|
948 |
+
|
949 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
950 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
951 |
+
and behavior.
|
952 |
+
|
953 |
+
Parameters:
|
954 |
+
config ([`Phi3Config`]):
|
955 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
956 |
+
load the weights associated with the model, only the configuration. Check out the
|
957 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
958 |
+
"""
|
959 |
+
|
960 |
+
|
961 |
+
@add_start_docstrings(
|
962 |
+
"The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
|
963 |
+
PHI3_START_DOCSTRING,
|
964 |
+
)
|
965 |
+
class Phi3PreTrainedModel(PreTrainedModel):
|
966 |
+
config_class = Phi3Config
|
967 |
+
base_model_prefix = "model"
|
968 |
+
supports_gradient_checkpointing = True
|
969 |
+
_no_split_modules = ["Phi3DecoderLayer"]
|
970 |
+
_skip_keys_device_placement = "past_key_values"
|
971 |
+
_supports_flash_attn_2 = True
|
972 |
+
_supports_sdpa = False
|
973 |
+
_supports_cache_class = True
|
974 |
+
|
975 |
+
_version = "0.0.5"
|
976 |
+
|
977 |
+
def _init_weights(self, module):
|
978 |
+
std = self.config.initializer_range
|
979 |
+
if isinstance(module, nn.Linear):
|
980 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
981 |
+
if module.bias is not None:
|
982 |
+
module.bias.data.zero_()
|
983 |
+
elif isinstance(module, nn.Embedding):
|
984 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
985 |
+
if module.padding_idx is not None:
|
986 |
+
module.weight.data[module.padding_idx].zero_()
|
987 |
+
|
988 |
+
|
989 |
+
PHI3_INPUTS_DOCSTRING = r"""
|
990 |
+
Args:
|
991 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
992 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
993 |
+
it.
|
994 |
+
|
995 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
996 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
997 |
+
|
998 |
+
[What are input IDs?](../glossary#input-ids)
|
999 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1000 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
1001 |
+
|
1002 |
+
- 1 for tokens that are **not masked**,
|
1003 |
+
- 0 for tokens that are **masked**.
|
1004 |
+
|
1005 |
+
[What are attention masks?](../glossary#attention-mask)
|
1006 |
+
|
1007 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1008 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1009 |
+
|
1010 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
1011 |
+
`past_key_values`).
|
1012 |
+
|
1013 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
1014 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
1015 |
+
information on the default strategy.
|
1016 |
+
|
1017 |
+
- 1 indicates the head is **not masked**,
|
1018 |
+
- 0 indicates the head is **masked**.
|
1019 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1020 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
1021 |
+
config.n_positions - 1]`.
|
1022 |
+
|
1023 |
+
[What are position IDs?](../glossary#position-ids)
|
1024 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
1025 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
1026 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
1027 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
1028 |
+
|
1029 |
+
Two formats are allowed:
|
1030 |
+
- a [`~cache_utils.Cache`] instance;
|
1031 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
1032 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
1033 |
+
cache format.
|
1034 |
+
|
1035 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
1036 |
+
legacy cache format will be returned.
|
1037 |
+
|
1038 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
1039 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
1040 |
+
of shape `(batch_size, sequence_length)`.
|
1041 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1042 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
1043 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
1044 |
+
model's internal embedding lookup matrix.
|
1045 |
+
use_cache (`bool`, *optional*):
|
1046 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1047 |
+
`past_key_values`).
|
1048 |
+
output_attentions (`bool`, *optional*):
|
1049 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1050 |
+
tensors for more detail.
|
1051 |
+
output_hidden_states (`bool`, *optional*):
|
1052 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1053 |
+
more detail.
|
1054 |
+
return_dict (`bool`, *optional*):
|
1055 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
1056 |
+
"""
|
1057 |
+
|
1058 |
+
|
1059 |
+
@add_start_docstrings(
|
1060 |
+
"The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
|
1061 |
+
PHI3_START_DOCSTRING,
|
1062 |
+
)
|
1063 |
+
class Phi3Model(Phi3PreTrainedModel):
|
1064 |
+
"""
|
1065 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
|
1066 |
+
|
1067 |
+
Args:
|
1068 |
+
config: Phi3Config
|
1069 |
+
"""
|
1070 |
+
|
1071 |
+
def __init__(self, config: Phi3Config):
|
1072 |
+
super().__init__(config)
|
1073 |
+
self.padding_idx = config.pad_token_id
|
1074 |
+
self.vocab_size = config.vocab_size
|
1075 |
+
|
1076 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
1077 |
+
self.embed_dropout = nn.Dropout(config.embd_pdrop)
|
1078 |
+
self.layers = nn.ModuleList(
|
1079 |
+
[Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
1080 |
+
)
|
1081 |
+
self.norm = PHI3_NORM_CLASS(config.hidden_size, eps=config.rms_norm_eps)
|
1082 |
+
|
1083 |
+
self._attn_implementation = config._attn_implementation
|
1084 |
+
|
1085 |
+
self.gradient_checkpointing = False
|
1086 |
+
# Initialize weights and apply final processing
|
1087 |
+
self.post_init()
|
1088 |
+
|
1089 |
+
def get_input_embeddings(self):
|
1090 |
+
return self.embed_tokens
|
1091 |
+
|
1092 |
+
def set_input_embeddings(self, value):
|
1093 |
+
self.embed_tokens = value
|
1094 |
+
|
1095 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
1096 |
+
def forward(
|
1097 |
+
self,
|
1098 |
+
input_ids: torch.LongTensor = None,
|
1099 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1100 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1101 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1102 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1103 |
+
use_cache: Optional[bool] = None,
|
1104 |
+
output_attentions: Optional[bool] = None,
|
1105 |
+
output_hidden_states: Optional[bool] = None,
|
1106 |
+
return_dict: Optional[bool] = None,
|
1107 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
1108 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1109 |
+
output_hidden_states = (
|
1110 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1111 |
+
)
|
1112 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1113 |
+
|
1114 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1115 |
+
|
1116 |
+
# retrieve input_ids and inputs_embeds
|
1117 |
+
if input_ids is not None and inputs_embeds is not None:
|
1118 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
1119 |
+
elif input_ids is not None:
|
1120 |
+
batch_size, seq_length = input_ids.shape[:2]
|
1121 |
+
elif inputs_embeds is not None:
|
1122 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
1123 |
+
else:
|
1124 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1125 |
+
|
1126 |
+
past_key_values_length = 0
|
1127 |
+
|
1128 |
+
if self.gradient_checkpointing and self.training:
|
1129 |
+
if use_cache:
|
1130 |
+
logger.warning_once(
|
1131 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
1132 |
+
)
|
1133 |
+
use_cache = False
|
1134 |
+
|
1135 |
+
if use_cache:
|
1136 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
1137 |
+
if use_legacy_cache:
|
1138 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
1139 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
1140 |
+
|
1141 |
+
if position_ids is None:
|
1142 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1143 |
+
position_ids = torch.arange(
|
1144 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
1145 |
+
)
|
1146 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
1147 |
+
else:
|
1148 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
1149 |
+
|
1150 |
+
if inputs_embeds is None:
|
1151 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
1152 |
+
|
1153 |
+
if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
|
1154 |
+
is_padding_right = attention_mask[:, -1].sum().item() != batch_size
|
1155 |
+
if is_padding_right:
|
1156 |
+
raise ValueError(
|
1157 |
+
"You are attempting to perform batched generation with padding_side='right'"
|
1158 |
+
" this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
|
1159 |
+
" call `tokenizer.padding_side = 'left'` before tokenizing the input. "
|
1160 |
+
)
|
1161 |
+
|
1162 |
+
if self._attn_implementation == "flash_attention_2":
|
1163 |
+
# 2d mask is passed through the layers
|
1164 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
1165 |
+
else:
|
1166 |
+
# 4d mask is passed through the layers
|
1167 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1168 |
+
attention_mask,
|
1169 |
+
(batch_size, seq_length),
|
1170 |
+
inputs_embeds,
|
1171 |
+
past_key_values_length,
|
1172 |
+
sliding_window=self.config.sliding_window,
|
1173 |
+
)
|
1174 |
+
|
1175 |
+
hidden_states = inputs_embeds
|
1176 |
+
|
1177 |
+
# decoder layers
|
1178 |
+
all_hidden_states = () if output_hidden_states else None
|
1179 |
+
all_self_attns = () if output_attentions else None
|
1180 |
+
next_decoder_cache = None
|
1181 |
+
|
1182 |
+
for decoder_layer in self.layers:
|
1183 |
+
if output_hidden_states:
|
1184 |
+
all_hidden_states += (hidden_states,)
|
1185 |
+
|
1186 |
+
if self.gradient_checkpointing and self.training:
|
1187 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1188 |
+
decoder_layer.__call__,
|
1189 |
+
hidden_states,
|
1190 |
+
attention_mask,
|
1191 |
+
position_ids,
|
1192 |
+
past_key_values,
|
1193 |
+
output_attentions,
|
1194 |
+
use_cache,
|
1195 |
+
)
|
1196 |
+
else:
|
1197 |
+
layer_outputs = decoder_layer(
|
1198 |
+
hidden_states,
|
1199 |
+
attention_mask=attention_mask,
|
1200 |
+
position_ids=position_ids,
|
1201 |
+
past_key_value=past_key_values,
|
1202 |
+
output_attentions=output_attentions,
|
1203 |
+
use_cache=use_cache,
|
1204 |
+
)
|
1205 |
+
|
1206 |
+
hidden_states = layer_outputs[0]
|
1207 |
+
|
1208 |
+
if use_cache:
|
1209 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1210 |
+
|
1211 |
+
if output_attentions:
|
1212 |
+
all_self_attns += (layer_outputs[1],)
|
1213 |
+
|
1214 |
+
hidden_states = self.norm(hidden_states)
|
1215 |
+
|
1216 |
+
# add hidden states from the last decoder layer
|
1217 |
+
if output_hidden_states:
|
1218 |
+
all_hidden_states += (hidden_states,)
|
1219 |
+
|
1220 |
+
next_cache = None
|
1221 |
+
if use_cache:
|
1222 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
1223 |
+
if not return_dict:
|
1224 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
1225 |
+
return BaseModelOutputWithPast(
|
1226 |
+
last_hidden_state=hidden_states,
|
1227 |
+
past_key_values=next_cache,
|
1228 |
+
hidden_states=all_hidden_states,
|
1229 |
+
attentions=all_self_attns,
|
1230 |
+
)
|
1231 |
+
|
1232 |
+
|
1233 |
+
class Phi3ForCausalLM(Phi3PreTrainedModel):
|
1234 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1235 |
+
|
1236 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3,bias=False->bias=True
|
1237 |
+
def __init__(self, config):
|
1238 |
+
super().__init__(config)
|
1239 |
+
self.model = Phi3Model(config)
|
1240 |
+
self.vocab_size = config.vocab_size
|
1241 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1242 |
+
|
1243 |
+
# Initialize weights and apply final processing
|
1244 |
+
self.post_init()
|
1245 |
+
|
1246 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
|
1247 |
+
def get_input_embeddings(self):
|
1248 |
+
return self.model.embed_tokens
|
1249 |
+
|
1250 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
|
1251 |
+
def set_input_embeddings(self, value):
|
1252 |
+
self.model.embed_tokens = value
|
1253 |
+
|
1254 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
|
1255 |
+
def get_output_embeddings(self):
|
1256 |
+
return self.lm_head
|
1257 |
+
|
1258 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
|
1259 |
+
def set_output_embeddings(self, new_embeddings):
|
1260 |
+
self.lm_head = new_embeddings
|
1261 |
+
|
1262 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
|
1263 |
+
def set_decoder(self, decoder):
|
1264 |
+
self.model = decoder
|
1265 |
+
|
1266 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
|
1267 |
+
def get_decoder(self):
|
1268 |
+
return self.model
|
1269 |
+
|
1270 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
1271 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1272 |
+
def forward(
|
1273 |
+
self,
|
1274 |
+
input_ids: torch.LongTensor = None,
|
1275 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1276 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1277 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1278 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1279 |
+
labels: Optional[torch.LongTensor] = None,
|
1280 |
+
use_cache: Optional[bool] = None,
|
1281 |
+
output_attentions: Optional[bool] = None,
|
1282 |
+
output_hidden_states: Optional[bool] = None,
|
1283 |
+
return_dict: Optional[bool] = None,
|
1284 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1285 |
+
r"""
|
1286 |
+
Args:
|
1287 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1288 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1289 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1290 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1291 |
+
|
1292 |
+
Returns:
|
1293 |
+
|
1294 |
+
Example:
|
1295 |
+
|
1296 |
+
```python
|
1297 |
+
>>> from transformers import AutoTokenizer, Phi3ForCausalLM
|
1298 |
+
|
1299 |
+
>>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3")
|
1300 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3")
|
1301 |
+
|
1302 |
+
>>> prompt = "This is an example script ."
|
1303 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1304 |
+
|
1305 |
+
>>> # Generate
|
1306 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1307 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1308 |
+
'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
|
1309 |
+
```"""
|
1310 |
+
|
1311 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1312 |
+
output_hidden_states = (
|
1313 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1314 |
+
)
|
1315 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1316 |
+
|
1317 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1318 |
+
outputs = self.model(
|
1319 |
+
input_ids=input_ids,
|
1320 |
+
attention_mask=attention_mask,
|
1321 |
+
position_ids=position_ids,
|
1322 |
+
past_key_values=past_key_values,
|
1323 |
+
inputs_embeds=inputs_embeds,
|
1324 |
+
use_cache=use_cache,
|
1325 |
+
output_attentions=output_attentions,
|
1326 |
+
output_hidden_states=output_hidden_states,
|
1327 |
+
return_dict=return_dict,
|
1328 |
+
)
|
1329 |
+
|
1330 |
+
hidden_states = outputs[0]
|
1331 |
+
logits = self.lm_head(hidden_states)
|
1332 |
+
logits = logits.float()
|
1333 |
+
|
1334 |
+
loss = None
|
1335 |
+
if labels is not None:
|
1336 |
+
# Shift so that tokens < n predict n
|
1337 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1338 |
+
shift_labels = labels[..., 1:].contiguous()
|
1339 |
+
# Flatten the tokens
|
1340 |
+
loss_fct = CrossEntropyLoss()
|
1341 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1342 |
+
shift_labels = shift_labels.view(-1)
|
1343 |
+
# Enable model parallelism
|
1344 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1345 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1346 |
+
|
1347 |
+
if not return_dict:
|
1348 |
+
output = (logits,) + outputs[1:]
|
1349 |
+
return (loss,) + output if loss is not None else output
|
1350 |
+
|
1351 |
+
return CausalLMOutputWithPast(
|
1352 |
+
loss=loss,
|
1353 |
+
logits=logits,
|
1354 |
+
past_key_values=outputs.past_key_values,
|
1355 |
+
hidden_states=outputs.hidden_states,
|
1356 |
+
attentions=outputs.attentions,
|
1357 |
+
)
|
1358 |
+
|
1359 |
+
# Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
|
1360 |
+
def prepare_inputs_for_generation(
|
1361 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
1362 |
+
):
|
1363 |
+
if past_key_values is not None:
|
1364 |
+
if isinstance(past_key_values, Cache):
|
1365 |
+
cache_length = past_key_values.get_seq_length()
|
1366 |
+
past_length = past_key_values.seen_tokens
|
1367 |
+
max_cache_length = past_key_values.get_max_length()
|
1368 |
+
else:
|
1369 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1370 |
+
max_cache_length = None
|
1371 |
+
|
1372 |
+
# Keep only the unprocessed tokens:
|
1373 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1374 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1375 |
+
# input)
|
1376 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1377 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1378 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1379 |
+
# input_ids based on the past_length.
|
1380 |
+
elif past_length < input_ids.shape[1]:
|
1381 |
+
input_ids = input_ids[:, past_length:]
|
1382 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1383 |
+
|
1384 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1385 |
+
if (
|
1386 |
+
max_cache_length is not None
|
1387 |
+
and attention_mask is not None
|
1388 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1389 |
+
):
|
1390 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1391 |
+
|
1392 |
+
position_ids = kwargs.get("position_ids", None)
|
1393 |
+
if attention_mask is not None and position_ids is None:
|
1394 |
+
# create position_ids on the fly for batch generation
|
1395 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1396 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1397 |
+
if past_key_values:
|
1398 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1399 |
+
|
1400 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1401 |
+
if inputs_embeds is not None and past_key_values is None:
|
1402 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1403 |
+
else:
|
1404 |
+
model_inputs = {"input_ids": input_ids}
|
1405 |
+
|
1406 |
+
model_inputs.update(
|
1407 |
+
{
|
1408 |
+
"position_ids": position_ids,
|
1409 |
+
"past_key_values": past_key_values,
|
1410 |
+
"use_cache": kwargs.get("use_cache"),
|
1411 |
+
"attention_mask": attention_mask,
|
1412 |
+
}
|
1413 |
+
)
|
1414 |
+
return model_inputs
|
1415 |
+
|
1416 |
+
@staticmethod
|
1417 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
|
1418 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1419 |
+
reordered_past = ()
|
1420 |
+
for layer_past in past_key_values:
|
1421 |
+
reordered_past += (
|
1422 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1423 |
+
)
|
1424 |
+
return reordered_past
|
1425 |
+
|
1426 |
+
|
1427 |
+
@add_start_docstrings(
|
1428 |
+
"""
|
1429 |
+
The [`Phi3Model`] with a sequence classification head on top (linear layer).
|
1430 |
+
|
1431 |
+
[`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1432 |
+
(e.g. GPT-2) do.
|
1433 |
+
|
1434 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1435 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1436 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1437 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1438 |
+
each row of the batch).
|
1439 |
+
""",
|
1440 |
+
PHI3_START_DOCSTRING,
|
1441 |
+
)
|
1442 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3 with self.transformer->self.model, transformer_outputs->model_outputs
|
1443 |
+
class Phi3ForSequenceClassification(Phi3PreTrainedModel):
|
1444 |
+
def __init__(self, config):
|
1445 |
+
super().__init__(config)
|
1446 |
+
self.num_labels = config.num_labels
|
1447 |
+
self.model = Phi3Model(config)
|
1448 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1449 |
+
|
1450 |
+
# Initialize weights and apply final processing
|
1451 |
+
self.post_init()
|
1452 |
+
|
1453 |
+
def get_input_embeddings(self):
|
1454 |
+
return self.model.embed_tokens
|
1455 |
+
|
1456 |
+
def set_input_embeddings(self, value):
|
1457 |
+
self.model.embed_tokens = value
|
1458 |
+
|
1459 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
1460 |
+
def forward(
|
1461 |
+
self,
|
1462 |
+
input_ids: torch.LongTensor = None,
|
1463 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1464 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1465 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1466 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1467 |
+
labels: Optional[torch.LongTensor] = None,
|
1468 |
+
use_cache: Optional[bool] = None,
|
1469 |
+
output_attentions: Optional[bool] = None,
|
1470 |
+
output_hidden_states: Optional[bool] = None,
|
1471 |
+
return_dict: Optional[bool] = None,
|
1472 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1473 |
+
r"""
|
1474 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1475 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1476 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1477 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1478 |
+
"""
|
1479 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1480 |
+
|
1481 |
+
model_outputs = self.model(
|
1482 |
+
input_ids,
|
1483 |
+
attention_mask=attention_mask,
|
1484 |
+
position_ids=position_ids,
|
1485 |
+
past_key_values=past_key_values,
|
1486 |
+
inputs_embeds=inputs_embeds,
|
1487 |
+
use_cache=use_cache,
|
1488 |
+
output_attentions=output_attentions,
|
1489 |
+
output_hidden_states=output_hidden_states,
|
1490 |
+
return_dict=return_dict,
|
1491 |
+
)
|
1492 |
+
hidden_states = model_outputs[0]
|
1493 |
+
logits = self.score(hidden_states)
|
1494 |
+
|
1495 |
+
if input_ids is not None:
|
1496 |
+
batch_size = input_ids.shape[0]
|
1497 |
+
else:
|
1498 |
+
batch_size = inputs_embeds.shape[0]
|
1499 |
+
|
1500 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1501 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1502 |
+
if self.config.pad_token_id is None:
|
1503 |
+
sequence_lengths = -1
|
1504 |
+
else:
|
1505 |
+
if input_ids is not None:
|
1506 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1507 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1508 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1509 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1510 |
+
else:
|
1511 |
+
sequence_lengths = -1
|
1512 |
+
|
1513 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1514 |
+
|
1515 |
+
loss = None
|
1516 |
+
if labels is not None:
|
1517 |
+
labels = labels.to(logits.device)
|
1518 |
+
if self.config.problem_type is None:
|
1519 |
+
if self.num_labels == 1:
|
1520 |
+
self.config.problem_type = "regression"
|
1521 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1522 |
+
self.config.problem_type = "single_label_classification"
|
1523 |
+
else:
|
1524 |
+
self.config.problem_type = "multi_label_classification"
|
1525 |
+
|
1526 |
+
if self.config.problem_type == "regression":
|
1527 |
+
loss_fct = MSELoss()
|
1528 |
+
if self.num_labels == 1:
|
1529 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1530 |
+
else:
|
1531 |
+
loss = loss_fct(pooled_logits, labels)
|
1532 |
+
elif self.config.problem_type == "single_label_classification":
|
1533 |
+
loss_fct = CrossEntropyLoss()
|
1534 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1535 |
+
elif self.config.problem_type == "multi_label_classification":
|
1536 |
+
loss_fct = BCEWithLogitsLoss()
|
1537 |
+
loss = loss_fct(pooled_logits, labels)
|
1538 |
+
if not return_dict:
|
1539 |
+
output = (pooled_logits,) + model_outputs[1:]
|
1540 |
+
return ((loss,) + output) if loss is not None else output
|
1541 |
+
|
1542 |
+
return SequenceClassifierOutputWithPast(
|
1543 |
+
loss=loss,
|
1544 |
+
logits=pooled_logits,
|
1545 |
+
past_key_values=model_outputs.past_key_values,
|
1546 |
+
hidden_states=model_outputs.hidden_states,
|
1547 |
+
attentions=model_outputs.attentions,
|
1548 |
+
)
|
1549 |
+
|
1550 |
+
|
1551 |
+
@add_start_docstrings(
|
1552 |
+
"""
|
1553 |
+
[`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
1554 |
+
Named-Entity-Recognition (NER) tasks.
|
1555 |
+
""",
|
1556 |
+
PHI3_START_DOCSTRING,
|
1557 |
+
)
|
1558 |
+
# Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,self.transformer->self.model,transformer_outputs->model_outputs
|
1559 |
+
class Phi3ForTokenClassification(Phi3PreTrainedModel):
|
1560 |
+
def __init__(self, config: Phi3Config):
|
1561 |
+
super().__init__(config)
|
1562 |
+
self.num_labels = config.num_labels
|
1563 |
+
|
1564 |
+
self.model = Phi3Model(config)
|
1565 |
+
if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
|
1566 |
+
classifier_dropout = config.classifier_dropout
|
1567 |
+
elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
|
1568 |
+
classifier_dropout = config.hidden_dropout
|
1569 |
+
else:
|
1570 |
+
classifier_dropout = 0.1
|
1571 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1572 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1573 |
+
|
1574 |
+
# Initialize weights and apply final processing
|
1575 |
+
self.post_init()
|
1576 |
+
|
1577 |
+
@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
|
1578 |
+
@add_code_sample_docstrings(
|
1579 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1580 |
+
output_type=TokenClassifierOutput,
|
1581 |
+
config_class=_CONFIG_FOR_DOC,
|
1582 |
+
)
|
1583 |
+
def forward(
|
1584 |
+
self,
|
1585 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1586 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
1587 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1588 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1589 |
+
labels: Optional[torch.Tensor] = None,
|
1590 |
+
use_cache: Optional[bool] = None,
|
1591 |
+
output_attentions: Optional[bool] = None,
|
1592 |
+
output_hidden_states: Optional[bool] = None,
|
1593 |
+
return_dict: Optional[bool] = None,
|
1594 |
+
**deprecated_arguments,
|
1595 |
+
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
1596 |
+
r"""
|
1597 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1598 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1599 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1600 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1601 |
+
"""
|
1602 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1603 |
+
|
1604 |
+
model_outputs = self.model(
|
1605 |
+
input_ids,
|
1606 |
+
past_key_values=past_key_values,
|
1607 |
+
attention_mask=attention_mask,
|
1608 |
+
inputs_embeds=inputs_embeds,
|
1609 |
+
use_cache=use_cache,
|
1610 |
+
output_attentions=output_attentions,
|
1611 |
+
output_hidden_states=output_hidden_states,
|
1612 |
+
return_dict=return_dict,
|
1613 |
+
)
|
1614 |
+
|
1615 |
+
hidden_states = model_outputs[0]
|
1616 |
+
hidden_states = self.dropout(hidden_states)
|
1617 |
+
logits = self.classifier(hidden_states)
|
1618 |
+
|
1619 |
+
loss = None
|
1620 |
+
if labels is not None:
|
1621 |
+
# move labels to correct device to enable model parallelism
|
1622 |
+
labels = labels.to(logits.device)
|
1623 |
+
batch_size, seq_length = labels.shape
|
1624 |
+
loss_fct = CrossEntropyLoss()
|
1625 |
+
loss = loss_fct(logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length))
|
1626 |
+
|
1627 |
+
if not return_dict:
|
1628 |
+
output = (logits,) + model_outputs[2:]
|
1629 |
+
return ((loss,) + output) if loss is not None else output
|
1630 |
+
|
1631 |
+
return TokenClassifierOutput(
|
1632 |
+
loss=loss,
|
1633 |
+
logits=logits,
|
1634 |
+
hidden_states=model_outputs.hidden_states,
|
1635 |
+
attentions=model_outputs.attentions,
|
1636 |
+
)
|
sample_finetune.py
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from datasets import load_dataset
|
3 |
+
from trl import SFTTrainer
|
4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments
|
5 |
+
|
6 |
+
"""
|
7 |
+
Please note that A100 or later generation GPUs are required to finetune Phi-3 models
|
8 |
+
1. Install accelerate:
|
9 |
+
conda install -c conda-forge accelerate
|
10 |
+
2. Setup accelerate config:
|
11 |
+
accelerate config
|
12 |
+
to simply use all the GPUs available:
|
13 |
+
python -c "from accelerate.utils import write_basic_config; write_basic_config(mixed_precision='bf16')"
|
14 |
+
check accelerate config:
|
15 |
+
accelerate env
|
16 |
+
3. Run the code:
|
17 |
+
accelerate launch phi3-mini-sample-ft.py
|
18 |
+
"""
|
19 |
+
|
20 |
+
###################
|
21 |
+
# Hyper-parameters
|
22 |
+
###################
|
23 |
+
|
24 |
+
|
25 |
+
args = {
|
26 |
+
"bf16": True,
|
27 |
+
"do_eval": False,
|
28 |
+
"evaluation_strategy": "no",
|
29 |
+
"eval_steps": 100,
|
30 |
+
"learning_rate": 5.0e-06,
|
31 |
+
"log_level": "info",
|
32 |
+
"logging_steps": 20,
|
33 |
+
"logging_strategy": "steps",
|
34 |
+
"lr_scheduler_type": "cosine",
|
35 |
+
"num_train_epochs": 1,
|
36 |
+
"max_steps": -1,
|
37 |
+
"output_dir": ".",
|
38 |
+
"overwrite_output_dir": True,
|
39 |
+
"per_device_eval_batch_size": 4,
|
40 |
+
"per_device_train_batch_size": 8,
|
41 |
+
"remove_unused_columns": True,
|
42 |
+
"save_steps": 100,
|
43 |
+
"save_total_limit": 1,
|
44 |
+
"seed": 0,
|
45 |
+
"gradient_checkpointing": True,
|
46 |
+
"gradient_accumulation_steps": 1,
|
47 |
+
"warmup_ratio": 0.1,
|
48 |
+
}
|
49 |
+
|
50 |
+
training_args = TrainingArguments(**args)
|
51 |
+
|
52 |
+
|
53 |
+
################
|
54 |
+
# Modle Loading
|
55 |
+
################
|
56 |
+
|
57 |
+
checkpoint_path = "microsoft/Phi-3-mini-4k-instruct"
|
58 |
+
# checkpoint_path = "microsoft/Phi-3-mini-128k-instruct"
|
59 |
+
model_kwargs = dict(
|
60 |
+
trust_remote_code=True,
|
61 |
+
attn_implementation="flash_attention_2", # load the model with flash-attenstion support
|
62 |
+
torch_dtype=torch.bfloat16,
|
63 |
+
device_map="cuda",
|
64 |
+
)
|
65 |
+
model = AutoModelForCausalLM.from_pretrained(checkpoint_path, **model_kwargs)
|
66 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint_path, trust_remote_code=True)
|
67 |
+
|
68 |
+
################
|
69 |
+
# Data Loading
|
70 |
+
################
|
71 |
+
|
72 |
+
dataset = load_dataset("imdb")
|
73 |
+
train_dataset = dataset["train"]
|
74 |
+
eval_dataset = dataset["test"]
|
75 |
+
|
76 |
+
|
77 |
+
################
|
78 |
+
# Training
|
79 |
+
################
|
80 |
+
|
81 |
+
trainer = SFTTrainer(
|
82 |
+
model=model,
|
83 |
+
args=training_args,
|
84 |
+
train_dataset=train_dataset,
|
85 |
+
max_seq_length=2048,
|
86 |
+
dataset_text_field="text",
|
87 |
+
tokenizer=tokenizer,
|
88 |
+
)
|
89 |
+
train_result = trainer.train()
|
90 |
+
metrics = train_result.metrics
|
91 |
+
trainer.log_metrics("train", metrics)
|
92 |
+
trainer.save_metrics("train", metrics)
|
93 |
+
trainer.save_state()
|
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 |
+
}
|