justinthelaw commited on
Commit
03a6b41
1 Parent(s): 200681f

additional model files

Browse files
README.md CHANGED
@@ -1,3 +1,368 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ license_link: <https://huggingface.co/justinthelaw/Phi-3-mini-128k-instruct-4bit-128g/resolve/main/LICENSE>
4
+
5
+ language:
6
+ - en
7
+ pipeline_tag: text-generation
8
+ tags:
9
+ - nlp
10
+ - code
11
+ - phi3
12
+ - custom_code
13
+ - conversational
14
  ---
15
+
16
+ # Phi-3-mini-128k-instruct GPTQ 4-bit 128g Group Size
17
+
18
+ - Model creator: [Microsoft](https://huggingface.co/microsoft)
19
+ - Original model: [Phi-3-mini-128k-instruct](https://huggingface.co/justinthelaw/Phi-3-mini-128k-instruct-4bit-128g)
20
+
21
+ <!-- description start -->
22
+ ## Description
23
+
24
+ This repo contains GPTQ 4-bit, 128g Group Size, quantized model files for the recently released upgrade of [Phi-3-mini-128k-instruct](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct).
25
+
26
+ <!-- README_AWQ.md-provided-files start -->
27
+ ## AWQ parameters
28
+
29
+ Models are released as sharded safetensors files.
30
+
31
+ | Bits | GS | AWQ Dataset | Seq Len | Size |
32
+ | ---- | -- | ----------- | ------- | ---- |
33
+ | 4 | 128 | [pile-val-backup](mit-han-lab/pile-val-backup) | 128000 | 2.28 GB
34
+
35
+ <!-- README_AWQ.md-provided-files end -->
36
+
37
+ ## Model Summary
38
+
39
+ The Phi-3-Mini-128K-Instruct is a 3.8 billion-parameter, lightweight, state-of-the-art open model trained using the Phi-3 datasets.
40
+ This dataset includes both synthetic data and filtered publicly available website data, with an emphasis on high-quality and reasoning-dense properties.
41
+ The model belongs to the Phi-3 family with the Mini version in two variants [4K](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct) and [128K](https://huggingface.co/justinthelaw/Phi-3-mini-128k-instruct-4bit-128g) which is the context length (in tokens) that it can support.
42
+
43
+ After initial training, the model underwent a post-training process that involved supervised fine-tuning and direct preference optimization to enhance its ability to follow instructions and adhere to safety measures.
44
+ When evaluated against benchmarks that test common sense, language understanding, mathematics, coding, long-term context, and logical reasoning, the Phi-3 Mini-128K-Instruct demonstrated robust and state-of-the-art performance among models with fewer than 13 billion parameters.
45
+ Resources and Technical Documentation:
46
+
47
+ 🏡 [Phi-3 Portal](https://azure.microsoft.com/en-us/products/phi-3) <br>
48
+ 📰 [Phi-3 Microsoft Blog](https://aka.ms/Phi-3Build2024) <br>
49
+ 📖 [Phi-3 Technical Report](https://aka.ms/phi3-tech-report) <br>
50
+ 🛠️ [Phi-3 on Azure AI Studio](https://aka.ms/phi3-azure-ai) <br>
51
+ 👩‍🍳 [Phi-3 Cookbook](https://github.com/microsoft/Phi-3CookBook) <br>
52
+ 🖥️ [Try It](https://aka.ms/try-phi3)
53
+
54
+ | | Short Context | Long Context |
55
+ | :- | :- | :- |
56
+ | Mini | 4K [[HF]](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx) ; [[GGUF]](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-gguf) | 128K [[HF]](https://huggingface.co/justinthelaw/Phi-3-mini-128k-instruct-4bit-128g) ; [[ONNX]](https://huggingface.co/justinthelaw/Phi-3-mini-128k-instruct-4bit-128g-onnx)|
57
+ | Small | 8K [[HF]](https://huggingface.co/microsoft/Phi-3-small-8k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-small-8k-instruct-onnx-cuda) | 128K [[HF]](https://huggingface.co/microsoft/Phi-3-small-128k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-small-128k-instruct-onnx-cuda)|
58
+ | Medium | 4K [[HF]](https://huggingface.co/microsoft/Phi-3-medium-4k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-medium-4k-instruct-onnx-cuda) | 128K [[HF]](https://huggingface.co/microsoft/Phi-3-medium-128k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-medium-128k-instruct-onnx-cuda)|
59
+ | Vision | | 128K [[HF]](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct) ; [[ONNX]](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct-onnx-cuda)|
60
+
61
+ ## Intended Uses
62
+
63
+ **Primary use cases**
64
+
65
+ The model is intended for commercial and research use in English. The model provides uses for applications which require:
66
+
67
+ 1) Memory/compute constrained environments
68
+ 2) Latency bound scenarios
69
+ 3) Strong reasoning (especially code, math and logic)
70
+
71
+ Our model is designed to accelerate research on language and multimodal models, for use as a building block for generative AI powered features.
72
+
73
+ **Use case considerations**
74
+
75
+ 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.
76
+
77
+ Nothing contained in this Model Card should be interpreted as or deemed a restriction or modification to the license the model is released under.
78
+
79
+ ## Release Notes
80
+
81
+ This is an update over the original instruction-tuned Phi-3-mini release based on valuable customer feedback.
82
+ The model used additional post-training data leading to substantial gains on long-context understanding, instruction following, and structure output.
83
+ We also improve multi-turn conversation quality, explicitly support <|system|> tag, and significantly improve reasoning capability.
84
+ We believe most use cases will benefit from this release, but we encourage users to test in their particular AI applications.
85
+ We appreciate the enthusiastic adoption of the Phi-3 model family, and continue to welcome all feedback from the community.
86
+
87
+ These tables below highlights improvements on instruction following, structure output, reasoning, and long-context understanding of the new release on our public and internal benchmark datasets.
88
+
89
+ | Benchmarks | Original | June 2024 Update |
90
+ | :- | :- | :- |
91
+ | Instruction Extra Hard | 5.7 | 5.9 |
92
+ | Instruction Hard | 5.0 | 5.2 |
93
+ | JSON Structure Output | 1.9 | 60.1 |
94
+ | XML Structure Output | 47.8 | 52.9 |
95
+ | GPQA | 25.9 | 29.7 |
96
+ | MMLU | 68.1 | 69.7 |
97
+ | **Average** | **25.7** | **37.3** |
98
+
99
+ RULER: a retrieval-based benchmark for long context understanding
100
+
101
+ | Model | 4K | 8K | 16K | 32K | 64K | 128K | Average |
102
+ | :-------------------| :------| :------| :------| :------| :------| :------| :---------|
103
+ | Original | 86.7 | 78.1 | 75.6 | 70.3 | 58.9 | 43.3 | **68.8** |
104
+ | June 2024 Update | 92.4 | 91.1 | 90.8 | 87.9 | 79.8 | 65.6 | **84.6** |
105
+
106
+ RepoQA: a benchmark for long context code understanding
107
+
108
+ | Model | Python | C++ | Rust | Java | TypeScript | Average |
109
+ | :-------------------| :--------| :-----| :------| :------| :------------| :---------|
110
+ | Original | 27 | 29 | 40 | 33 | 33 | **32.4** |
111
+ | June 2024 Update | 85 | 63 | 72 | 93 | 72 | **77** |
112
+
113
+ Notes: if users would like to check out the previous version, use the git commit id **bb5bf1e4001277a606e11debca0ef80323e5f824**. For the model conversion, e.g. GGUF and other formats, we invite the community to experiment with various approaches and share your valuable feedback. Let's innovate together!
114
+
115
+ ## How to Use
116
+
117
+ Phi-3 Mini-128K-Instruct has been integrated in the development version (4.41.3) of `transformers`. Until the official version is released through `pip`, ensure that you are doing one of the following:
118
+
119
+ - When loading the model, ensure that `trust_remote_code=True` is passed as an argument of the `from_pretrained()` function.
120
+
121
+ - 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.
122
+
123
+ The current `transformers` version can be verified with: `pip list | grep transformers`.
124
+
125
+ Examples of required packages:
126
+
127
+ ```
128
+ flash_attn==2.5.8
129
+ torch==2.3.1
130
+ accelerate==0.31.0
131
+ transformers==4.41.2
132
+ ```
133
+
134
+ Phi-3 Mini-128K-Instruct is also available in [Azure AI Studio](https://aka.ms/try-phi3)
135
+
136
+ ### Tokenizer
137
+
138
+ Phi-3 Mini-128K-Instruct supports a vocabulary size of up to `32064` tokens. The [tokenizer files](https://huggingface.co/justinthelaw/Phi-3-mini-128k-instruct-4bit-128g/blob/main/added_tokens.json) already provide placeholder tokens that can be used for downstream fine-tuning, but they can also be extended up to the model's vocabulary size.
139
+
140
+ ### Chat Format
141
+
142
+ Given the nature of the training data, the Phi-3 Mini-128K-Instruct model is best suited for prompts using the chat format as follows.
143
+ You can provide the prompt as a question with a generic template as follow:
144
+
145
+ ```markdown
146
+ <|system|>
147
+ You are a helpful assistant.<|end|>
148
+ <|user|>
149
+ Question?<|end|>
150
+ <|assistant|>
151
+ ```
152
+
153
+ For example:
154
+
155
+ ```markdown
156
+ <|system|>
157
+ You are a helpful assistant.<|end|>
158
+ <|user|>
159
+ How to explain Internet for a medieval knight?<|end|>
160
+ <|assistant|>
161
+ ```
162
+
163
+ where the model generates the text after `<|assistant|>` . In case of few-shots prompt, the prompt can be formatted as the following:
164
+
165
+ ```markdown
166
+ <|system|>
167
+ You are a helpful travel assistant.<|end|>
168
+ <|user|>
169
+ I am going to Paris, what should I see?<|end|>
170
+ <|assistant|>
171
+ Paris, the capital of France, is known for its stunning architecture, art museums, historical landmarks, and romantic atmosphere. Here are some of the top attractions to see in Paris:\n\n1. The Eiffel Tower: The iconic Eiffel Tower is one of the most recognizable landmarks in the world and offers breathtaking views of the city.\n2. The Louvre Museum: The Louvre is one of the world's largest and most famous museums, housing an impressive collection of art and artifacts, including the Mona Lisa.\n3. Notre-Dame Cathedral: This beautiful cathedral is one of the most famous landmarks in Paris and is known for its Gothic architecture and stunning stained glass windows.\n\nThese are just a few of the many attractions that Paris has to offer. With so much to see and do, it's no wonder that Paris is one of the most popular tourist destinations in the world."<|end|>
172
+ <|user|>
173
+ What is so great about #1?<|end|>
174
+ <|assistant|>
175
+ ```
176
+
177
+ ### Sample inference code
178
+
179
+ This code snippets show how to get quickly started with running the model on a GPU:
180
+
181
+ ```python
182
+ import torch
183
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
184
+
185
+ torch.random.manual_seed(0)
186
+ model = AutoModelForCausalLM.from_pretrained(
187
+ "justinthelaw/Phi-3-mini-128k-instruct-4bit-128g",
188
+ device_map="cuda",
189
+ torch_dtype="auto",
190
+ trust_remote_code=True,
191
+ )
192
+
193
+ tokenizer = AutoTokenizer.from_pretrained("justinthelaw/Phi-3-mini-128k-instruct-4bit-128g")
194
+
195
+ messages = [
196
+ {"role": "system", "content": "You are a helpful AI assistant."},
197
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
198
+ {"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."},
199
+ {"role": "user", "content": "What about solving an 2x + 3 = 7 equation?"},
200
+ ]
201
+
202
+ pipe = pipeline(
203
+ "text-generation",
204
+ model=model,
205
+ tokenizer=tokenizer,
206
+ )
207
+
208
+ generation_args = {
209
+ "max_new_tokens": 500,
210
+ "return_full_text": False,
211
+ "temperature": 0.0,
212
+ "do_sample": False,
213
+ }
214
+
215
+ output = pipe(messages, **generation_args)
216
+ print(output[0]['generated_text'])
217
+ ```
218
+
219
+ Notes: If you want to use flash attention, call _AutoModelForCausalLM.from_pretrained()_ with _attn_implementation="flash_attention_2"_
220
+
221
+ ## Responsible AI Considerations
222
+
223
+ 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:
224
+
225
+ - 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.
226
+ - 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.
227
+ - 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.
228
+ - Information Reliability: Language models can generate nonsensical content or fabricate content that might sound reasonable but is inaccurate or outdated.
229
+ - 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.
230
+
231
+ 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:
232
+
233
+ - 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.
234
+ - 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.
235
+ - 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).
236
+ - Generation of Harmful Content: Developers should assess outputs for their context and use available safety classifiers or custom solutions appropriate for their use case.
237
+ - 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.
238
+
239
+ ## Training
240
+
241
+ ### Model
242
+
243
+ - Architecture: Phi-3 Mini-128K-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.
244
+ - Inputs: Text. It is best suited for prompts using chat format.
245
+ - Context length: 128K tokens
246
+ - GPUs: 512 H100-80G
247
+ - Training time: 10 days
248
+ - Training data: 4.9T tokens
249
+ - Outputs: Generated text in response to the input
250
+ - Dates: Our models were trained between May and June 2024
251
+ - 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.
252
+ - Release dates: June, 2024.
253
+
254
+ ### Datasets
255
+
256
+ Our training data includes a wide variety of sources, totaling 4.9 trillion tokens, and is a combination of
257
+
258
+ 1) Publicly available documents filtered rigorously for quality, selected high-quality educational data, and code;
259
+ 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.);
260
+ 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.
261
+
262
+ We are focusing on the quality of data that could potentially improve the reasoning ability for the model, and we filter the publicly available documents to contain the correct level of knowledge. As an example, the result of a game in premier league in a particular day might be good training data for frontier models, but we need to remove such information to leave more model capacity for reasoning for the small size models. More details about data can be found in the [Phi-3 Technical Report](https://aka.ms/phi3-tech-report).
263
+
264
+ ### Fine-tuning
265
+
266
+ A basic example of multi-GPUs supervised fine-tuning (SFT) with TRL and Accelerate modules is provided [here](https://huggingface.co/justinthelaw/Phi-3-mini-128k-instruct-4bit-128g/resolve/main/sample_finetune.py).
267
+
268
+ ## Benchmarks
269
+
270
+ We report the results under completion format for Phi-3-Mini-128K-Instruct on standard open-source benchmarks measuring the model's reasoning ability (both common sense reasoning and logical reasoning). We compare to Mistral-7b-v0.1, Mixtral-8x7b, Gemma 7B, Llama-3-8B-Instruct, and GPT-3.5.
271
+
272
+ 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.
273
+
274
+ As is now standard, we use few-shot prompts to evaluate the models, at temperature 0.
275
+ 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.
276
+ 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.
277
+
278
+ The number of k–shot examples is listed per-benchmark.
279
+
280
+ | Category | Benchmark | Phi-3-Mini-128K-Ins | Gemma-7B | Mistral-7B | Mixtral-8x7B | Llama-3-8B-Ins | GPT3.5-Turbo-1106 |
281
+ | :----------| :-----------| :---------------------| :----------| :------------| :--------------| :----------------| :-------------------|
282
+ | Popular aggregated benchmark | AGI Eval <br>5-shot| 39.5 | 42.1 | 35.1 | 45.2 | 42 | 48.4 |
283
+ | | MMLU <br>5-shot | 69.7 | 63.6 | 61.7 | 70.5 | 66.5 | 71.4 |
284
+ | | BigBench Hard <br>3-shot | 72.1 | 59.6 | 57.3 | 69.7 | 51.5 | 68.3 |
285
+ | Language Understanding | ANLI <br>7-shot | 52.3 | 48.7 | 47.1 | 55.2 | 57.3 | 58.1 |
286
+ | | HellaSwag <br>5-shot | 70.5 | 49.8 | 58.5 | 70.4 | 71.1 | 78.8 |
287
+ | Reasoning | ARC Challenge <br>10-shot | 85.5 | 78.3 | 78.6 | 87.3 | 82.8 | 87.4 |
288
+ | | BoolQ <br>0-shot | 77.1 | 66 | 72.2 | 76.6 | 80.9 | 79.1 |
289
+ | | MedQA <br>2-shot | 56.4 | 49.6 | 50 | 62.2 | 60.5 | 63.4 |
290
+ | | OpenBookQA <br>10-shot | 78.8 | 78.6 | 79.8 | 85.8 | 82.6 | 86 |
291
+ | | PIQA <br>5-shot | 80.1 | 78.1 | 77.7 | 86 | 75.7 | 86.6 |
292
+ | | GPQA <br>0-shot | 29.7 | 2.9 | 15 | 6.9 | 32.4 | 29.9 |
293
+ | | Social IQA <br>5-shot | 74.7 | 65.5 | 74.6 | 75.9 | 73.9 | 68.3 |
294
+ | | TruthfulQA (MC2) <br>10-shot | 64.8 | 52.1 | 53 | 60.1 | 63.2 | 67.7 |
295
+ | | WinoGrande <br>5-shot | 71.0 | 55.6 | 54.2 | 62 | 65 | 68.8 |
296
+ | Factual Knowledge | TriviaQA <br>5-shot | 57.8 | 72.3 | 75.2 | 82.2 | 67.7 | 85.8 |
297
+ | Math | GSM8K CoTT <br>8-shot | 85.3 | 59.8 | 46.4 | 64.7 | 77.4 | 78.1 |
298
+ | Code Generation | HumanEval <br>0-shot | 60.4 | 34.1 | 28.0 | 37.8 | 60.4 | 62.2 |
299
+ | | MBPP <br>3-shot | 70.0 | 51.5 | 50.8 | 60.2 | 67.7 | 77.8 |
300
+ | **Average** | | **66.4** | **56.0** | **56.4** | **64.4** | **65.5** | **70.3** |
301
+
302
+ **Long Context**: Phi-3 Mini-128K-Instruct supports 128K context length, therefore the model is capable of several long context tasks including long document/meeting summarization, long document QA.
303
+
304
+ | Benchmark | Phi-3 Mini-128K-Instruct | Mistral-7B | Mixtral 8x7B | LLaMA-3-8B-Instruct |
305
+ | :---------------| :--------------------------|:------------|:--------------|:---------------------|
306
+ | GovReport | 25.3 | 4.9 | 20.3 | 10.3 |
307
+ | QMSum | 21.9 | 15.5 | 20.6 | 2.9 |
308
+ | Qasper | 41.6 | 23.5 | 26.6 | 8.1 |
309
+ | SQuALITY | 24.1 | 14.7 | 16.2 | 25 |
310
+ | SummScreenFD | 16.8 | 9.3 | 11.3 | 5.1 |
311
+ | **Average** | **25.9** | **13.6** | **19.0** | **10.3** |
312
+
313
+ We take a closer look at different categories across 100 public benchmark datasets at the table below:
314
+
315
+ | Category | Phi-3-Mini-128K-Instruct | Gemma-7B | Mistral-7B | Mixtral 8x7B | Llama-3-8B-Instruct | GPT-3.5-Turbo |
316
+ |:----------|:--------------------------|:----------|:------------|:--------------|:---------------------|:---------------|
317
+ | Popular aggregated benchmark | 60.6 | 59.4 | 56.5 | 66.2 | 59.9 | 67.0 |
318
+ | Reasoning | 69.4 | 60.3 | 62.8 | 68.1 | 69.6 | 71.7 |
319
+ | Language understanding | 57.5 | 57.6 | 52.5 | 66.1 | 63.2 | 67.7 |
320
+ | Code generation | 61.0 | 45.6 | 42.9 | 52.7 | 56.4 | 70.4 |
321
+ | Math | 51.6 | 35.8 | 25.4 | 40.3 | 41.1 | 52.8 |
322
+ | Factual knowledge | 35.8 | 46.7 | 49.8 | 58.6 | 43.1 | 63.4 |
323
+ | Multilingual | 56.4 | 66.5 | 57.4 | 66.7 | 66.6 | 71.0 |
324
+ | Robustness | 61.1 | 38.4 | 40.6 | 51.0 | 64.5 | 69.3 |
325
+
326
+ Overall, the model with only 3.8B-param achieves a similar level of language understanding and reasoning ability as much larger models. However, it is still fundamentally limited by its size for certain tasks. The model simply does not have the capacity to store too much world knowledge, which can be seen for example with low performance on TriviaQA. However, we believe such weakness can be resolved by augmenting Phi-3-Mini with a search engine.
327
+
328
+ ## Cross Platform Support
329
+
330
+ [ONNX runtime](https://onnxruntime.ai/blogs/accelerating-phi-3) now supports Phi-3 mini models across platforms and hardware.
331
+
332
+ 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 GPU acceleration is supported for Windows desktops GPUs (AMD, Intel, and NVIDIA).
333
+
334
+ Along with DML, ONNX Runtime provides cross platform support for Phi3 mini across a range of devices CPU, GPU, and mobile.
335
+
336
+ Here are some of the optimized configurations we have added:
337
+
338
+ 1. ONNX models for int4 DML: Quantized to int4 via AWQ
339
+ 2. ONNX model for fp16 CUDA
340
+ 3. ONNX model for int4 CUDA: Quantized to int4 via RTN
341
+ 4. ONNX model for int4 CPU and Mobile: Quantized to int4 via RTN
342
+
343
+ ## Software
344
+
345
+ - [PyTorch](https://github.com/pytorch/pytorch)
346
+ - [Transformers](https://github.com/huggingface/transformers)
347
+ - [Flash-Attention](https://github.com/HazyResearch/flash-attention)
348
+
349
+ ## Hardware
350
+
351
+ Note that by default, the Phi-3 Mini-128K-Instruct model uses flash attention, which requires certain types of GPU hardware to run. We have tested on the following GPU types:
352
+
353
+ - NVIDIA A100
354
+ - NVIDIA A6000
355
+ - NVIDIA H100
356
+
357
+ If you want to run the model on:
358
+
359
+ - NVIDIA V100 or earlier generation GPUs: call AutoModelForCausalLM.from_pretrained() with attn_implementation="eager"
360
+ - Optimized inference on GPU, CPU, and Mobile: use the **ONNX** models [128K](https://aka.ms/phi3-mini-128k-instruct-onnx)
361
+
362
+ ## License
363
+
364
+ The model is licensed under the [MIT license](https://huggingface.co/microsoft/Phi-3-mini-128k/resolve/main/LICENSE).
365
+
366
+ ## Trademarks
367
+
368
+ 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.
config.json CHANGED
@@ -1,8 +1,6 @@
1
  {
2
  "_name_or_path": "microsoft/Phi-3-mini-128k-instruct",
3
- "architectures": [
4
- "Phi3ForCausalLM"
5
- ],
6
  "attention_bias": false,
7
  "attention_dropout": 0.0,
8
  "auto_map": {
@@ -41,107 +39,41 @@
41
  "true_sequential": true
42
  },
43
  "resid_pdrop": 0.0,
44
- "rms_norm_eps": 1e-05,
45
  "rope_scaling": {
46
  "long_factor": [
47
- 1.0700000524520874,
48
- 1.1200000047683716,
49
- 1.149999976158142,
50
- 1.4199999570846558,
51
- 1.5699999332427979,
52
- 1.7999999523162842,
53
- 2.129999876022339,
54
- 2.129999876022339,
55
- 3.009999990463257,
56
- 5.910000324249268,
57
- 6.950000286102295,
58
- 9.070000648498535,
59
- 9.930000305175781,
60
- 10.710000038146973,
61
- 11.130000114440918,
62
- 14.609999656677246,
63
- 15.409998893737793,
64
- 19.809999465942383,
65
- 37.279998779296875,
66
- 38.279998779296875,
67
- 38.599998474121094,
68
- 40.12000274658203,
69
- 46.20000457763672,
70
- 50.940006256103516,
71
- 53.66000747680664,
72
- 54.9373893737793,
73
- 56.89738845825195,
74
- 57.28738784790039,
75
- 59.98738479614258,
76
- 60.86738586425781,
77
- 60.887386322021484,
78
- 61.71739196777344,
79
- 62.91739273071289,
80
- 62.957393646240234,
81
- 63.41739273071289,
82
- 63.8173942565918,
83
- 63.83739471435547,
84
- 63.897396087646484,
85
- 63.93739700317383,
86
- 64.06739807128906,
87
- 64.11434936523438,
88
- 64.12435150146484,
89
- 64.15435028076172,
90
- 64.19435119628906,
91
- 64.24435424804688,
92
- 64.57435607910156,
93
- 64.69000244140625,
94
- 64.76000213623047
95
  ],
96
  "short_factor": [
97
- 1.1,
98
- 1.1,
99
- 1.1,
100
- 1.3000000000000003,
101
- 1.3500000000000003,
102
- 1.3500000000000003,
103
- 1.4000000000000004,
104
- 1.5500000000000005,
105
- 2.000000000000001,
106
- 2.000000000000001,
107
- 2.000000000000001,
108
- 2.000000000000001,
109
- 2.000000000000001,
110
- 2.000000000000001,
111
- 2.000000000000001,
112
- 2.000000000000001,
113
- 2.000000000000001,
114
- 2.000000000000001,
115
- 2.000000000000001,
116
- 2.000000000000001,
117
- 2.000000000000001,
118
- 2.000000000000001,
119
- 2.000000000000001,
120
- 2.000000000000001,
121
- 2.000000000000001,
122
- 2.0500000000000007,
123
- 2.0500000000000007,
124
- 2.0500000000000007,
125
- 2.0500000000000007,
126
- 2.0500000000000007,
127
- 2.0500000000000007,
128
- 2.1000000000000005,
129
- 2.1000000000000005,
130
- 2.1500000000000004,
131
- 2.25,
132
- 2.25,
133
- 2.25,
134
- 2.25,
135
- 2.25,
136
- 2.3999999999999995,
137
- 2.4499999999999993,
138
- 2.499999999999999,
139
- 2.6999999999999984,
140
- 2.6999999999999984,
141
- 2.7499999999999982,
142
- 2.799999999999998,
143
- 2.8999999999999977,
144
- 3.049999999999997
145
  ],
146
  "type": "longrope"
147
  },
 
1
  {
2
  "_name_or_path": "microsoft/Phi-3-mini-128k-instruct",
3
+ "architectures": ["Phi3ForCausalLM"],
 
 
4
  "attention_bias": false,
5
  "attention_dropout": 0.0,
6
  "auto_map": {
 
39
  "true_sequential": true
40
  },
41
  "resid_pdrop": 0.0,
42
+ "rms_norm_eps": 1e-5,
43
  "rope_scaling": {
44
  "long_factor": [
45
+ 1.0700000524520874, 1.1200000047683716, 1.149999976158142,
46
+ 1.4199999570846558, 1.5699999332427979, 1.7999999523162842,
47
+ 2.129999876022339, 2.129999876022339, 3.009999990463257,
48
+ 5.910000324249268, 6.950000286102295, 9.070000648498535,
49
+ 9.930000305175781, 10.710000038146973, 11.130000114440918,
50
+ 14.609999656677246, 15.409998893737793, 19.809999465942383,
51
+ 37.279998779296875, 38.279998779296875, 38.599998474121094,
52
+ 40.12000274658203, 46.20000457763672, 50.940006256103516,
53
+ 53.66000747680664, 54.9373893737793, 56.89738845825195, 57.28738784790039,
54
+ 59.98738479614258, 60.86738586425781, 60.887386322021484,
55
+ 61.71739196777344, 62.91739273071289, 62.957393646240234,
56
+ 63.41739273071289, 63.8173942565918, 63.83739471435547,
57
+ 63.897396087646484, 63.93739700317383, 64.06739807128906,
58
+ 64.11434936523438, 64.12435150146484, 64.15435028076172,
59
+ 64.19435119628906, 64.24435424804688, 64.57435607910156,
60
+ 64.69000244140625, 64.76000213623047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  ],
62
  "short_factor": [
63
+ 1.1, 1.1, 1.1, 1.3000000000000003, 1.3500000000000003, 1.3500000000000003,
64
+ 1.4000000000000004, 1.5500000000000005, 2.000000000000001,
65
+ 2.000000000000001, 2.000000000000001, 2.000000000000001,
66
+ 2.000000000000001, 2.000000000000001, 2.000000000000001,
67
+ 2.000000000000001, 2.000000000000001, 2.000000000000001,
68
+ 2.000000000000001, 2.000000000000001, 2.000000000000001,
69
+ 2.000000000000001, 2.000000000000001, 2.000000000000001,
70
+ 2.000000000000001, 2.0500000000000007, 2.0500000000000007,
71
+ 2.0500000000000007, 2.0500000000000007, 2.0500000000000007,
72
+ 2.0500000000000007, 2.1000000000000005, 2.1000000000000005,
73
+ 2.1500000000000004, 2.25, 2.25, 2.25, 2.25, 2.25, 2.3999999999999995,
74
+ 2.4499999999999993, 2.499999999999999, 2.6999999999999984,
75
+ 2.6999999999999984, 2.7499999999999982, 2.799999999999998,
76
+ 2.8999999999999977, 3.049999999999997
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  ],
78
  "type": "longrope"
79
  },
configuration_phi3.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ Phi-3 model configuration"""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json",
27
+ "microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class Phi3Config(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the
36
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32064):
43
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Phi3Model`].
45
+ hidden_size (`int`, *optional*, defaults to 3072):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 8192):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
62
+ Dropout probability for mlp outputs.
63
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the embeddings.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio after computing the attention scores.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model might ever be used with.
71
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
73
+ original RoPE embeddings when using long scaling.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon value used for the RMSNorm.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`dict`, *optional*):
86
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ The id of the "beginning-of-sequence" token.
92
+ eos_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the "end-of-sequence" token.
94
+ pad_token_id (`int`, *optional*, defaults to 32000):
95
+ The id of the padding token.
96
+ sliding_window (`int`, *optional*):
97
+ Sliding window attention window size. If `None`, no sliding window is applied.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import Phi3Model, Phi3Config
103
+
104
+ >>> # Initializing a Phi-3 style configuration
105
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = Phi3Model(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32064,
120
+ hidden_size=3072,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="silu",
129
+ max_position_embeddings=4096,
130
+ original_max_position_embeddings=4096,
131
+ initializer_range=0.02,
132
+ rms_norm_eps=1e-5,
133
+ use_cache=True,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ bos_token_id=1,
138
+ eos_token_id=32000,
139
+ pad_token_id=32000,
140
+ sliding_window=None,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.hidden_size = hidden_size
145
+ self.intermediate_size = intermediate_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.resid_pdrop = resid_pdrop
154
+ self.embd_pdrop = embd_pdrop
155
+ self.attention_dropout = attention_dropout
156
+ self.hidden_act = hidden_act
157
+ self.max_position_embeddings = max_position_embeddings
158
+ self.original_max_position_embeddings = original_max_position_embeddings
159
+ self.initializer_range = initializer_range
160
+ self.rms_norm_eps = rms_norm_eps
161
+ self.use_cache = use_cache
162
+ self.rope_theta = rope_theta
163
+ self.rope_scaling = rope_scaling
164
+ self._rope_scaling_adjustment()
165
+ self._rope_scaling_validation()
166
+ self.sliding_window = sliding_window
167
+
168
+ super().__init__(
169
+ bos_token_id=bos_token_id,
170
+ eos_token_id=eos_token_id,
171
+ pad_token_id=pad_token_id,
172
+ tie_word_embeddings=tie_word_embeddings,
173
+ **kwargs,
174
+ )
175
+
176
+ def _rope_scaling_adjustment(self):
177
+ """
178
+ Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
179
+ """
180
+ if self.rope_scaling is None:
181
+ return
182
+
183
+ rope_scaling_type = self.rope_scaling.get("type", None)
184
+
185
+ # For backward compatibility if previous version used "su" or "yarn"
186
+ if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
187
+ self.rope_scaling["type"] = "longrope"
188
+
189
+ def _rope_scaling_validation(self):
190
+ """
191
+ Validate the `rope_scaling` configuration.
192
+ """
193
+ if self.rope_scaling is None:
194
+ return
195
+
196
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
197
+ raise ValueError(
198
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
199
+ f"got {self.rope_scaling}"
200
+ )
201
+ rope_scaling_type = self.rope_scaling.get("type", None)
202
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
203
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
204
+ if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
205
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
206
+ if not (
207
+ isinstance(rope_scaling_short_factor, list)
208
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
209
+ ):
210
+ raise ValueError(
211
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
212
+ )
213
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
214
+ raise ValueError(
215
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
216
+ )
217
+ if not (
218
+ isinstance(rope_scaling_long_factor, list)
219
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
220
+ ):
221
+ raise ValueError(
222
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
223
+ )
224
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
225
+ raise ValueError(
226
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
227
+ )
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "do_sample": true,
5
+ "eos_token_id": [32000, 32001, 32007],
6
+ "pad_token_id": 32000,
7
+ "transformers_version": "4.42.3"
8
+ }
modeling_phi3.py ADDED
@@ -0,0 +1,1563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi-3 model."""
17
+
18
+ import inspect
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_phi3 import Phi3Config
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
54
+ # if is_flash_attn_2_available():
55
+ _flash_supports_window_size = False
56
+ try:
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
61
+ except ImportError as error:
62
+ logger.warning(
63
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
64
+ )
65
+ if not _flash_supports_window_size:
66
+ logger.warning(
67
+ "Current `flash-attention` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
68
+ )
69
+
70
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
71
+ _CONFIG_FOR_DOC = "Phi3Config"
72
+
73
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
74
+ "microsoft/Phi-3-mini-4k-instruct",
75
+ "microsoft/Phi-3-mini-128k-instruct",
76
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
77
+ ]
78
+
79
+
80
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
81
+ class Phi3RMSNorm(nn.Module):
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ """
84
+ Phi3RMSNorm is equivalent to T5LayerNorm
85
+ """
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+ self.variance_epsilon = eps
89
+
90
+ def forward(self, hidden_states):
91
+ input_dtype = hidden_states.dtype
92
+ hidden_states = hidden_states.to(torch.float32)
93
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
94
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
95
+ return self.weight * hidden_states.to(input_dtype)
96
+
97
+
98
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
99
+ def _get_unpad_data(attention_mask):
100
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
101
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
102
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
103
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
104
+ return (
105
+ indices,
106
+ cu_seqlens,
107
+ max_seqlen_in_batch,
108
+ )
109
+
110
+
111
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
112
+ class Phi3RotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ self.register_buffer("inv_freq", None, persistent=False)
120
+
121
+ @torch.no_grad()
122
+ def forward(self, x, position_ids, seq_len=None):
123
+ # x: [bs, num_attention_heads, seq_len, head_size]
124
+ if self.inv_freq is None:
125
+ self.inv_freq = 1.0 / (
126
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
127
+ )
128
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
129
+ position_ids_expanded = position_ids[:, None, :].float()
130
+ # Force float32 since bfloat16 loses precision on long contexts
131
+ # See https://github.com/huggingface/transformers/pull/29285
132
+ device_type = x.device.type
133
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
134
+ with torch.autocast(device_type=device_type, enabled=False):
135
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ cos = emb.cos()
138
+ sin = emb.sin()
139
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
140
+
141
+
142
+ class Phi3LongRoPEScaledRotaryEmbedding(Phi3RotaryEmbedding):
143
+ def __init__(self, dim, config, device=None):
144
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
145
+
146
+ self.short_factor = config.rope_scaling["short_factor"]
147
+ self.long_factor = config.rope_scaling["long_factor"]
148
+ self.original_max_position_embeddings = config.original_max_position_embeddings
149
+
150
+ @torch.no_grad()
151
+ def forward(self, x, position_ids, seq_len=None):
152
+ seq_len = torch.max(position_ids) + 1
153
+ if seq_len > self.original_max_position_embeddings:
154
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
155
+ else:
156
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
157
+
158
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
159
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
160
+
161
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
162
+ position_ids_expanded = position_ids[:, None, :].float()
163
+
164
+ # Force float32 since bfloat16 loses precision on long contexts
165
+ # See https://github.com/huggingface/transformers/pull/29285
166
+ device_type = x.device.type
167
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
168
+ with torch.autocast(device_type=device_type, enabled=False):
169
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
170
+ emb = torch.cat((freqs, freqs), dim=-1)
171
+
172
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
173
+ if scale <= 1.0:
174
+ scaling_factor = 1.0
175
+ else:
176
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
177
+
178
+ cos = emb.cos() * scaling_factor
179
+ sin = emb.sin() * scaling_factor
180
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
181
+
182
+
183
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
184
+ def rotate_half(x):
185
+ """Rotates half the hidden dims of the input."""
186
+ x1 = x[..., : x.shape[-1] // 2]
187
+ x2 = x[..., x.shape[-1] // 2 :]
188
+ return torch.cat((-x2, x1), dim=-1)
189
+
190
+
191
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
192
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
193
+ """Applies Rotary Position Embedding to the query and key tensors.
194
+
195
+ Args:
196
+ q (`torch.Tensor`): The query tensor.
197
+ k (`torch.Tensor`): The key tensor.
198
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
199
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
200
+ position_ids (`torch.Tensor`, *optional*):
201
+ Deprecated and unused.
202
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
203
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
204
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
205
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
206
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
207
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
208
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
209
+ Returns:
210
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
211
+ """
212
+ cos = cos.unsqueeze(unsqueeze_dim)
213
+ sin = sin.unsqueeze(unsqueeze_dim)
214
+ q_embed = (q * cos) + (rotate_half(q) * sin)
215
+ k_embed = (k * cos) + (rotate_half(k) * sin)
216
+ return q_embed, k_embed
217
+
218
+
219
+ class Phi3MLP(nn.Module):
220
+ def __init__(self, config):
221
+ super().__init__()
222
+
223
+ self.config = config
224
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
225
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
226
+
227
+ self.activation_fn = ACT2FN[config.hidden_act]
228
+
229
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
230
+ up_states = self.gate_up_proj(hidden_states)
231
+
232
+ gate, up_states = up_states.chunk(2, dim=-1)
233
+ up_states = up_states * self.activation_fn(gate)
234
+
235
+ return self.down_proj(up_states)
236
+
237
+
238
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
239
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
240
+ """
241
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
242
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
243
+ """
244
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
245
+ if n_rep == 1:
246
+ return hidden_states
247
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
248
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
249
+
250
+
251
+ class Phi3Attention(nn.Module):
252
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
253
+
254
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
255
+ super().__init__()
256
+ self.config = config
257
+ self.layer_idx = layer_idx
258
+ if layer_idx is None:
259
+ logger.warning_once(
260
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
261
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
262
+ "when creating this class."
263
+ )
264
+
265
+ self.attention_dropout = config.attention_dropout
266
+ self.hidden_size = config.hidden_size
267
+ self.num_heads = config.num_attention_heads
268
+ self.head_dim = self.hidden_size // self.num_heads
269
+ self.num_key_value_heads = config.num_key_value_heads
270
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
271
+ self.max_position_embeddings = config.max_position_embeddings
272
+ self.original_max_position_embeddings = config.original_max_position_embeddings
273
+ self.rope_theta = config.rope_theta
274
+ self.rope_scaling = config.rope_scaling
275
+ self.is_causal = True
276
+
277
+ if (self.head_dim * self.num_heads) != self.hidden_size:
278
+ raise ValueError(
279
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
280
+ f" and `num_heads`: {self.num_heads})."
281
+ )
282
+
283
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
284
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
285
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
286
+ self._init_rope()
287
+
288
+ def _init_rope(self):
289
+ if self.rope_scaling is None:
290
+ self.rotary_emb = Phi3RotaryEmbedding(
291
+ self.head_dim,
292
+ max_position_embeddings=self.max_position_embeddings,
293
+ base=self.rope_theta,
294
+ )
295
+ else:
296
+ scaling_type = self.config.rope_scaling["type"]
297
+ if scaling_type == "longrope":
298
+ self.rotary_emb = Phi3LongRoPEScaledRotaryEmbedding(self.head_dim, self.config)
299
+ else:
300
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
301
+
302
+ def forward(
303
+ self,
304
+ hidden_states: torch.Tensor,
305
+ attention_mask: Optional[torch.Tensor] = None,
306
+ position_ids: Optional[torch.LongTensor] = None,
307
+ past_key_value: Optional[Cache] = None,
308
+ output_attentions: bool = False,
309
+ use_cache: bool = False,
310
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
311
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
312
+
313
+ bsz, q_len, _ = hidden_states.size()
314
+
315
+ qkv = self.qkv_proj(hidden_states)
316
+ query_pos = self.num_heads * self.head_dim
317
+ query_states = qkv[..., :query_pos]
318
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
319
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
320
+
321
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
322
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
323
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
324
+
325
+ kv_seq_len = key_states.shape[-2]
326
+ if past_key_value is not None:
327
+ if self.layer_idx is None:
328
+ raise ValueError(
329
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
330
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
331
+ "with a layer index."
332
+ )
333
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
334
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
335
+
336
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
337
+
338
+ if past_key_value is not None:
339
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
340
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
341
+
342
+ # repeat k/v heads if n_kv_heads < n_heads
343
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
344
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
345
+
346
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
347
+
348
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
349
+ raise ValueError(
350
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
351
+ f" {attn_weights.size()}"
352
+ )
353
+
354
+ if attention_mask is not None:
355
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
356
+ raise ValueError(
357
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
358
+ )
359
+ attn_weights = attn_weights + attention_mask
360
+
361
+ # upcast attention to fp32
362
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
363
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
364
+
365
+ attn_output = torch.matmul(attn_weights, value_states)
366
+
367
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
368
+ raise ValueError(
369
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
370
+ f" {attn_output.size()}"
371
+ )
372
+
373
+ attn_output = attn_output.transpose(1, 2).contiguous()
374
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
375
+
376
+ attn_output = self.o_proj(attn_output)
377
+
378
+ if not output_attentions:
379
+ attn_weights = None
380
+
381
+ return attn_output, attn_weights, past_key_value
382
+
383
+
384
+ class Phi3FlashAttention2(Phi3Attention):
385
+ """
386
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
387
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
388
+ flash attention and deal with padding tokens in case the input contains any of them.
389
+ """
390
+
391
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
392
+ def __init__(self, *args, **kwargs):
393
+ super().__init__(*args, **kwargs)
394
+
395
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
396
+ # 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.
397
+ # 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).
398
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
399
+
400
+ def forward(
401
+ self,
402
+ hidden_states: torch.Tensor,
403
+ attention_mask: Optional[torch.LongTensor] = None,
404
+ position_ids: Optional[torch.LongTensor] = None,
405
+ past_key_value: Optional[Cache] = None,
406
+ output_attentions: bool = False,
407
+ use_cache: bool = False,
408
+ **kwargs,
409
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
410
+ # Phi3FlashAttention2 attention does not support output_attentions
411
+
412
+ if not _flash_supports_window_size:
413
+ logger.warning_once(
414
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
415
+ )
416
+ raise ValueError("The current flash attention version does not support sliding window attention.")
417
+
418
+ output_attentions = False
419
+
420
+ if "padding_mask" in kwargs:
421
+ warnings.warn(
422
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
423
+ )
424
+
425
+ # overwrite attention_mask with padding_mask
426
+ attention_mask = kwargs.pop("padding_mask")
427
+
428
+ bsz, q_len, _ = hidden_states.size()
429
+
430
+ qkv = self.qkv_proj(hidden_states)
431
+ query_pos = self.num_heads * self.head_dim
432
+ query_states = qkv[..., :query_pos]
433
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
434
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
435
+
436
+ # Flash attention requires the input to have the shape
437
+ # batch_size x seq_length x head_dim x hidden_dim
438
+ # therefore we just need to keep the original shape
439
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
440
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
441
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
442
+
443
+ kv_seq_len = key_states.shape[-2]
444
+ if past_key_value is not None:
445
+ if self.layer_idx is None:
446
+ raise ValueError(
447
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
448
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
449
+ "with a layer index."
450
+ )
451
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
452
+
453
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
454
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
455
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
456
+
457
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
458
+
459
+ use_sliding_windows = (
460
+ _flash_supports_window_size
461
+ and getattr(self.config, "sliding_window", None) is not None
462
+ and kv_seq_len > self.config.sliding_window
463
+ )
464
+
465
+ if past_key_value is not None:
466
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
467
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
468
+ if (
469
+ getattr(self.config, "sliding_window", None) is not None
470
+ and kv_seq_len > self.config.sliding_window
471
+ and cache_has_contents
472
+ ):
473
+ slicing_tokens = 1 - self.config.sliding_window
474
+
475
+ past_key = past_key_value[self.layer_idx][0]
476
+ past_value = past_key_value[self.layer_idx][1]
477
+
478
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
479
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
480
+
481
+ if past_key.shape[-2] != self.config.sliding_window - 1:
482
+ raise ValueError(
483
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
484
+ f" {past_key.shape}"
485
+ )
486
+
487
+ if attention_mask is not None:
488
+ attention_mask = attention_mask[:, slicing_tokens:]
489
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
490
+
491
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
492
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
493
+
494
+ # repeat k/v heads if n_kv_heads < n_heads
495
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
496
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
497
+
498
+ attn_dropout = self.attention_dropout if self.training else 0.0
499
+
500
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
501
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
502
+ # cast them back in the correct dtype just to be sure everything works as expected.
503
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
504
+ # in fp32.
505
+
506
+ if query_states.dtype == torch.float32:
507
+ if torch.is_autocast_enabled():
508
+ target_dtype = torch.get_autocast_gpu_dtype()
509
+ # Handle the case where the model is quantized
510
+ elif hasattr(self.config, "_pre_quantization_dtype"):
511
+ target_dtype = self.config._pre_quantization_dtype
512
+ else:
513
+ target_dtype = self.qkv_proj.weight.dtype
514
+
515
+ logger.warning_once(
516
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
517
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
518
+ f" {target_dtype}."
519
+ )
520
+
521
+ query_states = query_states.to(target_dtype)
522
+ key_states = key_states.to(target_dtype)
523
+ value_states = value_states.to(target_dtype)
524
+
525
+ # Reashape to the expected shape for Flash Attention
526
+ query_states = query_states.transpose(1, 2)
527
+ key_states = key_states.transpose(1, 2)
528
+ value_states = value_states.transpose(1, 2)
529
+
530
+ attn_output = self._flash_attention_forward(
531
+ query_states,
532
+ key_states,
533
+ value_states,
534
+ attention_mask,
535
+ q_len,
536
+ dropout=attn_dropout,
537
+ use_sliding_windows=use_sliding_windows,
538
+ )
539
+
540
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
541
+ attn_output = self.o_proj(attn_output)
542
+
543
+ if not output_attentions:
544
+ attn_weights = None
545
+
546
+ return attn_output, attn_weights, past_key_value
547
+
548
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
549
+ def _flash_attention_forward(
550
+ self,
551
+ query_states,
552
+ key_states,
553
+ value_states,
554
+ attention_mask,
555
+ query_length,
556
+ dropout=0.0,
557
+ softmax_scale=None,
558
+ use_sliding_windows=False,
559
+ ):
560
+ """
561
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
562
+ first unpad the input, then computes the attention scores and pad the final attention scores.
563
+
564
+ Args:
565
+ query_states (`torch.Tensor`):
566
+ Input query states to be passed to Flash Attention API
567
+ key_states (`torch.Tensor`):
568
+ Input key states to be passed to Flash Attention API
569
+ value_states (`torch.Tensor`):
570
+ Input value states to be passed to Flash Attention API
571
+ attention_mask (`torch.Tensor`):
572
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
573
+ position of padding tokens and 1 for the position of non-padding tokens.
574
+ dropout (`float`):
575
+ Attention dropout
576
+ softmax_scale (`float`, *optional*):
577
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
578
+ use_sliding_windows (`bool`, *optional*):
579
+ Whether to activate sliding window attention.
580
+ """
581
+ if not self._flash_attn_uses_top_left_mask:
582
+ causal = self.is_causal
583
+ else:
584
+ # 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__.
585
+ causal = self.is_causal and query_length != 1
586
+
587
+ # Contains at least one padding token in the sequence
588
+ if attention_mask is not None:
589
+ batch_size = query_states.shape[0]
590
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
591
+ query_states, key_states, value_states, attention_mask, query_length
592
+ )
593
+
594
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
595
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
596
+
597
+ if not use_sliding_windows:
598
+ attn_output_unpad = flash_attn_varlen_func(
599
+ query_states,
600
+ key_states,
601
+ value_states,
602
+ cu_seqlens_q=cu_seqlens_q,
603
+ cu_seqlens_k=cu_seqlens_k,
604
+ max_seqlen_q=max_seqlen_in_batch_q,
605
+ max_seqlen_k=max_seqlen_in_batch_k,
606
+ dropout_p=dropout,
607
+ softmax_scale=softmax_scale,
608
+ causal=causal,
609
+ )
610
+ else:
611
+ attn_output_unpad = flash_attn_varlen_func(
612
+ query_states,
613
+ key_states,
614
+ value_states,
615
+ cu_seqlens_q=cu_seqlens_q,
616
+ cu_seqlens_k=cu_seqlens_k,
617
+ max_seqlen_q=max_seqlen_in_batch_q,
618
+ max_seqlen_k=max_seqlen_in_batch_k,
619
+ dropout_p=dropout,
620
+ softmax_scale=softmax_scale,
621
+ causal=causal,
622
+ window_size=(self.config.sliding_window, self.config.sliding_window),
623
+ )
624
+
625
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
626
+ else:
627
+ if not use_sliding_windows:
628
+ attn_output = flash_attn_func(
629
+ query_states,
630
+ key_states,
631
+ value_states,
632
+ dropout,
633
+ softmax_scale=softmax_scale,
634
+ causal=causal,
635
+ )
636
+ else:
637
+ attn_output = flash_attn_func(
638
+ query_states,
639
+ key_states,
640
+ value_states,
641
+ dropout,
642
+ softmax_scale=softmax_scale,
643
+ causal=causal,
644
+ window_size=(self.config.sliding_window, self.config.sliding_window),
645
+ )
646
+
647
+ return attn_output
648
+
649
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
650
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
651
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
652
+
653
+ # On the first iteration we need to properly re-create the padding mask
654
+ # by slicing it on the proper place
655
+ if kv_seq_len != attention_mask.shape[-1]:
656
+ attention_mask_num_tokens = attention_mask.shape[-1]
657
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
658
+
659
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
660
+
661
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
662
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
663
+
664
+ if query_length == kv_seq_len:
665
+ query_layer = index_first_axis(
666
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
667
+ )
668
+ cu_seqlens_q = cu_seqlens_k
669
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
670
+ indices_q = indices_k
671
+ elif query_length == 1:
672
+ max_seqlen_in_batch_q = 1
673
+ cu_seqlens_q = torch.arange(
674
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
675
+ ) # There is a memcpy here, that is very bad.
676
+ indices_q = cu_seqlens_q[:-1]
677
+ query_layer = query_layer.squeeze(1)
678
+ else:
679
+ # The -q_len: slice assumes left padding.
680
+ attention_mask = attention_mask[:, -query_length:]
681
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
682
+
683
+ return (
684
+ query_layer,
685
+ key_layer,
686
+ value_layer,
687
+ indices_q,
688
+ (cu_seqlens_q, cu_seqlens_k),
689
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
690
+ )
691
+
692
+
693
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
694
+ # TODO @Arthur no longer copied from LLama after static cache
695
+ class Phi3SdpaAttention(Phi3Attention):
696
+ """
697
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
698
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
699
+ SDPA API.
700
+ """
701
+
702
+ # Adapted from Phi3Attention.forward
703
+ def forward(
704
+ self,
705
+ hidden_states: torch.Tensor,
706
+ attention_mask: Optional[torch.Tensor] = None,
707
+ position_ids: Optional[torch.LongTensor] = None,
708
+ past_key_value: Optional[Cache] = None,
709
+ output_attentions: bool = False,
710
+ use_cache: bool = False,
711
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
712
+ if output_attentions:
713
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
714
+ logger.warning_once(
715
+ "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, "
716
+ '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.'
717
+ )
718
+ return super().forward(
719
+ hidden_states=hidden_states,
720
+ attention_mask=attention_mask,
721
+ position_ids=position_ids,
722
+ past_key_value=past_key_value,
723
+ output_attentions=output_attentions,
724
+ use_cache=use_cache,
725
+ )
726
+
727
+ bsz, q_len, _ = hidden_states.size()
728
+
729
+ qkv = self.qkv_proj(hidden_states)
730
+ query_pos = self.num_heads * self.head_dim
731
+ query_states = qkv[..., :query_pos]
732
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
733
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
734
+
735
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
736
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
737
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
738
+
739
+ kv_seq_len = key_states.shape[-2]
740
+ if past_key_value is not None:
741
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
742
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
743
+
744
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
745
+
746
+ if past_key_value is not None:
747
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
748
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
749
+
750
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
751
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
752
+
753
+ if attention_mask is not None:
754
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
755
+ raise ValueError(
756
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
757
+ )
758
+
759
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
760
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
761
+ if query_states.device.type == "cuda" and attention_mask is not None:
762
+ query_states = query_states.contiguous()
763
+ key_states = key_states.contiguous()
764
+ value_states = value_states.contiguous()
765
+
766
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
767
+ query_states,
768
+ key_states,
769
+ value_states,
770
+ attn_mask=attention_mask,
771
+ dropout_p=self.attention_dropout if self.training else 0.0,
772
+ # 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.
773
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
774
+ )
775
+
776
+ attn_output = attn_output.transpose(1, 2).contiguous()
777
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
778
+
779
+ attn_output = self.o_proj(attn_output)
780
+
781
+ return attn_output, None, past_key_value
782
+
783
+
784
+ PHI3_ATTENTION_CLASSES = {
785
+ "eager": Phi3Attention,
786
+ "flash_attention_2": Phi3FlashAttention2,
787
+ "sdpa": Phi3SdpaAttention,
788
+ }
789
+
790
+
791
+ class Phi3DecoderLayer(nn.Module):
792
+ def __init__(self, config: Phi3Config, layer_idx: int):
793
+ super().__init__()
794
+
795
+ self.config = config
796
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
797
+
798
+ self.mlp = Phi3MLP(config)
799
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
800
+
801
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
802
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
803
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
804
+
805
+ def forward(
806
+ self,
807
+ hidden_states: torch.Tensor,
808
+ attention_mask: Optional[torch.Tensor] = None,
809
+ position_ids: Optional[torch.LongTensor] = None,
810
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
811
+ output_attentions: Optional[bool] = False,
812
+ use_cache: Optional[bool] = False,
813
+ **kwargs,
814
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
815
+ if "padding_mask" in kwargs:
816
+ warnings.warn(
817
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
818
+ )
819
+ """
820
+ Args:
821
+ hidden_states (`torch.FloatTensor`):
822
+ input to the layer of shape `(batch, seq_len, embed_dim)`
823
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
824
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
825
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
826
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
827
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
828
+ output_attentions (`bool`, *optional*):
829
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
830
+ returned tensors for more detail.
831
+ use_cache (`bool`, *optional*):
832
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
833
+ (see `past_key_values`).
834
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
835
+ """
836
+
837
+ residual = hidden_states
838
+
839
+ hidden_states = self.input_layernorm(hidden_states)
840
+
841
+ # Self Attention
842
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
843
+ hidden_states=hidden_states,
844
+ attention_mask=attention_mask,
845
+ position_ids=position_ids,
846
+ past_key_value=past_key_value,
847
+ output_attentions=output_attentions,
848
+ use_cache=use_cache,
849
+ )
850
+
851
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
852
+
853
+ residual = hidden_states
854
+ hidden_states = self.post_attention_layernorm(hidden_states)
855
+ hidden_states = self.mlp(hidden_states)
856
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
857
+
858
+ outputs = (hidden_states,)
859
+
860
+ if output_attentions:
861
+ outputs += (self_attn_weights,)
862
+
863
+ if use_cache:
864
+ outputs += (present_key_value,)
865
+
866
+ return outputs
867
+
868
+
869
+ PHI3_START_DOCSTRING = r"""
870
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
871
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
872
+ etc.)
873
+
874
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
875
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
876
+ and behavior.
877
+
878
+ Parameters:
879
+ config ([`Phi3Config`]):
880
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
881
+ load the weights associated with the model, only the configuration. Check out the
882
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
883
+ """
884
+
885
+
886
+ @add_start_docstrings(
887
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
888
+ PHI3_START_DOCSTRING,
889
+ )
890
+ class Phi3PreTrainedModel(PreTrainedModel):
891
+ config_class = Phi3Config
892
+ base_model_prefix = "model"
893
+ supports_gradient_checkpointing = True
894
+ _no_split_modules = ["Phi3DecoderLayer"]
895
+ _skip_keys_device_placement = "past_key_values"
896
+ _supports_flash_attn_2 = True
897
+ _supports_sdpa = False
898
+ _supports_cache_class = True
899
+
900
+ _version = "0.0.5"
901
+
902
+ def _init_weights(self, module):
903
+ std = self.config.initializer_range
904
+ if isinstance(module, nn.Linear):
905
+ module.weight.data.normal_(mean=0.0, std=std)
906
+ if module.bias is not None:
907
+ module.bias.data.zero_()
908
+ elif isinstance(module, nn.Embedding):
909
+ module.weight.data.normal_(mean=0.0, std=std)
910
+ if module.padding_idx is not None:
911
+ module.weight.data[module.padding_idx].zero_()
912
+
913
+
914
+ PHI3_INPUTS_DOCSTRING = r"""
915
+ Args:
916
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
917
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
918
+ it.
919
+
920
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
921
+ [`PreTrainedTokenizer.__call__`] for details.
922
+
923
+ [What are input IDs?](../glossary#input-ids)
924
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
925
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
926
+
927
+ - 1 for tokens that are **not masked**,
928
+ - 0 for tokens that are **masked**.
929
+
930
+ [What are attention masks?](../glossary#attention-mask)
931
+
932
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
933
+ [`PreTrainedTokenizer.__call__`] for details.
934
+
935
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
936
+ `past_key_values`).
937
+
938
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
939
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
940
+ information on the default strategy.
941
+
942
+ - 1 indicates the head is **not masked**,
943
+ - 0 indicates the head is **masked**.
944
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
945
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
946
+ config.n_positions - 1]`.
947
+
948
+ [What are position IDs?](../glossary#position-ids)
949
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
950
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
951
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
952
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
953
+
954
+ Two formats are allowed:
955
+ - a [`~cache_utils.Cache`] instance;
956
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
957
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
958
+ cache format.
959
+
960
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
961
+ legacy cache format will be returned.
962
+
963
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
964
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
965
+ of shape `(batch_size, sequence_length)`.
966
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
967
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
968
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
969
+ model's internal embedding lookup matrix.
970
+ use_cache (`bool`, *optional*):
971
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
972
+ `past_key_values`).
973
+ output_attentions (`bool`, *optional*):
974
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
975
+ tensors for more detail.
976
+ output_hidden_states (`bool`, *optional*):
977
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
978
+ more detail.
979
+ return_dict (`bool`, *optional*):
980
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
981
+ """
982
+
983
+
984
+ @add_start_docstrings(
985
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
986
+ PHI3_START_DOCSTRING,
987
+ )
988
+ class Phi3Model(Phi3PreTrainedModel):
989
+ """
990
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
991
+
992
+ Args:
993
+ config: Phi3Config
994
+ """
995
+
996
+ def __init__(self, config: Phi3Config):
997
+ super().__init__(config)
998
+ self.padding_idx = config.pad_token_id
999
+ self.vocab_size = config.vocab_size
1000
+
1001
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1002
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1003
+ self.layers = nn.ModuleList(
1004
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1005
+ )
1006
+ self._attn_implementation = config._attn_implementation
1007
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1008
+
1009
+ self.gradient_checkpointing = False
1010
+ # Initialize weights and apply final processing
1011
+ self.post_init()
1012
+
1013
+ def get_input_embeddings(self):
1014
+ return self.embed_tokens
1015
+
1016
+ def set_input_embeddings(self, value):
1017
+ self.embed_tokens = value
1018
+
1019
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1020
+ def forward(
1021
+ self,
1022
+ input_ids: torch.LongTensor = None,
1023
+ attention_mask: Optional[torch.Tensor] = None,
1024
+ position_ids: Optional[torch.LongTensor] = None,
1025
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1026
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1027
+ use_cache: Optional[bool] = None,
1028
+ output_attentions: Optional[bool] = None,
1029
+ output_hidden_states: Optional[bool] = None,
1030
+ return_dict: Optional[bool] = None,
1031
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1032
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1033
+ output_hidden_states = (
1034
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1035
+ )
1036
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1037
+
1038
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1039
+
1040
+ # retrieve input_ids and inputs_embeds
1041
+ if input_ids is not None and inputs_embeds is not None:
1042
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1043
+ elif input_ids is not None:
1044
+ batch_size, seq_length = input_ids.shape[:2]
1045
+ elif inputs_embeds is not None:
1046
+ batch_size, seq_length = inputs_embeds.shape[:2]
1047
+ else:
1048
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1049
+
1050
+ past_key_values_length = 0
1051
+
1052
+ if self.gradient_checkpointing and self.training:
1053
+ if use_cache:
1054
+ logger.warning_once(
1055
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1056
+ )
1057
+ use_cache = False
1058
+
1059
+ if use_cache:
1060
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1061
+ if use_legacy_cache:
1062
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1063
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1064
+
1065
+ if position_ids is None:
1066
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1067
+ position_ids = torch.arange(
1068
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1069
+ )
1070
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1071
+ else:
1072
+ position_ids = position_ids.view(-1, seq_length).long()
1073
+
1074
+ if inputs_embeds is None:
1075
+ inputs_embeds = self.embed_tokens(input_ids)
1076
+
1077
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1078
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1079
+ if is_padding_right:
1080
+ raise ValueError(
1081
+ "You are attempting to perform batched generation with padding_side='right'"
1082
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1083
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1084
+ )
1085
+
1086
+ if self._attn_implementation == "flash_attention_2":
1087
+ # 2d mask is passed through the layers
1088
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1089
+ else:
1090
+ # 4d mask is passed through the layers
1091
+ attention_mask = _prepare_4d_causal_attention_mask(
1092
+ attention_mask,
1093
+ (batch_size, seq_length),
1094
+ inputs_embeds,
1095
+ past_key_values_length,
1096
+ sliding_window=self.config.sliding_window,
1097
+ )
1098
+
1099
+ hidden_states = inputs_embeds
1100
+
1101
+ # decoder layers
1102
+ all_hidden_states = () if output_hidden_states else None
1103
+ all_self_attns = () if output_attentions else None
1104
+ next_decoder_cache = None
1105
+
1106
+ for decoder_layer in self.layers:
1107
+ if output_hidden_states:
1108
+ all_hidden_states += (hidden_states,)
1109
+
1110
+ if self.gradient_checkpointing and self.training:
1111
+ layer_outputs = self._gradient_checkpointing_func(
1112
+ decoder_layer.__call__,
1113
+ hidden_states,
1114
+ attention_mask,
1115
+ position_ids,
1116
+ past_key_values,
1117
+ output_attentions,
1118
+ use_cache,
1119
+ )
1120
+ else:
1121
+ layer_outputs = decoder_layer(
1122
+ hidden_states,
1123
+ attention_mask=attention_mask,
1124
+ position_ids=position_ids,
1125
+ past_key_value=past_key_values,
1126
+ output_attentions=output_attentions,
1127
+ use_cache=use_cache,
1128
+ )
1129
+
1130
+ hidden_states = layer_outputs[0]
1131
+
1132
+ if use_cache:
1133
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1134
+
1135
+ if output_attentions:
1136
+ all_self_attns += (layer_outputs[1],)
1137
+
1138
+ hidden_states = self.norm(hidden_states)
1139
+
1140
+ # add hidden states from the last decoder layer
1141
+ if output_hidden_states:
1142
+ all_hidden_states += (hidden_states,)
1143
+
1144
+ next_cache = None
1145
+ if use_cache:
1146
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1147
+ if not return_dict:
1148
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1149
+ return BaseModelOutputWithPast(
1150
+ last_hidden_state=hidden_states,
1151
+ past_key_values=next_cache,
1152
+ hidden_states=all_hidden_states,
1153
+ attentions=all_self_attns,
1154
+ )
1155
+
1156
+
1157
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1158
+ _tied_weights_keys = ["lm_head.weight"]
1159
+
1160
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1161
+ def __init__(self, config):
1162
+ super().__init__(config)
1163
+ self.model = Phi3Model(config)
1164
+ self.vocab_size = config.vocab_size
1165
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1166
+
1167
+ # Initialize weights and apply final processing
1168
+ self.post_init()
1169
+
1170
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1171
+ def get_input_embeddings(self):
1172
+ return self.model.embed_tokens
1173
+
1174
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1175
+ def set_input_embeddings(self, value):
1176
+ self.model.embed_tokens = value
1177
+
1178
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1179
+ def get_output_embeddings(self):
1180
+ return self.lm_head
1181
+
1182
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1183
+ def set_output_embeddings(self, new_embeddings):
1184
+ self.lm_head = new_embeddings
1185
+
1186
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1187
+ def set_decoder(self, decoder):
1188
+ self.model = decoder
1189
+
1190
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1191
+ def get_decoder(self):
1192
+ return self.model
1193
+
1194
+ # Ignore copy
1195
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1196
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1197
+ def forward(
1198
+ self,
1199
+ input_ids: torch.LongTensor = None,
1200
+ attention_mask: Optional[torch.Tensor] = None,
1201
+ position_ids: Optional[torch.LongTensor] = None,
1202
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1203
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1204
+ labels: Optional[torch.LongTensor] = None,
1205
+ use_cache: Optional[bool] = None,
1206
+ output_attentions: Optional[bool] = None,
1207
+ output_hidden_states: Optional[bool] = None,
1208
+ return_dict: Optional[bool] = None,
1209
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1210
+ r"""
1211
+ Args:
1212
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1213
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1214
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1215
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1216
+
1217
+ Returns:
1218
+
1219
+ Example:
1220
+
1221
+ ```python
1222
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1223
+
1224
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1225
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1226
+
1227
+ >>> prompt = "This is an example script ."
1228
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1229
+
1230
+ >>> # Generate
1231
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1232
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1233
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1234
+ ```"""
1235
+
1236
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1237
+ output_hidden_states = (
1238
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1239
+ )
1240
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1241
+
1242
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1243
+ outputs = self.model(
1244
+ input_ids=input_ids,
1245
+ attention_mask=attention_mask,
1246
+ position_ids=position_ids,
1247
+ past_key_values=past_key_values,
1248
+ inputs_embeds=inputs_embeds,
1249
+ use_cache=use_cache,
1250
+ output_attentions=output_attentions,
1251
+ output_hidden_states=output_hidden_states,
1252
+ return_dict=return_dict,
1253
+ )
1254
+
1255
+ hidden_states = outputs[0]
1256
+ logits = self.lm_head(hidden_states)
1257
+ logits = logits.float()
1258
+
1259
+ loss = None
1260
+ if labels is not None:
1261
+ # Shift so that tokens < n predict n
1262
+ shift_logits = logits[..., :-1, :].contiguous()
1263
+ shift_labels = labels[..., 1:].contiguous()
1264
+ # Flatten the tokens
1265
+ loss_fct = CrossEntropyLoss()
1266
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1267
+ shift_labels = shift_labels.view(-1)
1268
+ # Enable model parallelism
1269
+ shift_labels = shift_labels.to(shift_logits.device)
1270
+ loss = loss_fct(shift_logits, shift_labels)
1271
+
1272
+ if not return_dict:
1273
+ output = (logits,) + outputs[1:]
1274
+ return (loss,) + output if loss is not None else output
1275
+
1276
+ return CausalLMOutputWithPast(
1277
+ loss=loss,
1278
+ logits=logits,
1279
+ past_key_values=outputs.past_key_values,
1280
+ hidden_states=outputs.hidden_states,
1281
+ attentions=outputs.attentions,
1282
+ )
1283
+
1284
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1285
+ def prepare_inputs_for_generation(
1286
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1287
+ ):
1288
+ if past_key_values is not None:
1289
+ if isinstance(past_key_values, Cache):
1290
+ cache_length = past_key_values.get_seq_length()
1291
+ past_length = past_key_values.seen_tokens
1292
+ max_cache_length = past_key_values.get_max_length()
1293
+ else:
1294
+ cache_length = past_length = past_key_values[0][0].shape[2]
1295
+ max_cache_length = None
1296
+
1297
+ # Keep only the unprocessed tokens:
1298
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1299
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1300
+ # input)
1301
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1302
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1303
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1304
+ # input_ids based on the past_length.
1305
+ elif past_length < input_ids.shape[1]:
1306
+ input_ids = input_ids[:, past_length:]
1307
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1308
+
1309
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1310
+ if (
1311
+ max_cache_length is not None
1312
+ and attention_mask is not None
1313
+ and cache_length + input_ids.shape[1] > max_cache_length
1314
+ ):
1315
+ attention_mask = attention_mask[:, -max_cache_length:]
1316
+
1317
+ position_ids = kwargs.get("position_ids", None)
1318
+ if attention_mask is not None and position_ids is None:
1319
+ # create position_ids on the fly for batch generation
1320
+ position_ids = attention_mask.long().cumsum(-1) - 1
1321
+ position_ids.masked_fill_(attention_mask == 0, 1)
1322
+ if past_key_values:
1323
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1324
+
1325
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1326
+ if inputs_embeds is not None and past_key_values is None:
1327
+ model_inputs = {"inputs_embeds": inputs_embeds}
1328
+ else:
1329
+ model_inputs = {"input_ids": input_ids}
1330
+
1331
+ model_inputs.update(
1332
+ {
1333
+ "position_ids": position_ids,
1334
+ "past_key_values": past_key_values,
1335
+ "use_cache": kwargs.get("use_cache"),
1336
+ "attention_mask": attention_mask,
1337
+ }
1338
+ )
1339
+ return model_inputs
1340
+
1341
+ @staticmethod
1342
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1343
+ def _reorder_cache(past_key_values, beam_idx):
1344
+ reordered_past = ()
1345
+ for layer_past in past_key_values:
1346
+ reordered_past += (
1347
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1348
+ )
1349
+ return reordered_past
1350
+
1351
+
1352
+ @add_start_docstrings(
1353
+ """
1354
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1355
+
1356
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1357
+ (e.g. GPT-2) do.
1358
+
1359
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1360
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1361
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1362
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1363
+ each row of the batch).
1364
+ """,
1365
+ PHI3_START_DOCSTRING,
1366
+ )
1367
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1368
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1369
+ def __init__(self, config):
1370
+ super().__init__(config)
1371
+ self.num_labels = config.num_labels
1372
+ self.model = Phi3Model(config)
1373
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1374
+
1375
+ # Initialize weights and apply final processing
1376
+ self.post_init()
1377
+
1378
+ def get_input_embeddings(self):
1379
+ return self.model.embed_tokens
1380
+
1381
+ def set_input_embeddings(self, value):
1382
+ self.model.embed_tokens = value
1383
+
1384
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1385
+ def forward(
1386
+ self,
1387
+ input_ids: torch.LongTensor = None,
1388
+ attention_mask: Optional[torch.Tensor] = None,
1389
+ position_ids: Optional[torch.LongTensor] = None,
1390
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1391
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1392
+ labels: Optional[torch.LongTensor] = None,
1393
+ use_cache: Optional[bool] = None,
1394
+ output_attentions: Optional[bool] = None,
1395
+ output_hidden_states: Optional[bool] = None,
1396
+ return_dict: Optional[bool] = None,
1397
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1398
+ r"""
1399
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1400
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1401
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1402
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1403
+ """
1404
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1405
+
1406
+ model_outputs = self.model(
1407
+ input_ids,
1408
+ attention_mask=attention_mask,
1409
+ position_ids=position_ids,
1410
+ past_key_values=past_key_values,
1411
+ inputs_embeds=inputs_embeds,
1412
+ use_cache=use_cache,
1413
+ output_attentions=output_attentions,
1414
+ output_hidden_states=output_hidden_states,
1415
+ return_dict=return_dict,
1416
+ )
1417
+ hidden_states = model_outputs[0]
1418
+ logits = self.score(hidden_states)
1419
+
1420
+ if input_ids is not None:
1421
+ batch_size = input_ids.shape[0]
1422
+ else:
1423
+ batch_size = inputs_embeds.shape[0]
1424
+
1425
+ if self.config.pad_token_id is None and batch_size != 1:
1426
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1427
+ if self.config.pad_token_id is None:
1428
+ sequence_lengths = -1
1429
+ else:
1430
+ if input_ids is not None:
1431
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1432
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1433
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1434
+ sequence_lengths = sequence_lengths.to(logits.device)
1435
+ else:
1436
+ sequence_lengths = -1
1437
+
1438
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1439
+
1440
+ loss = None
1441
+ if labels is not None:
1442
+ labels = labels.to(logits.device)
1443
+ if self.config.problem_type is None:
1444
+ if self.num_labels == 1:
1445
+ self.config.problem_type = "regression"
1446
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1447
+ self.config.problem_type = "single_label_classification"
1448
+ else:
1449
+ self.config.problem_type = "multi_label_classification"
1450
+
1451
+ if self.config.problem_type == "regression":
1452
+ loss_fct = MSELoss()
1453
+ if self.num_labels == 1:
1454
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1455
+ else:
1456
+ loss = loss_fct(pooled_logits, labels)
1457
+ elif self.config.problem_type == "single_label_classification":
1458
+ loss_fct = CrossEntropyLoss()
1459
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1460
+ elif self.config.problem_type == "multi_label_classification":
1461
+ loss_fct = BCEWithLogitsLoss()
1462
+ loss = loss_fct(pooled_logits, labels)
1463
+ if not return_dict:
1464
+ output = (pooled_logits,) + model_outputs[1:]
1465
+ return ((loss,) + output) if loss is not None else output
1466
+
1467
+ return SequenceClassifierOutputWithPast(
1468
+ loss=loss,
1469
+ logits=pooled_logits,
1470
+ past_key_values=model_outputs.past_key_values,
1471
+ hidden_states=model_outputs.hidden_states,
1472
+ attentions=model_outputs.attentions,
1473
+ )
1474
+
1475
+
1476
+ @add_start_docstrings(
1477
+ """
1478
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1479
+ Named-Entity-Recognition (NER) tasks.
1480
+ """,
1481
+ PHI3_START_DOCSTRING,
1482
+ )
1483
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1484
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1485
+ def __init__(self, config: Phi3Config):
1486
+ super().__init__(config)
1487
+ self.num_labels = config.num_labels
1488
+
1489
+ self.model = Phi3Model(config)
1490
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1491
+ classifier_dropout = config.classifier_dropout
1492
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1493
+ classifier_dropout = config.hidden_dropout
1494
+ else:
1495
+ classifier_dropout = 0.1
1496
+ self.dropout = nn.Dropout(classifier_dropout)
1497
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1498
+
1499
+ # Initialize weights and apply final processing
1500
+ self.post_init()
1501
+
1502
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1503
+ @add_code_sample_docstrings(
1504
+ checkpoint=_CHECKPOINT_FOR_DOC,
1505
+ output_type=TokenClassifierOutput,
1506
+ config_class=_CONFIG_FOR_DOC,
1507
+ )
1508
+ def forward(
1509
+ self,
1510
+ input_ids: Optional[torch.LongTensor] = None,
1511
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1512
+ attention_mask: Optional[torch.Tensor] = None,
1513
+ inputs_embeds: Optional[torch.Tensor] = None,
1514
+ labels: Optional[torch.Tensor] = None,
1515
+ use_cache: Optional[bool] = None,
1516
+ output_attentions: Optional[bool] = None,
1517
+ output_hidden_states: Optional[bool] = None,
1518
+ return_dict: Optional[bool] = None,
1519
+ **deprecated_arguments,
1520
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1521
+ r"""
1522
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1523
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1524
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1525
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1526
+ """
1527
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1528
+
1529
+ model_outputs = self.model(
1530
+ input_ids,
1531
+ past_key_values=past_key_values,
1532
+ attention_mask=attention_mask,
1533
+ inputs_embeds=inputs_embeds,
1534
+ use_cache=use_cache,
1535
+ output_attentions=output_attentions,
1536
+ output_hidden_states=output_hidden_states,
1537
+ return_dict=return_dict,
1538
+ )
1539
+
1540
+ hidden_states = model_outputs[0]
1541
+ hidden_states = self.dropout(hidden_states)
1542
+ logits = self.classifier(hidden_states)
1543
+
1544
+ loss = None
1545
+ if labels is not None:
1546
+ # move labels to correct device to enable model parallelism
1547
+ labels = labels.to(logits.device)
1548
+ batch_size, seq_length = labels.shape
1549
+ loss_fct = CrossEntropyLoss()
1550
+ loss = loss_fct(
1551
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1552
+ )
1553
+
1554
+ if not return_dict:
1555
+ output = (logits,) + model_outputs[2:]
1556
+ return ((loss,) + output) if loss is not None else output
1557
+
1558
+ return TokenClassifierOutput(
1559
+ loss=loss,
1560
+ logits=logits,
1561
+ hidden_states=model_outputs.hidden_states,
1562
+ attentions=model_outputs.attentions,
1563
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": true,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "32000": {
31
+ "content": "<|endoftext|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "32001": {
39
+ "content": "<|assistant|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": true,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "32002": {
47
+ "content": "<|placeholder1|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": true,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "32003": {
55
+ "content": "<|placeholder2|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": true,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "32004": {
63
+ "content": "<|placeholder3|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": true,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "32005": {
71
+ "content": "<|placeholder4|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": true,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "32006": {
79
+ "content": "<|system|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": true,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "32007": {
87
+ "content": "<|end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": true,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "32008": {
95
+ "content": "<|placeholder5|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": true,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "32009": {
103
+ "content": "<|placeholder6|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": true,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "32010": {
111
+ "content": "<|user|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": true,
115
+ "single_word": false,
116
+ "special": true
117
+ }
118
+ },
119
+ "bos_token": "<s>",
120
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'system' %}{{'<|system|>\n' + message['content'] + '<|end|>\n'}}{% elif message['role'] == 'user' %}{{'<|user|>\n' + message['content'] + '<|end|>\n'}}{% elif message['role'] == 'assistant' %}{{'<|assistant|>\n' + message['content'] + '<|end|>\n'}}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>\n' }}{% else %}{{ eos_token }}{% endif %}",
121
+ "clean_up_tokenization_spaces": false,
122
+ "eos_token": "<|endoftext|>",
123
+ "legacy": false,
124
+ "model_max_length": 131072,
125
+ "pad_token": "<|endoftext|>",
126
+ "padding_side": "left",
127
+ "sp_model_kwargs": {},
128
+ "tokenizer_class": "LlamaTokenizer",
129
+ "unk_token": "<unk>",
130
+ "use_default_system_prompt": false
131
+ }