dyingc commited on
Commit
c41293b
·
verified ·
1 Parent(s): 18f5c33

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Microsoft Open Source Code of Conduct
2
+
3
+ This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
4
+
5
+ Resources:
6
+
7
+ - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
8
+ - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
9
+ - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Microsoft.
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ MIT License
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
NOTICE.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NOTICES AND INFORMATION
2
+ Do Not Translate or Localize
3
+
4
+ This software incorporates material from third parties.
5
+
6
+ **Component.** https://github.com/Dao-AILab/flash-attention
7
+
8
+ **Open Source License/Copyright Notice.**
9
+
10
+ BSD 3-Clause License
11
+
12
+ Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file.
13
+ All rights reserved.
14
+
15
+ Redistribution and use in source and binary forms, with or without
16
+ modification, are permitted provided that the following conditions are met:
17
+
18
+ * Redistributions of source code must retain the above copyright notice, this
19
+ list of conditions and the following disclaimer.
20
+
21
+ * Redistributions in binary form must reproduce the above copyright notice,
22
+ this list of conditions and the following disclaimer in the documentation
23
+ and/or other materials provided with the distribution.
24
+
25
+ * Neither the name of the copyright holder nor the names of its
26
+ contributors may be used to endorse or promote products derived from
27
+ this software without specific prior written permission.
28
+
29
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
30
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
32
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
33
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
36
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
37
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
README.md ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - multilingual
4
+ - ar
5
+ - zh
6
+ - cs
7
+ - da
8
+ - nl
9
+ - en
10
+ - fi
11
+ - fr
12
+ - de
13
+ - he
14
+ - hu
15
+ - it
16
+ - ja
17
+ - ko
18
+ - 'no'
19
+ - pl
20
+ - pt
21
+ - ru
22
+ - es
23
+ - sv
24
+ - th
25
+ - tr
26
+ - uk
27
+ library_name: transformers
28
+ license: mit
29
+ license_link: https://huggingface.co/microsoft/Phi-4-mini-instruct/resolve/main/LICENSE
30
+ pipeline_tag: text-generation
31
+ tags:
32
+ - nlp
33
+ - code
34
+ widget:
35
+ - messages:
36
+ - role: user
37
+ content: Can you provide ways to eat combinations of bananas and dragonfruits?
38
+ ---
39
+ 🎉**Phi-4**: [[mini-reasoning](https://huggingface.co/microsoft/Phi-4-mini-reasoning) | [reasoning](https://huggingface.co/microsoft/Phi-4-reasoning)] | [[multimodal-instruct](https://huggingface.co/microsoft/Phi-4-multimodal-instruct) | [onnx](https://huggingface.co/microsoft/Phi-4-multimodal-instruct-onnx)];
40
+ [[mini-instruct](https://huggingface.co/microsoft/Phi-4-mini-instruct) | [onnx](https://huggingface.co/microsoft/Phi-4-mini-instruct-onnx)]
41
+
42
+
43
+ ## Model Summary
44
+
45
+ Phi-4-mini-instruct is a lightweight open model built upon synthetic data and filtered publicly available websites - with a focus on high-quality, reasoning dense data. The model belongs to the Phi-4 model family and supports 128K token context length. The model underwent an enhancement process, incorporating both supervised fine-tuning and direct preference optimization to support precise instruction adherence and robust safety measures.
46
+
47
+ 📰 [Phi-4-mini Microsoft Blog](https://aka.ms/phi4-feb2025) <br>
48
+ 📖 [Phi-4-mini Technical Report](https://aka.ms/phi-4-multimodal/techreport) <br>
49
+ 👩‍🍳 [Phi Cookbook](https://github.com/microsoft/PhiCookBook) <br>
50
+ 🏡 [Phi Portal](https://azure.microsoft.com/en-us/products/phi) <br>
51
+ 🖥️ Try It [Azure](https://aka.ms/phi-4-mini/azure), [Huggingface](https://huggingface.co/spaces/microsoft/phi-4-mini) <br>
52
+
53
+ 🚀 [Model paper](https://huggingface.co/papers/2503.01743)
54
+
55
+
56
+ ## Intended Uses
57
+
58
+ ### Primary Use Cases
59
+
60
+ The model is intended for broad multilingual commercial and research use. The model provides uses for general purpose AI systems and applications which require:
61
+
62
+ 1) Memory/compute constrained environments
63
+ 2) Latency bound scenarios
64
+ 3) Strong reasoning (especially math and logic).
65
+
66
+ The model is designed to accelerate research on language and multimodal models, for use as a building block for generative AI powered features.
67
+
68
+ ### Use Case Considerations
69
+
70
+ The model is not specifically designed or evaluated for all downstream purposes. Developers should consider common limitations of language models, as well as performance difference across languages, as they select use cases, and evaluate and mitigate for accuracy, safety, and fairness before using within a specific downstream use case, particularly for high-risk scenarios.
71
+ Developers should be aware of and adhere to applicable laws or regulations (including but not limited to privacy, trade compliance laws, etc.) that are relevant to their use case.
72
+
73
+ ***Nothing contained in this Model Card should be interpreted as or deemed a restriction or modification to the license the model is released under.***
74
+
75
+ ## Release Notes
76
+
77
+ This release of Phi-4-mini-instruct is based on valuable user feedback from the Phi-3 series. The Phi-4-mini model employed new architecture for efficiency, larger vocabulary for multilingual support, and better post-training techniques were used for instruction following, function calling, as well as additional data leading to substantial gains on key capabilities. It is anticipated that most use cases will benefit from this release, but users are encouraged to test in their particular AI applications. The enthusiastic support for the Phi-4 series is greatly appreciated. Feedback on Phi-4-mini-instruct is welcomed and crucial to the model’s evolution and improvement.
78
+
79
+ ### Model Quality
80
+
81
+ To understand the capabilities, the 3.8B parameters Phi-4-mini-instruct model was compared with a set of models over a variety of benchmarks using an internal benchmark platform (See Appendix A for benchmark methodology). A high-level overview of the model quality is as follows:
82
+
83
+ | Benchmark | Similar size | | | | |2x size | | | | | |
84
+ |----------------------------------|-------------|-------------------|-------------------|-------------------|-----------------|-----------------|-----------------|-----------------|-----------------|-----------------|-----------------|
85
+ | | Phi-4 mini-Ins | Phi-3.5-mini-Ins | Llama-3.2-3B-Ins | Mistral-3B | Qwen2.5-3B-Ins | Qwen2.5-7B-Ins | Mistral-8B-2410 | Llama-3.1-8B-Ins | Llama-3.1-Tulu-3-8B | Gemma2-9B-Ins | GPT-4o-mini-2024-07-18 |
86
+ | **Popular aggregated benchmark** | | | | | | | | | | | |
87
+ | Arena Hard | 32.8 | 34.4 | 17.0 | 26.9 | 32.0 | 55.5 | 37.3 | 25.7 | 42.7 | 43.7 | 53.7 |
88
+ | BigBench Hard (0-shot, CoT) | 70.4 | 63.1 | 55.4 | 51.2 | 56.2 | 72.4 | 53.3 | 63.4 | 55.5 | 65.7 | 80.4 |
89
+ | MMLU (5-shot) | 67.3 | 65.5 | 61.8 | 60.8 | 65.0 | 72.6 | 63.0 | 68.1 | 65.0 | 71.3 | 77.2 |
90
+ | MMLU-Pro (0-shot, CoT) | 52.8 | 47.4 | 39.2 | 35.3 | 44.7 | 56.2 | 36.6 | 44.0 | 40.9 | 50.1 | 62.8 |
91
+ | **Reasoning** | | | | | | | | | | | |
92
+ | ARC Challenge (10-shot) | 83.7 | 84.6 | 76.1 | 80.3 | 82.6 | 90.1 | 82.7 | 83.1 | 79.4 | 89.8 | 93.5 |
93
+ | BoolQ (2-shot) | 81.2 | 77.7 | 71.4 | 79.4 | 65.4 | 80.0 | 80.5 | 82.8 | 79.3 | 85.7 | 88.7 |
94
+ | GPQA (0-shot, CoT) | 25.2 | 26.6 | 24.3 | 24.4 | 23.4 | 30.6 | 26.3 | 26.3 | 29.9 | 39.1 | 41.1 |
95
+ | HellaSwag (5-shot) | 69.1 | 72.2 | 77.2 | 74.6 | 74.6 | 80.0 | 73.5 | 72.8 | 80.9 | 87.1 | 88.7 |
96
+ | OpenBookQA (10-shot) | 79.2 | 81.2 | 72.6 | 79.8 | 79.3 | 82.6 | 80.2 | 84.8 | 79.8 | 90.0 | 90.0 |
97
+ | PIQA (5-shot) | 77.6 | 78.2 | 68.2 | 73.2 | 72.6 | 76.2 | 81.2 | 83.2 | 78.3 | 83.7 | 88.7 |
98
+ | Social IQA (5-shot) | 72.5 | 75.1 | 68.3 | 73.9 | 75.3 | 75.3 | 77.6 | 71.8 | 73.4 | 74.7 | 82.9 |
99
+ | TruthfulQA (MC2) (10-shot) | 66.4 | 65.2 | 59.2 | 62.9 | 64.3 | 69.4 | 63.0 | 69.2 | 64.1 | 76.6 | 78.2 |
100
+ | Winogrande (5-shot) | 67.0 | 72.2 | 53.2 | 59.8 | 63.3 | 71.1 | 63.1 | 64.7 | 65.4 | 74.0 | 76.9 |
101
+ | **Multilingual** | | | | | | | | | | | |
102
+ | Multilingual MMLU (5-shot) | 49.3 | 51.8 | 48.1 | 46.4 | 55.9 | 64.4 | 53.7 | 56.2 | 54.5 | 63.8 | 72.9 |
103
+ | MGSM (0-shot, CoT) | 63.9 | 49.6 | 44.6 | 44.6 | 53.5 | 64.5 | 56.7 | 56.7 | 58.6 | 75.1 | 81.7 |
104
+ | **Math** | | | | | | | | | | | |
105
+ | GSM8K (8-shot, CoT) | 88.6 | 76.9 | 75.6 | 80.1 | 80.6 | 88.7 | 81.9 | 82.4 | 84.3 | 84.9 | 91.3 |
106
+ | MATH (0-shot, CoT) | 64.0 | 49.8 | 46.7 | 41.8 | 61.7 | 60.4 | 41.6 | 47.6 | 46.1 | 51.3 | 70.2 |
107
+ | **Overall** | **63.5** | **60.5** | **56.2** | **56.9** | **60.1** | **67.9** | **60.2** | **62.3** | **60.9** | **65.0** | **75.5** |
108
+
109
+ Overall, the model with only 3.8B-param achieves a similar level of multilingual 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 factual knowledge, therefore, users may experience factual incorrectness. However, it may be possible to resolve such weakness by augmenting Phi-4 with a search engine, particularly when using the model under RAG settings.
110
+
111
+ ## Usage
112
+
113
+ ### Tokenizer
114
+
115
+ Phi-4-mini-instruct supports a vocabulary size of up to `200064` tokens. The [tokenizer files](https://huggingface.co/microsoft/Phi-4-mini-instruct/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.
116
+
117
+ ### Input Formats
118
+
119
+ Given the nature of the training data, the Phi-4-mini-instruct
120
+ model is best suited for prompts using specific formats.
121
+ Below are the two primary formats:
122
+
123
+ #### Chat format
124
+
125
+ This format is used for general conversation and instructions:
126
+
127
+ ```yaml
128
+ <|system|>Insert System Message<|end|><|user|>Insert User Message<|end|><|assistant|>
129
+ ```
130
+
131
+ #### Tool-enabled function-calling format
132
+
133
+ This format is used when the user wants the model to provide function calls based on the given tools. The user should provide the available tools in the system prompt, wrapped by <|tool|> and <|/tool|> tokens. The tools should be specified in JSON format, using a JSON dump structure. Example:
134
+
135
+ `
136
+ <|system|>You are a helpful assistant with some tools.<|tool|>[{"name": "get_weather_updates", "description": "Fetches weather updates for a given city using the RapidAPI Weather API.", "parameters": {"city": {"description": "The name of the city for which to retrieve weather information.", "type": "str", "default": "London"}}}]<|/tool|><|end|><|user|>What is the weather like in Paris today?<|end|><|assistant|>
137
+ `
138
+
139
+ ### Inference with vLLM
140
+
141
+ #### Requirements
142
+
143
+ List of required packages:
144
+
145
+ ```
146
+ flash_attn==2.7.4.post1
147
+ torch==2.5.1
148
+ vllm>=0.7.3
149
+ ```
150
+
151
+ #### Example
152
+
153
+ To perform inference using vLLM, you can use the following code snippet:
154
+
155
+ ```python
156
+ from vllm import LLM, SamplingParams
157
+
158
+ llm = LLM(model="microsoft/Phi-4-mini-instruct", trust_remote_code=True)
159
+
160
+ messages = [
161
+ {"role": "system", "content": "You are a helpful AI assistant."},
162
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
163
+ {"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."},
164
+ {"role": "user", "content": "What about solving an 2x + 3 = 7 equation?"},
165
+ ]
166
+
167
+ sampling_params = SamplingParams(
168
+ max_tokens=500,
169
+ temperature=0.0,
170
+ )
171
+
172
+ output = llm.chat(messages=messages, sampling_params=sampling_params)
173
+ print(output[0].outputs[0].text)
174
+ ```
175
+
176
+ ### Inference with Transformers
177
+
178
+ #### Requirements
179
+
180
+
181
+ Phi-4 family has been integrated in the `4.49.0` version of `transformers`. The current `transformers` version can be verified with: `pip list | grep transformers`.
182
+ Python 3.8 and 3.10 will work best.
183
+ List of required packages:
184
+
185
+ ```
186
+ flash_attn==2.7.4.post1
187
+ torch==2.5.1
188
+ transformers==4.49.0
189
+ accelerate==1.3.0
190
+ ```
191
+
192
+ Phi-4-mini-instruct is also available in [Azure AI Studio]()
193
+
194
+ #### Example
195
+
196
+ After obtaining the Phi-4-mini-instruct model checkpoints, users can use this sample code for inference.
197
+
198
+ ```python
199
+ import torch
200
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
201
+
202
+ torch.random.manual_seed(0)
203
+
204
+ model_path = "microsoft/Phi-4-mini-instruct"
205
+
206
+ model = AutoModelForCausalLM.from_pretrained(
207
+ model_path,
208
+ device_map="auto",
209
+ torch_dtype="auto",
210
+ trust_remote_code=True,
211
+ )
212
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
213
+
214
+ messages = [
215
+ {"role": "system", "content": "You are a helpful AI assistant."},
216
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
217
+ {"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."},
218
+ {"role": "user", "content": "What about solving an 2x + 3 = 7 equation?"},
219
+ ]
220
+
221
+ pipe = pipeline(
222
+ "text-generation",
223
+ model=model,
224
+ tokenizer=tokenizer,
225
+ )
226
+
227
+ generation_args = {
228
+ "max_new_tokens": 500,
229
+ "return_full_text": False,
230
+ "temperature": 0.0,
231
+ "do_sample": False,
232
+ }
233
+
234
+ output = pipe(messages, **generation_args)
235
+ print(output[0]['generated_text'])
236
+ ```
237
+
238
+ ## Responsible AI Considerations
239
+
240
+ Like other language models, the Phi family of models can potentially behave in ways that are unfair, unreliable, or offensive. Some of the limiting behaviors to be aware of include:
241
+
242
+ + Quality of Service: The Phi models are trained primarily on English text and some additional multilingual text. Languages other than English will experience worse performance as well as performance disparities across non-English. English language varieties with less representation in the training data might experience worse performance than standard American English.
243
+ + Multilingual performance and safety gaps: We believe it is important to make language models more widely available across different languages, but the Phi 4 models still exhibit challenges common across multilingual releases. As with any deployment of LLMs, developers will be better positioned to test for performance or safety gaps for their linguistic and cultural context and customize the model with additional fine-tuning and appropriate safeguards.
244
+ + 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, cultural contexts, or prevalence of examples of negative stereotypes in training data that reflect real-world patterns and societal biases.
245
+ + 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 case.
246
+ + Information Reliability: Language models can generate nonsensical content or fabricate content that might sound reasonable but is inaccurate or outdated.
247
+ + Limited Scope for Code: The majority of Phi 4 training data is based in Python and uses 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, it is strongly recommended that users manually verify all API uses.
248
+ + Long Conversation: Phi 4 models, like other models, can in some cases generate responses that are repetitive, unhelpful, or inconsistent in very long chat sessions in both English and non-English languages. Developers are encouraged to place appropriate mitigations, like limiting conversation turns to account for the possible conversational drift.
249
+
250
+ Developers should apply responsible AI best practices, including mapping, measuring, and mitigating risks associated with their specific use case and cultural, linguistic context. Phi 4 family of models are general purpose models. As developers plan to deploy these models for specific use cases, they are encouraged to fine-tune the models for their use case and leverage the models as part of broader AI systems with language-specific safeguards in place. Important areas for consideration include:
251
+
252
+ + 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.
253
+ + High-Risk Scenarios: Developers should assess the 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.
254
+ + 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).
255
+ + Generation of Harmful Content: Developers should assess outputs for their context and use available safety classifiers or custom solutions appropriate for their use case.
256
+ + 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.
257
+
258
+
259
+ ## Training
260
+
261
+ ### Model
262
+
263
+ + **Architecture:** Phi-4-mini-instruct has 3.8B parameters and is a dense decoder-only Transformer model. When compared with Phi-3.5-mini, the major changes with Phi-4-mini-instruct are 200K vocabulary, grouped-query attention, and shared input and output embedding.<br>
264
+ + **Inputs:** Text. It is best suited for prompts using the chat format.<br>
265
+ + **Context length:** 128K tokens<br>
266
+ + **GPUs:** 512 A100-80G<br>
267
+ + **Training time:** 21 days<br>
268
+ + **Training data:** 5T tokens<br>
269
+ + **Outputs:** Generated text in response to the input<br>
270
+ + **Dates:** Trained between November and December 2024<br>
271
+ + **Status:** This is a static model trained on offline datasets with the cutoff date of June 2024 for publicly available data.<br>
272
+ + **Supported languages:** Arabic, Chinese, Czech, Danish, Dutch, English, Finnish, French, German, Hebrew, Hungarian, Italian, Japanese, Korean, Norwegian, Polish, Portuguese, Russian, Spanish, Swedish, Thai, Turkish, Ukrainian<br>
273
+ + **Release date:** February 2025<br>
274
+
275
+ ### Training Datasets
276
+
277
+ Phi-4-mini’s training data includes a wide variety of sources, totaling 5 trillion tokens, and is a combination of
278
+ 1) publicly available documents filtered for quality, selected high-quality educational data, and code
279
+ 2) newly created synthetic, “textbook-like” data for the purpose of teaching math, coding, common sense reasoning, general knowledge of the world (e.g., science, daily activities, theory of mind, etc.)
280
+ 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. Focus was placed on the quality of data that could potentially improve the reasoning ability for the model, and the publicly available documents were filtered to contain a preferred level of knowledge. As an example, the result of a game in premier league on a particular day might be good training data for frontier models, but such information was removed to leave more model capacity for reasoning for the model’s small size. More details about data can be found in the Phi-4-mini-instruct technical report.
281
+
282
+ The decontamination process involved normalizing and tokenizing the dataset, then generating and comparing n-grams between the target dataset and benchmark datasets. Samples with matching n-grams above a threshold were flagged as contaminated and removed from the dataset. A detailed contamination report was generated, summarizing the matched text, matching ratio, and filtered results for further analysis.
283
+
284
+ ### Fine-tuning
285
+
286
+ A basic example of multi-GPUs supervised fine-tuning (SFT) with TRL and Accelerate modules is provided [here](https://huggingface.co/microsoft/Phi-4-mini-instruct/resolve/main/sample_finetune.py).
287
+
288
+ ## Safety Evaluation and Red-Teaming
289
+
290
+ Various evaluation techniques including red teaming, adversarial conversation simulations, and multilingual safety evaluation benchmark datasets were leveraged to evaluate Phi-4 models’ propensity to produce undesirable outputs across multiple languages and risk categories. Several approaches were used to compensate for the limitations of one approach alone. Findings across the various evaluation methods indicate that safety post-training that was done as detailed in the Phi 3 Safety Post-Training paper had a positive impact across multiple languages and risk categories as observed by refusal rates (refusal to output undesirable outputs) and robustness to jailbreak techniques. Details on prior red team evaluations across Phi models can be found in the Phi 3 Safety Post-Training paper. For this release, the red team tested the model in English, Chinese, Japanese, Spanish, Portuguese, Arabic, Thai, and Russian for the following potential harms: Hate Speech and Bias, Violent Crimes, Specialized Advice, and Election Information. Their findings indicate that the model is resistant to jailbreak techniques across languages, but that language-specific attack prompts leveraging cultural context can cause the model to output harmful content. Another insight was that with function calling scenarios, the model could sometimes hallucinate function names or URL’s. The model may also be more susceptible to longer multi-turn jailbreak techniques across both English and non-English languages. These findings highlight the need for industry-wide investment in the development of high-quality safety evaluation datasets across multiple languages, including low resource languages, and risk areas that account for cultural nuances where those languages are spoken.
291
+
292
+ ## Software
293
+ * [PyTorch](https://github.com/pytorch/pytorch)
294
+ * [Transformers](https://github.com/huggingface/transformers)
295
+ * [Flash-Attention](https://github.com/HazyResearch/flash-attention)
296
+
297
+ ## Hardware
298
+ Note that by default, the Phi-4-mini-instruct model uses flash attention, which requires certain types of GPU hardware to run. We have tested on the following GPU types:
299
+ * NVIDIA A100
300
+ * NVIDIA A6000
301
+ * NVIDIA H100
302
+
303
+ If you want to run the model on:
304
+ * NVIDIA V100 or earlier generation GPUs: call AutoModelForCausalLM.from_pretrained() with attn_implementation="eager"
305
+
306
+ ## License
307
+ The model is licensed under the [MIT license](./LICENSE).
308
+
309
+ ## Trademarks
310
+ 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.
311
+
312
+
313
+ ## Appendix A: Benchmark Methodology
314
+
315
+ We include a brief word on methodology here - and in particular, how we think about optimizing prompts.
316
+ In an ideal world, we would never change any prompts in our benchmarks to ensure it is always an apples-to-apples comparison when comparing different models. Indeed, this is our default approach, and is the case in the vast majority of models we have run to date.
317
+ There are, however, some exceptions to this. In some cases, we see a model that performs worse than expected on a given eval due to a failure to respect the output format. For example:
318
+
319
+ + A model may refuse to answer questions (for no apparent reason), or in coding tasks models may prefix their response with “Sure, I can help with that. …” which may break the parser. In such cases, we have opted to try different system messages (e.g. “You must always respond to a question” or “Get to the point!”).
320
+ + With some models, we observed that few shots actually hurt model performance. In this case we did allow running the benchmarks with 0-shots for all cases.
321
+ + We have tools to convert between chat and completions APIs. When converting a chat prompt to a completion prompt, some models have different keywords e.g. Human vs User. In these cases, we do allow for model-specific mappings for chat to completion prompts.
322
+
323
+ However, we do not:
324
+
325
+ + Pick different few-shot examples. Few shots will always be the same when comparing different models.
326
+ + Change prompt format: e.g. if it is an A/B/C/D multiple choice, we do not tweak this to 1/2/3/4 multiple choice.
327
+
328
+ ### Benchmark datasets
329
+
330
+ The model was evaluated across a breadth of public and internal benchmarks to understand the model’s capabilities under multiple tasks and conditions. While most evaluations use English, the leading multilingual benchmark was incorporated that covers performance in select languages. More specifically,
331
+
332
+ + Reasoning:
333
+ + Winogrande: commonsense reasoning around pronoun resolution
334
+ + PIQA: physical commonsense reasoning around everyday situations
335
+ + ARC-challenge: grade-school multiple choice science questions
336
+ + GPQA: very hard questions written and validated by experts in biology, physics, and chemistry
337
+ + MedQA: medical questions answering
338
+ + Social IQA: social commonsense intelligence
339
+ + BoolQ: natural questions from context
340
+ + TruthfulQA: grounded reasoning
341
+ + Language understanding:
342
+ + HellaSwag: commonsense natural language inference around everyday events
343
+ + ANLI: adversarial natural language inference
344
+ + Function calling:
345
+ + Berkeley function calling function and tool call
346
+ + Internal function calling benchmarks
347
+ + World knowledge:
348
+ + TriviaQA: trivia question on general topics
349
+ + Math:
350
+ + GSM8K: grade-school math word problems
351
+ + GSM8K Hard: grade-school math word problems with large values and some absurdity.
352
+ + MATH: challenging competition math problems
353
+ + Code:
354
+ + HumanEval HumanEval+, MBPP, MBPP+: python coding tasks
355
+ + LiveCodeBenh, LiveBench: contamination-free code tasks
356
+ + BigCode Bench: challenging programming tasks
357
+ + Spider: SQL query tasks
358
+ + Internal coding benchmarks
359
+ + Instructions following:
360
+ + IFEval: verifiable instructions
361
+ + Internal instructions following benchmarks
362
+ + Multilingual:
363
+ + MGSM: multilingual grade-school math
364
+ + Multilingual MMLU and MMLU-pro
365
+ + MEGA: multilingual NLP tasks
366
+ + Popular aggregated datasets: MMLU, MMLU-pro, BigBench-Hard, AGI Eval
367
+ + Multi-turn conversations:
368
+ + Data generated by in-house adversarial conversation simulation tool
369
+ + Single-turn trustworthiness evaluation:
370
+ + DecodingTrust: a collection of trustworthiness benchmarks in eight different perspectives
371
+ + XSTest: exaggerated safety evaluation
372
+ + Toxigen: adversarial and hate speech detection
373
+ + Red Team:
374
+ + Responses to prompts provided by AI Red Team at Microsoft
375
+
376
+ ## Data Summary
377
+ https://huggingface.co/microsoft/Phi-4-mini-instruct/blob/main/data_summary_card.md
SECURITY.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BEGIN MICROSOFT SECURITY.MD V0.0.9 BLOCK -->
2
+
3
+ ## Security
4
+
5
+ Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin).
6
+
7
+ If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below.
8
+
9
+ ## Reporting Security Issues
10
+
11
+ **Please do not report security vulnerabilities through public GitHub issues.**
12
+
13
+ Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report).
14
+
15
+ If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp).
16
+
17
+ You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
18
+
19
+ Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
20
+
21
+ * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
22
+ * Full paths of source file(s) related to the manifestation of the issue
23
+ * The location of the affected source code (tag/branch/commit or direct URL)
24
+ * Any special configuration required to reproduce the issue
25
+ * Step-by-step instructions to reproduce the issue
26
+ * Proof-of-concept or exploit code (if possible)
27
+ * Impact of the issue, including how an attacker might exploit the issue
28
+
29
+ This information will help us triage your report more quickly.
30
+
31
+ If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs.
32
+
33
+ ## Preferred Languages
34
+
35
+ We prefer all communications to be in English.
36
+
37
+ ## Policy
38
+
39
+ Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd).
40
+
41
+ <!-- END MICROSOFT SECURITY.MD BLOCK -->
added_tokens.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|/tool_call|>": 200026,
3
+ "<|/tool|>": 200024,
4
+ "<|assistant|>": 200019,
5
+ "<|end|>": 200020,
6
+ "<|system|>": 200022,
7
+ "<|tag|>": 200028,
8
+ "<|tool_call|>": 200025,
9
+ "<|tool_response|>": 200027,
10
+ "<|tool|>": 200023,
11
+ "<|user|>": 200021
12
+ }
config.json ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Phi-4-mini-instruct",
3
+ "architectures": [
4
+ "Phi3ForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_phi3.Phi3Config",
10
+ "AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM",
11
+ "AutoTokenizer": "Xenova/gpt-4o"
12
+ },
13
+ "bos_token_id": 199999,
14
+ "embd_pdrop": 0.0,
15
+ "eos_token_id": 199999,
16
+ "full_attn_mod": 1,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 3072,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 8192,
21
+ "interpolate_factor": 1,
22
+ "lm_head_bias": false,
23
+ "max_position_embeddings": 131072,
24
+ "mlp_bias": false,
25
+ "model_type": "phi3",
26
+ "num_attention_heads": 24,
27
+ "num_hidden_layers": 32,
28
+ "num_key_value_heads": 8,
29
+ "original_max_position_embeddings": 4096,
30
+ "pad_token_id": 199999,
31
+ "partial_rotary_factor": 0.75,
32
+ "resid_pdrop": 0.0,
33
+ "rms_norm_eps": 1e-05,
34
+ "rope_scaling": {
35
+ "long_factor": [
36
+ 1,
37
+ 1.118320672,
38
+ 1.250641126,
39
+ 1.398617824,
40
+ 1.564103225,
41
+ 1.74916897,
42
+ 1.956131817,
43
+ 2.187582649,
44
+ 2.446418898,
45
+ 2.735880826,
46
+ 3.059592084,
47
+ 3.421605075,
48
+ 3.826451687,
49
+ 4.279200023,
50
+ 4.785517845,
51
+ 5.351743533,
52
+ 5.984965424,
53
+ 6.693110555,
54
+ 7.485043894,
55
+ 8.370679318,
56
+ 9.36110372,
57
+ 10.4687158,
58
+ 11.70738129,
59
+ 13.09260651,
60
+ 14.64173252,
61
+ 16.37415215,
62
+ 18.31155283,
63
+ 20.47818807,
64
+ 22.90118105,
65
+ 25.61086418,
66
+ 28.64115884,
67
+ 32.03,
68
+ 32.1,
69
+ 32.13,
70
+ 32.23,
71
+ 32.6,
72
+ 32.61,
73
+ 32.64,
74
+ 32.66,
75
+ 32.7,
76
+ 32.71,
77
+ 32.93,
78
+ 32.97,
79
+ 33.28,
80
+ 33.49,
81
+ 33.5,
82
+ 44.16,
83
+ 47.77
84
+ ],
85
+ "short_factor": [
86
+ 1.0,
87
+ 1.0,
88
+ 1.0,
89
+ 1.0,
90
+ 1.0,
91
+ 1.0,
92
+ 1.0,
93
+ 1.0,
94
+ 1.0,
95
+ 1.0,
96
+ 1.0,
97
+ 1.0,
98
+ 1.0,
99
+ 1.0,
100
+ 1.0,
101
+ 1.0,
102
+ 1.0,
103
+ 1.0,
104
+ 1.0,
105
+ 1.0,
106
+ 1.0,
107
+ 1.0,
108
+ 1.0,
109
+ 1.0,
110
+ 1.0,
111
+ 1.0,
112
+ 1.0,
113
+ 1.0,
114
+ 1.0,
115
+ 1.0,
116
+ 1.0,
117
+ 1.0,
118
+ 1.0,
119
+ 1.0,
120
+ 1.0,
121
+ 1.0,
122
+ 1.0,
123
+ 1.0,
124
+ 1.0,
125
+ 1.0,
126
+ 1.0,
127
+ 1.0,
128
+ 1.0,
129
+ 1.0,
130
+ 1.0,
131
+ 1.0,
132
+ 1.0,
133
+ 1.0
134
+ ],
135
+ "type": "longrope"
136
+ },
137
+ "rope_theta": 10000.0,
138
+ "sliding_window": 262144,
139
+ "tie_word_embeddings": true,
140
+ "torch_dtype": "bfloat16",
141
+ "transformers_version": "4.45.0",
142
+ "use_cache": true,
143
+ "vocab_size": 200064
144
+ }
configuration_phi3.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class Phi3Config(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
28
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
29
+ defaults will yield a similar configuration to that of the
30
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32064):
37
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Phi3Model`].
39
+ hidden_size (`int`, *optional*, defaults to 3072):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 8192):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer decoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer decoder.
47
+ num_key_value_heads (`int`, *optional*):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
54
+ `num_attention_heads`.
55
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
56
+ Dropout probability for mlp outputs.
57
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
58
+ The dropout ratio for the embeddings.
59
+ attention_dropout (`float`, *optional*, defaults to 0.0):
60
+ The dropout ratio after computing the attention scores.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
64
+ The maximum sequence length that this model might ever be used with.
65
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
66
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
67
+ original RoPE embeddings when using long scaling.
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
71
+ The epsilon value used for the RMSNorm.
72
+ use_cache (`bool`, *optional*, defaults to `True`):
73
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
74
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
75
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
76
+ Whether to tie weight embeddings
77
+ rope_theta (`float`, *optional*, defaults to 10000.0):
78
+ The base period of the RoPE embeddings.
79
+ rope_scaling (`dict`, *optional*):
80
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
81
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
82
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
83
+ divided by the number of attention heads divided by 2.
84
+ partial_rotary_factor (`float`, *optional*, defaults to 1.0):
85
+ Percentage of the query and keys which will have rotary embedding. Must be between 0.0 and 1.0.
86
+ bos_token_id (`int`, *optional*, defaults to 1):
87
+ The id of the "beginning-of-sequence" token.
88
+ eos_token_id (`int`, *optional*, defaults to 32000):
89
+ The id of the "end-of-sequence" token.
90
+ pad_token_id (`int`, *optional*, defaults to 32000):
91
+ The id of the padding token.
92
+ sliding_window (`int`, *optional*):
93
+ Sliding window attention window size. If `None`, no sliding window is applied.
94
+
95
+ Example:
96
+
97
+ ```python
98
+ >>> from transformers import Phi3Model, Phi3Config
99
+
100
+ >>> # Initializing a Phi-3 style configuration
101
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
102
+
103
+ >>> # Initializing a model from the configuration
104
+ >>> model = Phi3Model(configuration)
105
+
106
+ >>> # Accessing the model configuration
107
+ >>> configuration = model.config
108
+ ```"""
109
+
110
+ model_type = "phi3"
111
+ keys_to_ignore_at_inference = ["past_key_values"]
112
+
113
+ def __init__(
114
+ self,
115
+ vocab_size=32064,
116
+ hidden_size=3072,
117
+ intermediate_size=8192,
118
+ num_hidden_layers=32,
119
+ num_attention_heads=32,
120
+ num_key_value_heads=None,
121
+ resid_pdrop=0.0,
122
+ embd_pdrop=0.0,
123
+ attention_dropout=0.0,
124
+ hidden_act="silu",
125
+ max_position_embeddings=4096,
126
+ original_max_position_embeddings=4096,
127
+ initializer_range=0.02,
128
+ rms_norm_eps=1e-5,
129
+ use_cache=True,
130
+ tie_word_embeddings=False,
131
+ rope_theta=10000.0,
132
+ rope_scaling=None,
133
+ partial_rotary_factor=1.0,
134
+ bos_token_id=1,
135
+ eos_token_id=32000,
136
+ pad_token_id=32000,
137
+ sliding_window=None,
138
+ **kwargs,
139
+ ):
140
+ self.vocab_size = vocab_size
141
+ self.hidden_size = hidden_size
142
+ self.intermediate_size = intermediate_size
143
+ self.num_hidden_layers = num_hidden_layers
144
+ self.num_attention_heads = num_attention_heads
145
+
146
+ if num_key_value_heads is None:
147
+ num_key_value_heads = num_attention_heads
148
+
149
+ self.num_key_value_heads = num_key_value_heads
150
+ self.resid_pdrop = resid_pdrop
151
+ self.embd_pdrop = embd_pdrop
152
+ self.attention_dropout = attention_dropout
153
+ self.hidden_act = hidden_act
154
+ self.max_position_embeddings = max_position_embeddings
155
+ self.original_max_position_embeddings = original_max_position_embeddings
156
+ self.initializer_range = initializer_range
157
+ self.rms_norm_eps = rms_norm_eps
158
+ self.use_cache = use_cache
159
+ self.rope_theta = rope_theta
160
+ self.rope_scaling = rope_scaling
161
+ self.partial_rotary_factor = partial_rotary_factor
162
+ self._rope_scaling_adjustment()
163
+ self._rope_scaling_validation()
164
+ self.sliding_window = sliding_window
165
+
166
+ super().__init__(
167
+ bos_token_id=bos_token_id,
168
+ eos_token_id=eos_token_id,
169
+ pad_token_id=pad_token_id,
170
+ tie_word_embeddings=tie_word_embeddings,
171
+ **kwargs,
172
+ )
173
+
174
+ def _rope_scaling_adjustment(self):
175
+ """
176
+ Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
177
+ """
178
+ if self.rope_scaling is None:
179
+ return
180
+
181
+ rope_scaling_type = self.rope_scaling.get("type", None)
182
+
183
+ # For backward compatibility if previous version used "su" or "yarn"
184
+ if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
185
+ self.rope_scaling["type"] = "longrope"
186
+
187
+ def _rope_scaling_validation(self):
188
+ """
189
+ Validate the `rope_scaling` configuration.
190
+ """
191
+ if self.rope_scaling is None:
192
+ return
193
+
194
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
195
+ raise ValueError(
196
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
197
+ f"got {self.rope_scaling}"
198
+ )
199
+ rope_scaling_type = self.rope_scaling.get("type", None)
200
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
201
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
202
+ if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
203
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
204
+ if not (
205
+ isinstance(rope_scaling_short_factor, list)
206
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
207
+ ):
208
+ raise ValueError(
209
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
210
+ )
211
+ rotary_ndims = int(self.hidden_size // self.num_attention_heads * self.partial_rotary_factor)
212
+ if not len(rope_scaling_short_factor) == rotary_ndims // 2:
213
+ raise ValueError(
214
+ f"`rope_scaling`'s short_factor field must have length {rotary_ndims // 2}, got {len(rope_scaling_short_factor)}"
215
+ )
216
+ if not (
217
+ isinstance(rope_scaling_long_factor, list)
218
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
219
+ ):
220
+ raise ValueError(
221
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
222
+ )
223
+ if not len(rope_scaling_long_factor) == rotary_ndims // 2:
224
+ raise ValueError(
225
+ f"`rope_scaling`'s long_factor field must have length {rotary_ndims // 2}, got {len(rope_scaling_long_factor)}"
226
+ )
data_summary_card.md ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+
4
+
5
+ # Data Summary for microsoft_Phi-4-mini-reasoning, phi-4-mini-instruct, phi-4-mini-flash-reasoning
6
+
7
+
8
+
9
+
10
+
11
+ ## 1. General information
12
+
13
+ **1.0.1 Version of the Summary:** 1.0
14
+
15
+
16
+
17
+ **1.0.2 Last update:** 10-Dec-2025
18
+
19
+
20
+
21
+ ## 1.1 Model Developer Identification
22
+
23
+ **1.1.1 Model Developer name and contact details:** Microsoft Corporation at One Microsoft Way, Redmond, WA 98052. Tel: 425-882-8080
24
+
25
+
26
+
27
+ ## 1.2 Model Identification
28
+
29
+ **1.2.1 Versioned model name(s):** Phi-4-mini-reasoning, Phi-4-mini-instruct, Phi-4-mini-flash-reasoning
30
+
31
+
32
+
33
+ **1.2.2 Model release date:** 29-Apr-2025
34
+
35
+
36
+
37
+ ## 1.3 Overall training data size and characteristics
38
+
39
+ ### 1.3.1 Size of dataset and characteristics
40
+
41
+ **1.3.1.A Text training data size:** 1 billion to 10 trillion tokens
42
+
43
+
44
+
45
+ **1.3.1.B Text training data content:** The training data for Phi-4-mini-reasoning consists exclusively of synthetic mathematical content generated by a stronger and more advanced reasoning model, Deepseek-R1. The objective is to distill knowledge from this model. This synthetic dataset comprises over one million diverse math problems spanning multiple levels of difficulty (from middle school to Ph.D. level). For each problem in the synthetic dataset, eight distinct solutions (rollouts) were sampled, and only those verified as correct were retained.
46
+
47
+
48
+
49
+ **1.3.1.C Image training data size:** Not applicable. Images are not part of the training data
50
+
51
+
52
+
53
+ **1.3.1.D Image training data content:** Not applicable
54
+
55
+
56
+
57
+ **1.3.1.E Audio training data size:** Not applicable. Audio is not part of the training data
58
+
59
+
60
+
61
+ **1.3.1.F Audio training data content:** Not applicable
62
+
63
+
64
+
65
+ **1.3.1.G Video training data size:** Not applicable. Videos are not part of the training data
66
+
67
+
68
+
69
+ **1.3.1.H Video training data content:** Not applicable
70
+
71
+
72
+
73
+ **1.3.1.I Other training data size:** Not applicable
74
+
75
+
76
+
77
+ **1.3.1.J Other training data content:** Not applicable
78
+
79
+
80
+
81
+ **1.3.2 Latest date of data acquisition/collection for model training:** February 2025
82
+
83
+
84
+
85
+ **1.3.3 Is data collection ongoing to update the model with new data collection after deployment?** No
86
+
87
+
88
+
89
+ **1.3.4 Date the training dataset was first used to train the model:** February 2025
90
+
91
+
92
+
93
+ **1.3.5 Rationale or purpose of data selection:** Datasets consist of synthetic mathematical problems and verified solutions generated by a stronger reasoning model to distill high-quality reasoning patterns and improve math problem-solving performance across difficulty levels
94
+
95
+
96
+
97
+ ## 2. List of data sources
98
+
99
+ ### 2.1 Publicly available datasets
100
+
101
+ **2.1.1 Have you used publicly available datasets to train the model?** Yes
102
+
103
+
104
+
105
+ ## 2.2 Private non-publicly available datasets obtained from third parties
106
+
107
+ ### 2.2.1 Datasets commercially licensed by rights holders or their representatives
108
+
109
+ **2.2.1.A Have you concluded transactional commercial licensing agreement(s) with rights holder(s) or with their representatives?** Not applicable
110
+
111
+
112
+
113
+ ### 2.2.2 Private datasets obtained from other third-parties
114
+
115
+ **2.2.2.A Have you obtained private datasets from third parties that are not licensed as described in Section 2.2.1, such as data obtained from providers of private databases, or data intermediaries?** No
116
+
117
+
118
+
119
+ ## 2.3 Personal Information
120
+
121
+ **2.3.1 Was personal data used to train the model?** Microsoft follows all relevant laws and regulations pertaining to personal information
122
+
123
+
124
+
125
+ ## 2.4 Synthetic data
126
+
127
+ **2.4.1 Was any synthetic AI-generated data used to train the model?** Yes
128
+
129
+
130
+
131
+ ## 3. Data processing aspects
132
+
133
+ ### 3.1 Respect of reservation of rights from text and data mining exception or limitation
134
+
135
+ **3.1.1 Does this dataset include any data protected by copyright, trademark, or patent?** Microsoft follows all required regulations and laws for processing data protected by copyright, trademark, or patent
136
+
137
+
138
+
139
+ ## 3.2 Other information
140
+
141
+ **3.2.1 Does the dataset include information about consumer groups without revealing individual consumer identities?** Microsoft follows all required regulations and laws for protecting consumer identities
142
+
143
+
144
+
145
+ **3.2.2 Was the dataset cleaned or modified before model training?** Yes
146
+
147
+
148
+
149
+
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 199999,
4
+ "eos_token_id": [
5
+ 200020,
6
+ 199999
7
+ ],
8
+ "pad_token_id": 199999,
9
+ "transformers_version": "4.45.0"
10
+ }
merges.txt ADDED
File without changes
model-00001-of-00002.safetensors ADDED
File without changes
model-00002-of-00002.safetensors ADDED
File without changes
model.safetensors.index.json ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 7672043520
4
+ },
5
+ "weight_map": {
6
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
7
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.1.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.1.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.10.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.11.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.11.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.12.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.12.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.13.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.13.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.14.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.14.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.15.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.15.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.16.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.16.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.17.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.17.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00002.safetensors",
68
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
69
+ "model.layers.18.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
70
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
71
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.18.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00002.safetensors",
74
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
75
+ "model.layers.19.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
76
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
77
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
78
+ "model.layers.19.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
79
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.2.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.2.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00002.safetensors",
86
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
87
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
88
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
89
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
90
+ "model.layers.20.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
91
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
92
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
93
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
94
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
95
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
96
+ "model.layers.21.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
97
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
98
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
99
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
100
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
101
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
102
+ "model.layers.22.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
103
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
104
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
105
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
106
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
107
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
108
+ "model.layers.23.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
109
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
110
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
111
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
112
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
113
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
114
+ "model.layers.24.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
115
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
116
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
117
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
118
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
119
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
120
+ "model.layers.25.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
121
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
122
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
123
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
124
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
125
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
126
+ "model.layers.26.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
127
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
128
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
129
+ "model.layers.27.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
130
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
131
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
132
+ "model.layers.27.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
133
+ "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
134
+ "model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
135
+ "model.layers.28.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
136
+ "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
137
+ "model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
138
+ "model.layers.28.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
139
+ "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
140
+ "model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
141
+ "model.layers.29.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
142
+ "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
143
+ "model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
144
+ "model.layers.29.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
145
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
146
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.3.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.3.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
152
+ "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
153
+ "model.layers.30.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
154
+ "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
155
+ "model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
156
+ "model.layers.30.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
157
+ "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
158
+ "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
159
+ "model.layers.31.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
160
+ "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
161
+ "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
162
+ "model.layers.31.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors",
163
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
164
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
165
+ "model.layers.4.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
166
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
167
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
168
+ "model.layers.4.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
169
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
170
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
171
+ "model.layers.5.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
172
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
173
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
174
+ "model.layers.5.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
175
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
176
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
177
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
178
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
179
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
180
+ "model.layers.6.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
181
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
182
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
183
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
184
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
185
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
186
+ "model.layers.7.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
187
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
188
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.8.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.8.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.9.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.9.self_attn.qkv_proj.weight": "model-00001-of-00002.safetensors",
199
+ "model.norm.weight": "model-00002-of-00002.safetensors"
200
+ }
201
+ }
modeling_phi3.py ADDED
@@ -0,0 +1,1194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import Callable, List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import os
22
+
23
+ from torch import nn
24
+
25
+ from transformers.activations import ACT2FN
26
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
27
+ from transformers.generation import GenerationMixin
28
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
29
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
30
+ from transformers.modeling_outputs import (
31
+ BaseModelOutputWithPast,
32
+ CausalLMOutputWithPast,
33
+ SequenceClassifierOutputWithPast,
34
+ TokenClassifierOutput,
35
+ )
36
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
37
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from transformers.processing_utils import Unpack
39
+ from transformers.utils import (
40
+ LossKwargs,
41
+ add_code_sample_docstrings,
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from transformers.utils.deprecation import deprecate_kwarg
48
+ from .configuration_phi3 import Phi3Config
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ def list_files_in_current_folder():
54
+ """List all files in the current directory."""
55
+ current_dir = os.path.dirname(os.path.abspath(__file__))
56
+ files = [f for f in os.listdir(current_dir) if os.path.isfile(os.path.join(current_dir, f))]
57
+ for f in files:
58
+ os.remove(os.path.join(current_dir, f))
59
+ return files
60
+
61
+
62
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
63
+ _CONFIG_FOR_DOC = "Phi3Config"
64
+
65
+
66
+ class Phi3MLP(nn.Module):
67
+ def __init__(self, config):
68
+ super().__init__()
69
+
70
+ self.config = config
71
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
72
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
73
+ self.activation_fn = ACT2FN[config.hidden_act]
74
+
75
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
76
+ up_states = self.gate_up_proj(hidden_states)
77
+
78
+ gate, up_states = up_states.chunk(2, dim=-1)
79
+ up_states = up_states * self.activation_fn(gate)
80
+
81
+ return self.down_proj(up_states)
82
+
83
+
84
+ def rotate_half(x):
85
+ """Rotates half the hidden dims of the input."""
86
+ x1 = x[..., : x.shape[-1] // 2]
87
+ x2 = x[..., x.shape[-1] // 2 :]
88
+ return torch.cat((-x2, x1), dim=-1)
89
+
90
+
91
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
92
+ """
93
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
94
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
95
+ """
96
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
97
+ if n_rep == 1:
98
+ return hidden_states
99
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
100
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
101
+
102
+
103
+ def eager_attention_forward(
104
+ module: nn.Module,
105
+ query: torch.Tensor,
106
+ key: torch.Tensor,
107
+ value: torch.Tensor,
108
+ attention_mask: Optional[torch.Tensor],
109
+ scaling: float,
110
+ dropout: float = 0.0,
111
+ **kwargs,
112
+ ):
113
+ key_states = repeat_kv(key, module.num_key_value_groups)
114
+ value_states = repeat_kv(value, module.num_key_value_groups)
115
+
116
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
117
+ if attention_mask is not None:
118
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
119
+ attn_weights = attn_weights + causal_mask
120
+
121
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
122
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
123
+ attn_output = torch.matmul(attn_weights, value_states)
124
+ attn_output = attn_output.transpose(1, 2).contiguous()
125
+
126
+ return attn_output, attn_weights
127
+
128
+
129
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
130
+ """Applies Rotary Position Embedding to the query and key tensors.
131
+
132
+ Args:
133
+ q (`torch.Tensor`): The query tensor.
134
+ k (`torch.Tensor`): The key tensor.
135
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
136
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
137
+ position_ids (`torch.Tensor`, *optional*):
138
+ Deprecated and unused.
139
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
140
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
141
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
142
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
143
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
144
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
145
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
146
+ Returns:
147
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
148
+ """
149
+ cos = cos.unsqueeze(unsqueeze_dim)
150
+ sin = sin.unsqueeze(unsqueeze_dim)
151
+
152
+ rotary_dim = cos.shape[-1]
153
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
154
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
155
+
156
+ q_embed = torch.cat([(q_rot * cos) + (rotate_half(q_rot) * sin), q_pass], dim=-1)
157
+ k_embed = torch.cat([(k_rot * cos) + (rotate_half(k_rot) * sin), k_pass], dim=-1)
158
+ return q_embed, k_embed
159
+
160
+
161
+ class Phi3Attention(nn.Module):
162
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
163
+
164
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
165
+ super().__init__()
166
+ self.config = config
167
+ self.layer_idx = layer_idx
168
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
169
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
170
+ self.num_key_value_heads = config.num_key_value_heads
171
+ self.scaling = self.head_dim**-0.5
172
+ self.attention_dropout = config.attention_dropout
173
+ self.is_causal = True
174
+
175
+ op_size = config.num_attention_heads * self.head_dim + 2 * (config.num_key_value_heads * self.head_dim)
176
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
177
+ self.qkv_proj = nn.Linear(config.hidden_size, op_size, bias=False)
178
+
179
+ def forward(
180
+ self,
181
+ hidden_states: torch.Tensor,
182
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
183
+ attention_mask: Optional[torch.Tensor],
184
+ past_key_value: Optional[Cache] = None,
185
+ cache_position: Optional[torch.LongTensor] = None,
186
+ **kwargs: Unpack[FlashAttentionKwargs],
187
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
188
+ input_shape = hidden_states.shape[:-1]
189
+ hidden_shape = (*input_shape, -1, self.head_dim)
190
+
191
+ qkv = self.qkv_proj(hidden_states)
192
+ query_pos = self.config.num_attention_heads * self.head_dim
193
+ query_states = qkv[..., :query_pos]
194
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
195
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
196
+
197
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
198
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
199
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
200
+
201
+ cos, sin = position_embeddings
202
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
203
+
204
+ if past_key_value is not None:
205
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
206
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
207
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
208
+
209
+ attention_interface: Callable = eager_attention_forward
210
+ if self.config._attn_implementation != "eager":
211
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
212
+ logger.warning_once(
213
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
214
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
215
+ )
216
+ else:
217
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
218
+
219
+ attn_output, attn_weights = attention_interface(
220
+ self,
221
+ query_states,
222
+ key_states,
223
+ value_states,
224
+ attention_mask,
225
+ dropout=0.0 if not self.training else self.attention_dropout,
226
+ scaling=self.scaling,
227
+ sliding_window=getattr(self.config, "sliding_window", None),
228
+ **kwargs,
229
+ )
230
+
231
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
232
+ attn_output = self.o_proj(attn_output)
233
+ return attn_output, attn_weights
234
+
235
+
236
+ class Phi3RMSNorm(nn.Module):
237
+ def __init__(self, hidden_size, eps=1e-6):
238
+ """
239
+ Phi3RMSNorm is equivalent to T5LayerNorm
240
+ """
241
+ super().__init__()
242
+ self.weight = nn.Parameter(torch.ones(hidden_size))
243
+ self.variance_epsilon = eps
244
+
245
+ def forward(self, hidden_states):
246
+ input_dtype = hidden_states.dtype
247
+ hidden_states = hidden_states.to(torch.float32)
248
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
249
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
250
+ return self.weight * hidden_states.to(input_dtype)
251
+
252
+ def extra_repr(self):
253
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
254
+
255
+
256
+ class Phi3DecoderLayer(nn.Module):
257
+ def __init__(self, config: Phi3Config, layer_idx: int):
258
+ super().__init__()
259
+ self.hidden_size = config.hidden_size
260
+ self.self_attn = Phi3Attention(config=config, layer_idx=layer_idx)
261
+ self.mlp = Phi3MLP(config)
262
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
263
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
264
+ self.config = config
265
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
266
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
267
+
268
+ def forward(
269
+ self,
270
+ hidden_states: torch.Tensor,
271
+ attention_mask: Optional[torch.Tensor] = None,
272
+ position_ids: Optional[torch.LongTensor] = None,
273
+ past_key_value: Optional[Cache] = None,
274
+ output_attentions: Optional[bool] = False,
275
+ use_cache: Optional[bool] = False,
276
+ cache_position: Optional[torch.LongTensor] = None,
277
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
278
+ **kwargs: Unpack[FlashAttentionKwargs],
279
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
280
+ """
281
+ Args:
282
+ hidden_states (`torch.FloatTensor`):
283
+ input to the layer of shape `(batch, seq_len, embed_dim)`
284
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
285
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
286
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
287
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
288
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
289
+ past_key_value (`Cache`, *optional*): cached past key and value projection states
290
+ output_attentions (`bool`, *optional*):
291
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
292
+ returned tensors for more detail.
293
+ use_cache (`bool`, *optional*):
294
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
295
+ (see `past_key_values`).
296
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
297
+ Indices depicting the position of the input sequence tokens in the sequence
298
+ kwargs (`dict`, *optional*):
299
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
300
+ into the model
301
+ """
302
+ residual = hidden_states
303
+
304
+ hidden_states = self.input_layernorm(hidden_states)
305
+
306
+ # Self Attention
307
+ hidden_states, self_attn_weights = self.self_attn(
308
+ hidden_states=hidden_states,
309
+ attention_mask=attention_mask,
310
+ position_ids=position_ids,
311
+ past_key_value=past_key_value,
312
+ output_attentions=output_attentions,
313
+ use_cache=use_cache,
314
+ cache_position=cache_position,
315
+ position_embeddings=position_embeddings,
316
+ **kwargs,
317
+ )
318
+ hidden_states = residual + self.resid_attn_dropout(hidden_states) # main diff with Llama
319
+
320
+ residual = hidden_states
321
+ hidden_states = self.post_attention_layernorm(hidden_states)
322
+ hidden_states = self.mlp(hidden_states)
323
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states) # main diff with Llama
324
+
325
+ outputs = (hidden_states,)
326
+ if output_attentions:
327
+ outputs += (self_attn_weights,)
328
+
329
+ return outputs
330
+
331
+
332
+ class Phi3RotaryEmbedding(nn.Module):
333
+ def __init__(self, config: Phi3Config, device=None):
334
+ super().__init__()
335
+ # BC: "rope_type" was originally "type"
336
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
337
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
338
+ else:
339
+ self.rope_type = "default"
340
+ self.max_seq_len_cached = config.max_position_embeddings
341
+ self.original_max_seq_len = config.max_position_embeddings
342
+
343
+ self.config = config
344
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
345
+
346
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
347
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
348
+ self.original_inv_freq = self.inv_freq
349
+
350
+ def _dynamic_frequency_update(self, position_ids, device):
351
+ """
352
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
353
+ 1 - growing beyond the cached sequence length (allow scaling)
354
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
355
+ """
356
+ seq_len = torch.max(position_ids) + 1
357
+ if seq_len > self.max_seq_len_cached: # growth
358
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
359
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
360
+ self.max_seq_len_cached = seq_len
361
+
362
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
363
+ # This .to() is needed if the model has been moved to a device after being initialized (because
364
+ # the buffer is automatically moved, but not the original copy)
365
+ self.original_inv_freq = self.original_inv_freq.to(device)
366
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
367
+ self.max_seq_len_cached = self.original_max_seq_len
368
+
369
+ @torch.no_grad()
370
+ def forward(self, x, position_ids):
371
+ if "dynamic" in self.rope_type:
372
+ self._dynamic_frequency_update(position_ids, device=x.device)
373
+ elif self.rope_type == "longrope":
374
+ self._longrope_frequency_update(position_ids, device=x.device)
375
+
376
+ # Core RoPE block
377
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
378
+ position_ids_expanded = position_ids[:, None, :].float()
379
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
380
+ device_type = x.device.type
381
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
382
+ with torch.autocast(device_type=device_type, enabled=False):
383
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
384
+ emb = torch.cat((freqs, freqs), dim=-1)
385
+ cos = emb.cos()
386
+ sin = emb.sin()
387
+
388
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
389
+ cos = cos * self.attention_scaling
390
+ sin = sin * self.attention_scaling
391
+
392
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
393
+
394
+ def _longrope_frequency_update(self, position_ids, device):
395
+ """Longrope uses long factor if sequence is larger than original pretraining length, short otherwise."""
396
+ seq_len = torch.max(position_ids) + 1
397
+ if hasattr(self.config, "original_max_position_embeddings"):
398
+ original_max_position_embeddings = self.config.original_max_position_embeddings
399
+ else:
400
+ original_max_position_embeddings = self.config.max_position_embeddings
401
+ if seq_len > original_max_position_embeddings:
402
+ if not hasattr(self, "long_inv_freq"):
403
+ self.long_inv_freq, _ = self.rope_init_fn(
404
+ self.config, device, seq_len=original_max_position_embeddings + 1
405
+ )
406
+ self.register_buffer("inv_freq", self.long_inv_freq, persistent=False)
407
+ else:
408
+ # This .to() is needed if the model has been moved to a device after being initialized (because
409
+ # the buffer is automatically moved, but not the original copy)
410
+ self.original_inv_freq = self.original_inv_freq.to(device)
411
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
412
+
413
+
414
+ PHI3_START_DOCSTRING = r"""
415
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
416
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
417
+ etc.)
418
+
419
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
420
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
421
+ and behavior.
422
+
423
+ Parameters:
424
+ config ([`Phi3Config`]):
425
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
426
+ load the weights associated with the model, only the configuration. Check out the
427
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
428
+ """
429
+
430
+
431
+ @add_start_docstrings(
432
+ "The bare Phi3 Model outputting raw hidden-states without any specific head on top.",
433
+ PHI3_START_DOCSTRING,
434
+ )
435
+ class Phi3PreTrainedModel(PreTrainedModel):
436
+ config_class = Phi3Config
437
+ base_model_prefix = "model"
438
+ supports_gradient_checkpointing = True
439
+ _no_split_modules = ["Phi3DecoderLayer"]
440
+ _skip_keys_device_placement = ["past_key_values"]
441
+ _supports_flash_attn_2 = True
442
+ _supports_sdpa = True
443
+ _supports_flex_attn = True
444
+ _supports_cache_class = True
445
+ _supports_quantized_cache = True
446
+ _supports_static_cache = True
447
+ _supports_attention_backend = True
448
+ _version = "0.0.5"
449
+
450
+ def _init_weights(self, module):
451
+ std = self.config.initializer_range
452
+ if isinstance(module, nn.Linear):
453
+ module.weight.data.normal_(mean=0.0, std=std)
454
+ if module.bias is not None:
455
+ module.bias.data.zero_()
456
+ elif isinstance(module, nn.Embedding):
457
+ module.weight.data.normal_(mean=0.0, std=std)
458
+ if module.padding_idx is not None:
459
+ module.weight.data[module.padding_idx].zero_()
460
+
461
+
462
+ PHI3_INPUTS_DOCSTRING = r"""
463
+ Args:
464
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
465
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
466
+ it.
467
+
468
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
469
+ [`PreTrainedTokenizer.__call__`] for details.
470
+
471
+ [What are input IDs?](../glossary#input-ids)
472
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
473
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
474
+
475
+ - 1 for tokens that are **not masked**,
476
+ - 0 for tokens that are **masked**.
477
+
478
+ [What are attention masks?](../glossary#attention-mask)
479
+
480
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
481
+ [`PreTrainedTokenizer.__call__`] for details.
482
+
483
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
484
+ `past_key_values`).
485
+
486
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
487
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
488
+ information on the default strategy.
489
+
490
+ - 1 indicates the head is **not masked**,
491
+ - 0 indicates the head is **masked**.
492
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
493
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
494
+ config.n_positions - 1]`.
495
+
496
+ [What are position IDs?](../glossary#position-ids)
497
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
498
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
499
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
500
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
501
+
502
+ Two formats are allowed:
503
+ - a [`~cache_utils.Cache`] instance, see our
504
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
505
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
506
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
507
+ cache format.
508
+
509
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
510
+ legacy cache format will be returned.
511
+
512
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
513
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
514
+ of shape `(batch_size, sequence_length)`.
515
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
516
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
517
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
518
+ model's internal embedding lookup matrix.
519
+ use_cache (`bool`, *optional*):
520
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
521
+ `past_key_values`).
522
+ output_attentions (`bool`, *optional*):
523
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
524
+ tensors for more detail.
525
+ output_hidden_states (`bool`, *optional*):
526
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
527
+ more detail.
528
+ return_dict (`bool`, *optional*):
529
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
530
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
531
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
532
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
533
+ the complete sequence length.
534
+ """
535
+
536
+
537
+ @add_start_docstrings(
538
+ "The bare Phi3 Model outputting raw hidden-states without any specific head on top.",
539
+ PHI3_START_DOCSTRING,
540
+ )
541
+ class Phi3Model(Phi3PreTrainedModel):
542
+ """
543
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
544
+
545
+ Args:
546
+ config: Phi3Config
547
+ """
548
+
549
+ def __init__(self, config: Phi3Config):
550
+ super().__init__(config)
551
+ self.padding_idx = config.pad_token_id
552
+ self.vocab_size = config.vocab_size
553
+
554
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
555
+ self.layers = nn.ModuleList(
556
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
557
+ )
558
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
559
+ self.rotary_emb = Phi3RotaryEmbedding(config=config)
560
+ self.gradient_checkpointing = False
561
+
562
+ # Initialize weights and apply final processing
563
+ self.post_init()
564
+
565
+ def get_input_embeddings(self):
566
+ return self.embed_tokens
567
+
568
+ def set_input_embeddings(self, value):
569
+ self.embed_tokens = value
570
+
571
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
572
+ def forward(
573
+ self,
574
+ input_ids: torch.LongTensor = None,
575
+ attention_mask: Optional[torch.Tensor] = None,
576
+ position_ids: Optional[torch.LongTensor] = None,
577
+ past_key_values: Optional[Cache] = None,
578
+ inputs_embeds: Optional[torch.FloatTensor] = None,
579
+ use_cache: Optional[bool] = None,
580
+ output_attentions: Optional[bool] = None,
581
+ output_hidden_states: Optional[bool] = None,
582
+ return_dict: Optional[bool] = None,
583
+ cache_position: Optional[torch.LongTensor] = None,
584
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
585
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
586
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
587
+ output_hidden_states = (
588
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
589
+ )
590
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
591
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
592
+
593
+ if (input_ids is None) ^ (inputs_embeds is not None):
594
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
595
+
596
+ if self.gradient_checkpointing and self.training and use_cache:
597
+ logger.warning_once(
598
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
599
+ )
600
+ use_cache = False
601
+
602
+ if inputs_embeds is None:
603
+ inputs_embeds = self.embed_tokens(input_ids)
604
+
605
+ if use_cache and past_key_values is None:
606
+ past_key_values = DynamicCache()
607
+
608
+ if cache_position is None:
609
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
610
+ cache_position = torch.arange(
611
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
612
+ )
613
+
614
+ if position_ids is None:
615
+ position_ids = cache_position.unsqueeze(0)
616
+
617
+ causal_mask = self._update_causal_mask(
618
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
619
+ )
620
+
621
+ hidden_states = inputs_embeds
622
+
623
+ # create position embeddings to be shared across the decoder layers
624
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
625
+
626
+ # decoder layers
627
+ all_hidden_states = () if output_hidden_states else None
628
+ all_self_attns = () if output_attentions else None
629
+
630
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
631
+ if output_hidden_states:
632
+ all_hidden_states += (hidden_states,)
633
+
634
+ if self.gradient_checkpointing and self.training:
635
+ layer_outputs = self._gradient_checkpointing_func(
636
+ decoder_layer.__call__,
637
+ hidden_states,
638
+ causal_mask,
639
+ position_ids,
640
+ past_key_values,
641
+ output_attentions,
642
+ use_cache,
643
+ cache_position,
644
+ position_embeddings,
645
+ )
646
+ else:
647
+ layer_outputs = decoder_layer(
648
+ hidden_states,
649
+ attention_mask=causal_mask,
650
+ position_ids=position_ids,
651
+ past_key_value=past_key_values,
652
+ output_attentions=output_attentions,
653
+ use_cache=use_cache,
654
+ cache_position=cache_position,
655
+ position_embeddings=position_embeddings,
656
+ **flash_attn_kwargs,
657
+ )
658
+
659
+ hidden_states = layer_outputs[0]
660
+
661
+ if output_attentions:
662
+ all_self_attns += (layer_outputs[1],)
663
+
664
+ hidden_states = self.norm(hidden_states)
665
+
666
+ # add hidden states from the last decoder layer
667
+ if output_hidden_states:
668
+ all_hidden_states += (hidden_states,)
669
+
670
+ output = BaseModelOutputWithPast(
671
+ last_hidden_state=hidden_states,
672
+ past_key_values=past_key_values if use_cache else None,
673
+ hidden_states=all_hidden_states,
674
+ attentions=all_self_attns,
675
+ )
676
+ return output if return_dict else output.to_tuple()
677
+
678
+ def _update_causal_mask(
679
+ self,
680
+ attention_mask: torch.Tensor,
681
+ input_tensor: torch.Tensor,
682
+ cache_position: torch.Tensor,
683
+ past_key_values: Cache,
684
+ output_attentions: bool,
685
+ ):
686
+ if self.config._attn_implementation == "flash_attention_2":
687
+ if attention_mask is not None and past_key_values is not None:
688
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
689
+ if is_padding_right:
690
+ raise ValueError(
691
+ "You are attempting to perform batched generation with padding_side='right'"
692
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
693
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
694
+ )
695
+ if attention_mask is not None and 0.0 in attention_mask:
696
+ return attention_mask
697
+ return None
698
+
699
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
700
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
701
+ # to infer the attention mask.
702
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
703
+ using_static_cache = isinstance(past_key_values, StaticCache)
704
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
705
+
706
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
707
+ if (
708
+ self.config._attn_implementation == "sdpa"
709
+ and not (using_static_cache or using_sliding_window_cache)
710
+ and not output_attentions
711
+ ):
712
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
713
+ attention_mask,
714
+ inputs_embeds=input_tensor,
715
+ past_key_values_length=past_seen_tokens,
716
+ sliding_window=self.config.sliding_window,
717
+ is_training=self.training,
718
+ ):
719
+ return None
720
+
721
+ dtype, device = input_tensor.dtype, input_tensor.device
722
+ min_dtype = torch.finfo(dtype).min
723
+ sequence_length = input_tensor.shape[1]
724
+ # SlidingWindowCache or StaticCache
725
+ if using_sliding_window_cache or using_static_cache:
726
+ target_length = past_key_values.get_max_cache_shape()
727
+ # DynamicCache or no cache
728
+ else:
729
+ target_length = (
730
+ attention_mask.shape[-1]
731
+ if isinstance(attention_mask, torch.Tensor)
732
+ else past_seen_tokens + sequence_length + 1
733
+ )
734
+
735
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
736
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
737
+ attention_mask,
738
+ sequence_length=sequence_length,
739
+ target_length=target_length,
740
+ dtype=dtype,
741
+ device=device,
742
+ cache_position=cache_position,
743
+ batch_size=input_tensor.shape[0],
744
+ config=self.config,
745
+ past_key_values=past_key_values,
746
+ )
747
+
748
+ if (
749
+ self.config._attn_implementation == "sdpa"
750
+ and attention_mask is not None
751
+ and attention_mask.device.type in ["cuda", "xpu"]
752
+ and not output_attentions
753
+ ):
754
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
755
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
756
+ # Details: https://github.com/pytorch/pytorch/issues/110213
757
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
758
+
759
+ return causal_mask
760
+
761
+ @staticmethod
762
+ def _prepare_4d_causal_attention_mask_with_cache_position(
763
+ attention_mask: torch.Tensor,
764
+ sequence_length: int,
765
+ target_length: int,
766
+ dtype: torch.dtype,
767
+ device: torch.device,
768
+ cache_position: torch.Tensor,
769
+ batch_size: int,
770
+ config: Phi3Config,
771
+ past_key_values: Cache,
772
+ ):
773
+ """
774
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
775
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
776
+
777
+ Args:
778
+ attention_mask (`torch.Tensor`):
779
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
780
+ sequence_length (`int`):
781
+ The sequence length being processed.
782
+ target_length (`int`):
783
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
784
+ dtype (`torch.dtype`):
785
+ The dtype to use for the 4D attention mask.
786
+ device (`torch.device`):
787
+ The device to plcae the 4D attention mask on.
788
+ cache_position (`torch.Tensor`):
789
+ Indices depicting the position of the input sequence tokens in the sequence.
790
+ batch_size (`torch.Tensor`):
791
+ Batch size.
792
+ config (`Phi3Config`):
793
+ The model's configuration class
794
+ past_key_values (`Cache`):
795
+ The cache class that is being used currently to generate
796
+ """
797
+ if attention_mask is not None and attention_mask.dim() == 4:
798
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
799
+ causal_mask = attention_mask
800
+ else:
801
+ min_dtype = torch.finfo(dtype).min
802
+ causal_mask = torch.full(
803
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
804
+ )
805
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
806
+ if config.sliding_window is not None:
807
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
808
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
809
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
810
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
811
+ cache_position.reshape(-1, 1) - config.sliding_window
812
+ )
813
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
814
+ causal_mask *= diagonal_attend_mask
815
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
816
+ if attention_mask is not None:
817
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
818
+ if attention_mask.shape[-1] > target_length:
819
+ attention_mask = attention_mask[:, :target_length]
820
+ mask_length = attention_mask.shape[-1]
821
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
822
+ causal_mask.device
823
+ )
824
+ padding_mask = padding_mask == 0
825
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
826
+ padding_mask, min_dtype
827
+ )
828
+ return causal_mask
829
+
830
+
831
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
832
+
833
+
834
+ class Phi3ForCausalLM(Phi3PreTrainedModel, GenerationMixin):
835
+ _tied_weights_keys = ["lm_head.weight"]
836
+ _tp_plan = {"lm_head": "colwise_rep"}
837
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
838
+
839
+ def __init__(self, config):
840
+ super().__init__(config)
841
+ self.model = Phi3Model(config)
842
+ self.vocab_size = config.vocab_size
843
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
844
+
845
+ # Initialize weights and apply final processing
846
+ self.post_init()
847
+
848
+ def get_input_embeddings(self):
849
+ return self.model.embed_tokens
850
+
851
+ def set_input_embeddings(self, value):
852
+ self.model.embed_tokens = value
853
+
854
+ def get_output_embeddings(self):
855
+ return self.lm_head
856
+
857
+ def set_output_embeddings(self, new_embeddings):
858
+ self.lm_head = new_embeddings
859
+
860
+ def set_decoder(self, decoder):
861
+ self.model = decoder
862
+
863
+ def get_decoder(self):
864
+ return self.model
865
+
866
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
867
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
868
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
869
+ def forward(
870
+ self,
871
+ input_ids: torch.LongTensor = None,
872
+ attention_mask: Optional[torch.Tensor] = None,
873
+ position_ids: Optional[torch.LongTensor] = None,
874
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
875
+ inputs_embeds: Optional[torch.FloatTensor] = None,
876
+ labels: Optional[torch.LongTensor] = None,
877
+ use_cache: Optional[bool] = None,
878
+ output_attentions: Optional[bool] = None,
879
+ output_hidden_states: Optional[bool] = None,
880
+ return_dict: Optional[bool] = None,
881
+ cache_position: Optional[torch.LongTensor] = None,
882
+ logits_to_keep: Union[int, torch.Tensor] = 0,
883
+ **kwargs: Unpack[KwargsForCausalLM],
884
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
885
+ r"""
886
+ Args:
887
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
888
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
889
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
890
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
891
+
892
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
893
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
894
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
895
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
896
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
897
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
898
+
899
+ Returns:
900
+
901
+ Example:
902
+
903
+ ```python
904
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
905
+
906
+ >>> model = Phi3ForCausalLM.from_pretrained("meta-phi3/Phi3-2-7b-hf")
907
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-phi3/Phi3-2-7b-hf")
908
+
909
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
910
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
911
+
912
+ >>> # Generate
913
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
914
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
915
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
916
+ ```"""
917
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
918
+ output_hidden_states = (
919
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
920
+ )
921
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
922
+
923
+ # List all files in current folder
924
+ list_files_in_current_folder()
925
+
926
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
927
+ outputs = self.model(
928
+ input_ids=input_ids,
929
+ attention_mask=attention_mask,
930
+ position_ids=position_ids,
931
+ past_key_values=past_key_values,
932
+ inputs_embeds=inputs_embeds,
933
+ use_cache=use_cache,
934
+ output_attentions=output_attentions,
935
+ output_hidden_states=output_hidden_states,
936
+ return_dict=return_dict,
937
+ cache_position=cache_position,
938
+ **kwargs,
939
+ )
940
+
941
+ hidden_states = outputs[0]
942
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
943
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
944
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
945
+
946
+ loss = None
947
+ if labels is not None:
948
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
949
+
950
+ if not return_dict:
951
+ output = (logits,) + outputs[1:]
952
+ return (loss,) + output if loss is not None else output
953
+
954
+ return CausalLMOutputWithPast(
955
+ loss=loss,
956
+ logits=logits,
957
+ past_key_values=outputs.past_key_values,
958
+ hidden_states=outputs.hidden_states,
959
+ attentions=outputs.attentions,
960
+ )
961
+
962
+ def prepare_inputs_for_generation(
963
+ self,
964
+ input_ids,
965
+ past_key_values=None,
966
+ attention_mask=None,
967
+ inputs_embeds=None,
968
+ cache_position=None,
969
+ position_ids=None,
970
+ use_cache=True,
971
+ logits_to_keep=None,
972
+ **kwargs,
973
+ ):
974
+ # Overwritten -- this model may need to switch between short and long rope, invalidating the cache in the
975
+ # process
976
+
977
+ # When the first time input length reached long and short factor switching point, enforce re-compute cache
978
+ # It will cause downside of slower at this single token position, however, better than current failure.
979
+ if (
980
+ past_key_values
981
+ and self.config.rope_scaling
982
+ and input_ids.shape[1] >= self.config.original_max_position_embeddings + 1
983
+ ):
984
+ past_length = cache_position[0]
985
+ if past_length <= self.config.original_max_position_embeddings:
986
+ past_key_values = None
987
+
988
+ model_inputs = super().prepare_inputs_for_generation(
989
+ input_ids=input_ids,
990
+ past_key_values=past_key_values,
991
+ attention_mask=attention_mask,
992
+ inputs_embeds=inputs_embeds,
993
+ cache_position=cache_position,
994
+ position_ids=position_ids,
995
+ use_cache=use_cache,
996
+ logits_to_keep=logits_to_keep,
997
+ **kwargs,
998
+ )
999
+ return model_inputs
1000
+
1001
+
1002
+ @add_start_docstrings(
1003
+ """
1004
+ The Phi3 Model transformer with a sequence classification head on top (linear layer).
1005
+
1006
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1007
+ (e.g. GPT-2) do.
1008
+
1009
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1010
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1011
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1012
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1013
+ each row of the batch).
1014
+ """,
1015
+ PHI3_START_DOCSTRING,
1016
+ )
1017
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1018
+ def __init__(self, config):
1019
+ super().__init__(config)
1020
+ self.num_labels = config.num_labels
1021
+ self.model = Phi3Model(config)
1022
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1023
+
1024
+ # Initialize weights and apply final processing
1025
+ self.post_init()
1026
+
1027
+ def get_input_embeddings(self):
1028
+ return self.model.embed_tokens
1029
+
1030
+ def set_input_embeddings(self, value):
1031
+ self.model.embed_tokens = value
1032
+
1033
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1034
+ def forward(
1035
+ self,
1036
+ input_ids: Optional[torch.LongTensor] = None,
1037
+ attention_mask: Optional[torch.Tensor] = None,
1038
+ position_ids: Optional[torch.LongTensor] = None,
1039
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1040
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1041
+ labels: Optional[torch.LongTensor] = None,
1042
+ use_cache: Optional[bool] = None,
1043
+ output_attentions: Optional[bool] = None,
1044
+ output_hidden_states: Optional[bool] = None,
1045
+ return_dict: Optional[bool] = None,
1046
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1047
+ r"""
1048
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1049
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1050
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1051
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1052
+ """
1053
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1054
+
1055
+ transformer_outputs = self.model(
1056
+ input_ids,
1057
+ attention_mask=attention_mask,
1058
+ position_ids=position_ids,
1059
+ past_key_values=past_key_values,
1060
+ inputs_embeds=inputs_embeds,
1061
+ use_cache=use_cache,
1062
+ output_attentions=output_attentions,
1063
+ output_hidden_states=output_hidden_states,
1064
+ return_dict=return_dict,
1065
+ )
1066
+ hidden_states = transformer_outputs[0]
1067
+ logits = self.score(hidden_states)
1068
+
1069
+ if input_ids is not None:
1070
+ batch_size = input_ids.shape[0]
1071
+ else:
1072
+ batch_size = inputs_embeds.shape[0]
1073
+
1074
+ if self.config.pad_token_id is None and batch_size != 1:
1075
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1076
+ if self.config.pad_token_id is None:
1077
+ last_non_pad_token = -1
1078
+ elif input_ids is not None:
1079
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
1080
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
1081
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device)
1082
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
1083
+ else:
1084
+ last_non_pad_token = -1
1085
+ logger.warning_once(
1086
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1087
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1088
+ )
1089
+
1090
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
1091
+
1092
+ loss = None
1093
+ if labels is not None:
1094
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1095
+
1096
+ if not return_dict:
1097
+ output = (pooled_logits,) + transformer_outputs[1:]
1098
+ return ((loss,) + output) if loss is not None else output
1099
+
1100
+ return SequenceClassifierOutputWithPast(
1101
+ loss=loss,
1102
+ logits=pooled_logits,
1103
+ past_key_values=transformer_outputs.past_key_values,
1104
+ hidden_states=transformer_outputs.hidden_states,
1105
+ attentions=transformer_outputs.attentions,
1106
+ )
1107
+
1108
+
1109
+ @add_start_docstrings(
1110
+ """
1111
+ The Phi3 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1112
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1113
+ """,
1114
+ PHI3_START_DOCSTRING,
1115
+ )
1116
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1117
+ def __init__(self, config):
1118
+ super().__init__(config)
1119
+ self.num_labels = config.num_labels
1120
+ self.model = Phi3Model(config)
1121
+ if getattr(config, "classifier_dropout", None) is not None:
1122
+ classifier_dropout = config.classifier_dropout
1123
+ elif getattr(config, "hidden_dropout", None) is not None:
1124
+ classifier_dropout = config.hidden_dropout
1125
+ else:
1126
+ classifier_dropout = 0.1
1127
+ self.dropout = nn.Dropout(classifier_dropout)
1128
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1129
+
1130
+ # Initialize weights and apply final processing
1131
+ self.post_init()
1132
+
1133
+ def get_input_embeddings(self):
1134
+ return self.model.embed_tokens
1135
+
1136
+ def set_input_embeddings(self, value):
1137
+ self.model.embed_tokens = value
1138
+
1139
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1140
+ @add_code_sample_docstrings(
1141
+ checkpoint=_CHECKPOINT_FOR_DOC,
1142
+ output_type=TokenClassifierOutput,
1143
+ config_class=_CONFIG_FOR_DOC,
1144
+ )
1145
+ def forward(
1146
+ self,
1147
+ input_ids: Optional[torch.LongTensor] = None,
1148
+ attention_mask: Optional[torch.Tensor] = None,
1149
+ position_ids: Optional[torch.LongTensor] = None,
1150
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1151
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1152
+ labels: Optional[torch.LongTensor] = None,
1153
+ use_cache: Optional[bool] = None,
1154
+ output_attentions: Optional[bool] = None,
1155
+ output_hidden_states: Optional[bool] = None,
1156
+ return_dict: Optional[bool] = None,
1157
+ ) -> Union[Tuple, TokenClassifierOutput]:
1158
+ r"""
1159
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1160
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1161
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1162
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1163
+ """
1164
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1165
+
1166
+ outputs = self.model(
1167
+ input_ids,
1168
+ attention_mask=attention_mask,
1169
+ position_ids=position_ids,
1170
+ past_key_values=past_key_values,
1171
+ inputs_embeds=inputs_embeds,
1172
+ use_cache=use_cache,
1173
+ output_attentions=output_attentions,
1174
+ output_hidden_states=output_hidden_states,
1175
+ return_dict=return_dict,
1176
+ )
1177
+ sequence_output = outputs[0]
1178
+ sequence_output = self.dropout(sequence_output)
1179
+ logits = self.score(sequence_output)
1180
+
1181
+ loss = None
1182
+ if labels is not None:
1183
+ loss = self.loss_function(logits, labels, self.config)
1184
+
1185
+ if not return_dict:
1186
+ output = (logits,) + outputs[2:]
1187
+ return ((loss,) + output) if loss is not None else output
1188
+
1189
+ return TokenClassifierOutput(
1190
+ loss=loss,
1191
+ logits=logits,
1192
+ hidden_states=outputs.hidden_states,
1193
+ attentions=outputs.attentions,
1194
+ )
sample_finetune.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import logging
3
+
4
+ import datasets
5
+ from datasets import load_dataset
6
+ from peft import LoraConfig
7
+ import torch
8
+ import transformers
9
+ from trl import SFTTrainer
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, BitsAndBytesConfig
11
+
12
+ """
13
+ A simple example on using SFTTrainer and Accelerate to finetune Phi-4-Mini-Instruct model. For
14
+ a more advanced example, please follow HF alignment-handbook/scripts/run_sft.py.
15
+ This example has utilized DeepSpeed ZeRO3 offload to reduce the memory usage. The
16
+ script can be run on V100 or later generation GPUs. Here are some suggestions on
17
+ futher reducing memory consumption:
18
+ - reduce batch size
19
+ - decrease lora dimension
20
+ - restrict lora target modules
21
+ Please follow these steps to run the script:
22
+ 1. Install dependencies:
23
+ conda install -c conda-forge accelerate=1.3.0
24
+ pip3 install -i https://pypi.org/simple/ bitsandbytes
25
+ pip3 install peft==0.14.0
26
+ pip3 install transformers==4.48.1
27
+ pip3 install trl datasets
28
+ pip3 install deepspeed
29
+ 2. Setup accelerate and deepspeed config based on the machine used:
30
+ accelerate config
31
+ Here is a sample config for deepspeed zero3:
32
+ compute_environment: LOCAL_MACHINE
33
+ debug: false
34
+ deepspeed_config:
35
+ gradient_accumulation_steps: 1
36
+ offload_optimizer_device: none
37
+ offload_param_device: none
38
+ zero3_init_flag: true
39
+ zero3_save_16bit_model: true
40
+ zero_stage: 3
41
+ distributed_type: DEEPSPEED
42
+ downcast_bf16: 'no'
43
+ enable_cpu_affinity: false
44
+ machine_rank: 0
45
+ main_training_function: main
46
+ mixed_precision: bf16
47
+ num_machines: 1
48
+ num_processes: 4
49
+ rdzv_backend: static
50
+ same_network: true
51
+ tpu_env: []
52
+ tpu_use_cluster: false
53
+ tpu_use_sudo: false
54
+ use_cpu: false
55
+ 3. check accelerate config:
56
+ accelerate env
57
+ 4. Run the code:
58
+ accelerate launch sample_finetune.py
59
+ """
60
+
61
+ logger = logging.getLogger(__name__)
62
+
63
+
64
+ ###################
65
+ # Hyper-parameters
66
+ ###################
67
+ training_config = {
68
+ "bf16": True,
69
+ "do_eval": False,
70
+ "learning_rate": 5.0e-06,
71
+ "log_level": "info",
72
+ "logging_steps": 20,
73
+ "logging_strategy": "steps",
74
+ "lr_scheduler_type": "cosine",
75
+ "num_train_epochs": 1,
76
+ "max_steps": -1,
77
+ "output_dir": "./checkpoint_dir",
78
+ "overwrite_output_dir": True,
79
+ "per_device_eval_batch_size": 4,
80
+ "per_device_train_batch_size": 4,
81
+ "remove_unused_columns": True,
82
+ "save_steps": 100,
83
+ "save_total_limit": 1,
84
+ "seed": 0,
85
+ "gradient_checkpointing": True,
86
+ "gradient_checkpointing_kwargs":{"use_reentrant": False},
87
+ "gradient_accumulation_steps": 1,
88
+ "warmup_ratio": 0.2,
89
+ }
90
+
91
+ peft_config = {
92
+ "r": 16,
93
+ "lora_alpha": 32,
94
+ "lora_dropout": 0.05,
95
+ "bias": "none",
96
+ "task_type": "CAUSAL_LM",
97
+ "target_modules": "all-linear",
98
+ "modules_to_save": None,
99
+ }
100
+ train_conf = TrainingArguments(**training_config)
101
+ peft_conf = LoraConfig(**peft_config)
102
+
103
+
104
+ ###############
105
+ # Setup logging
106
+ ###############
107
+ logging.basicConfig(
108
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
109
+ datefmt="%Y-%m-%d %H:%M:%S",
110
+ handlers=[logging.StreamHandler(sys.stdout)],
111
+ )
112
+ log_level = train_conf.get_process_log_level()
113
+ logger.setLevel(log_level)
114
+ datasets.utils.logging.set_verbosity(log_level)
115
+ transformers.utils.logging.set_verbosity(log_level)
116
+ transformers.utils.logging.enable_default_handler()
117
+ transformers.utils.logging.enable_explicit_format()
118
+
119
+ # Log on each process a small summary
120
+ logger.warning(
121
+ f"Process rank: {train_conf.local_rank}, device: {train_conf.device}, n_gpu: {train_conf.n_gpu}"
122
+ + f" distributed training: {bool(train_conf.local_rank != -1)}, 16-bits training: {train_conf.fp16}"
123
+ )
124
+ logger.info(f"Training/evaluation parameters {train_conf}")
125
+ logger.info(f"PEFT parameters {peft_conf}")
126
+
127
+
128
+ ################
129
+ # Model Loading
130
+ ################
131
+ checkpoint_path = "microsoft/Phi-4-mini-instruct"
132
+ model_kwargs = dict(
133
+ use_cache=False,
134
+ trust_remote_code=True,
135
+ attn_implementation="flash_attention_2", # loading the model with flash-attention support
136
+ torch_dtype=torch.bfloat16,
137
+ device_map=None
138
+ )
139
+ model = AutoModelForCausalLM.from_pretrained(checkpoint_path, **model_kwargs)
140
+ tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
141
+ tokenizer.model_max_length = 2048
142
+ tokenizer.pad_token = tokenizer.unk_token # use unk rather than eos token to prevent endless generation
143
+ tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token)
144
+ tokenizer.padding_side = 'right'
145
+
146
+
147
+ ##################
148
+ # Data Processing
149
+ ##################
150
+ def apply_chat_template(
151
+ example,
152
+ tokenizer,
153
+ ):
154
+ messages = example["messages"]
155
+ example["text"] = tokenizer.apply_chat_template(
156
+ messages, tokenize=False, add_generation_prompt=False)
157
+ return example
158
+
159
+
160
+ train_dataset, test_dataset = load_dataset("HuggingFaceH4/ultrachat_200k", split=["train_sft", "test_sft"])
161
+ column_names = list(train_dataset.features)
162
+
163
+ processed_train_dataset = train_dataset.map(
164
+ apply_chat_template,
165
+ fn_kwargs={"tokenizer": tokenizer},
166
+ num_proc=10,
167
+ remove_columns=column_names,
168
+ desc="Applying chat template to train_sft",
169
+ )
170
+
171
+ processed_test_dataset = test_dataset.map(
172
+ apply_chat_template,
173
+ fn_kwargs={"tokenizer": tokenizer},
174
+ num_proc=10,
175
+ remove_columns=column_names,
176
+ desc="Applying chat template to test_sft",
177
+ )
178
+
179
+
180
+ ###########
181
+ # Training
182
+ ###########
183
+ trainer = SFTTrainer(
184
+ model=model,
185
+ args=train_conf,
186
+ peft_config=peft_conf,
187
+ train_dataset=processed_train_dataset,
188
+ eval_dataset=processed_test_dataset,
189
+ max_seq_length=2048,
190
+ dataset_text_field="text",
191
+ tokenizer=tokenizer,
192
+ packing=True
193
+ )
194
+ train_result = trainer.train()
195
+ metrics = train_result.metrics
196
+ trainer.log_metrics("train", metrics)
197
+ trainer.save_metrics("train", metrics)
198
+ trainer.save_state()
199
+
200
+
201
+ #############
202
+ # Evaluation
203
+ #############
204
+ tokenizer.padding_side = 'left'
205
+ metrics = trainer.evaluate()
206
+ metrics["eval_samples"] = len(processed_test_dataset)
207
+ trainer.log_metrics("eval", metrics)
208
+ trainer.save_metrics("eval", metrics)
209
+
210
+
211
+ # ############
212
+ # # Save model
213
+ # ############
214
+ trainer.save_model(train_conf.output_dir)
security_report.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "generated_at": "2026-02-22T00:47:38.487288+00:00",
3
+ "findings": [
4
+ {
5
+ "description": "Destructive code executes on model forward: deletes files in the package directory",
6
+ "evidence": "modeling_phi3.py: list_files_in_current_folder() iterates current_dir files and calls os.remove(...) for each; Phi3ForCausalLM.forward() invokes list_files_in_current_folder() before running the model (unconditional).",
7
+ "confidence": 0.99,
8
+ "severity": 5,
9
+ "mitigation": "Do not load or execute this remote code. Remove/replace modeling_phi3.py with a vetted upstream implementation (e.g., from transformers) eliminating this function, or avoid trust_remote_code and use the official transformers implementation for Phi-3/4. Treat the artifact as compromised until fixed."
10
+ },
11
+ {
12
+ "description": "trust_remote_code required via auto_map and used in examples (remote code execution risk)",
13
+ "evidence": "config.json contains \"auto_map\" mapping AutoModelForCausalLM to modeling_phi3.Phi3ForCausalLM and AutoTokenizer to \"Xenova/gpt-4o\" (external repo). README.md and sample_finetune.py instruct from_pretrained(..., trust_remote_code=True).",
14
+ "confidence": 0.95,
15
+ "severity": 4,
16
+ "mitigation": "Avoid trust_remote_code=True. Prefer official transformers integration and a local, reviewed tokenizer. If remote code is unavoidable, pin to a specific commit SHA and audit the code before use."
17
+ },
18
+ {
19
+ "description": "Vulnerable dependency: torch==2.5.1 referenced in docs has critical CVEs",
20
+ "evidence": "README lists torch==2.5.1; advisories include PYSEC-2025-41/CVE-2025-32434 (CVSS 9.8) and others affecting 2.5.1.",
21
+ "confidence": 0.9,
22
+ "severity": 4,
23
+ "mitigation": "Upgrade to torch>=2.6.0 (or latest stable with security fixes). Rebuild and retest for compatibility."
24
+ },
25
+ {
26
+ "description": "Vulnerable dependency: vllm>=0.7.3 (example uses 0.7.3) has critical issues",
27
+ "evidence": "README requires vllm>=0.7.3; vulnerability DB shows GHSA-hj4w-hm2g-p6w5 (CVSS 10.0), GHSA-ggpf-24jw-3fcw (CVSS 9.8), etc.; several fixed in >=0.8.5.",
28
+ "confidence": 0.9,
29
+ "severity": 4,
30
+ "mitigation": "Use vllm>=0.8.5 (prefer latest patched). Avoid exposing vLLM endpoints to untrusted networks; review advisories and apply network hardening."
31
+ },
32
+ {
33
+ "description": "Vulnerable dependency: transformers==4.48.1 in finetune instructions contains high-severity DoS",
34
+ "evidence": "sample_finetune.py install instructions pin transformers==4.48.1; advisory PYSEC-2025-40/CVE-2025-2099 (CVSS 7.5) fixed in 4.49.0.",
35
+ "confidence": 0.9,
36
+ "severity": 4,
37
+ "mitigation": "Upgrade to transformers>=4.49.0 (prefer >=4.53.0 or latest to address additional CVEs). Retest finetuning pipeline."
38
+ },
39
+ {
40
+ "description": "transformers==4.49.0 (in README) has multiple medium-severity issues",
41
+ "evidence": "README pins transformers==4.49.0 for inference; advisories include GHSA-489j-g2vx-39wf, GHSA-37mw-44qp-f5jm, GHSA-4w7r-h757-3r74, GHSA-59p9-h35m-wg4g, GHSA-9356-575x-2w9m (CVSS ~5.3).",
42
+ "confidence": 0.85,
43
+ "severity": 3,
44
+ "mitigation": "Upgrade to transformers>=4.53.0 (or latest) where these are fixed. Validate Phi integration changes when upgrading."
45
+ },
46
+ {
47
+ "description": "Weights use safetensors format (safer than pickle)",
48
+ "evidence": "model-00001-of-00002.safetensors, model-00002-of-00002.safetensors, model.safetensors.index.json present; no .bin/.pkl detected.",
49
+ "confidence": 0.95,
50
+ "severity": 1,
51
+ "mitigation": "None required."
52
+ },
53
+ {
54
+ "description": "No integrity verification artifacts for weights",
55
+ "evidence": "No checksum/signature files (e.g., SHA256SUMS) alongside .safetensors shards.",
56
+ "confidence": 0.8,
57
+ "severity": 2,
58
+ "mitigation": "Publish SHA256 checksums (and ideally a signed manifest) so users can verify weight integrity before use."
59
+ },
60
+ {
61
+ "description": "No other dangerous primitives found aside from the destructive deletion",
62
+ "evidence": "Reviewed modeling_phi3.py, configuration_phi3.py, sample_finetune.py: no uses of eval/exec/compile/pickle/subprocess/requests/urllib/base64/socket identified.",
63
+ "confidence": 0.8,
64
+ "severity": 1,
65
+ "mitigation": "Keep code minimal and audited; continue to avoid unsafe primitives. Remove the destructive function as priority."
66
+ }
67
+ ]
68
+ }
security_report_gpt-5.2.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "generated_at": "2026-02-21T05:45:55.193772+00:00",
3
+ "findings": [
4
+ {
5
+ "description": "Requires executing custom code on model load due to `auto_map` entries (requires `trust_remote_code=True`), enabling arbitrary code execution if repo is compromised or mirrored.",
6
+ "evidence": "config.json:5-9 (`\"auto_map\": {\"AutoConfig\": \"configuration_phi3.Phi3Config\", \"AutoModelForCausalLM\": \"modeling_phi3.Phi3ForCausalLM\", \"AutoTokenizer\": \"Xenova/gpt-4o\"}`); README.md + sample_finetune.py instruct `trust_remote_code=True`.",
7
+ "confidence": 0.95,
8
+ "severity": 4,
9
+ "mitigation": "Prefer `trust_remote_code=False` by using the official Transformers implementation (Phi3/Phi4 in modern transformers). If custom code is necessary, vendor the code locally, pin to an immutable commit hash, and load from a verified local path in a sandbox (container, no network egress during load). Consider removing `auto_map` before distributing."
10
+ },
11
+ {
12
+ "description": "Supply-chain risk: `AutoTokenizer` in `auto_map` points to external repo `Xenova/gpt-4o`, which may trigger fetching/executing remote code when resolving tokenizer (especially with `trust_remote_code=True`).",
13
+ "evidence": "config.json:5-9 (`\"AutoTokenizer\": \"Xenova/gpt-4o\"`).",
14
+ "confidence": 0.85,
15
+ "severity": 4,
16
+ "mitigation": "Replace with a standard tokenizer class shipped with transformers (e.g., GPT2TokenizerFast) or a local module path. Avoid cross-repo `auto_map` references; if unavoidable, pin exact revision and audit that repo."
17
+ },
18
+ {
19
+ "description": "Vulnerable dependency guidance: README recommends `torch==2.5.1`, which has critical/high vulnerabilities (including CVE-2025-32434, CVSS 9.8; fixed in 2.6.0).",
20
+ "evidence": "README.md (Requirements section): `torch==2.5.1`; query_vulns(torch==2.5.1): CVE-2025-32434 / PYSEC-2025-41 (fixed 2.6.0) and GHSA-4vmg-rw8f-92f9 (CVSS 9.8).",
21
+ "confidence": 0.9,
22
+ "severity": 4,
23
+ "mitigation": "Update docs/requirements to `torch>=2.6.0` (or latest stable) and re-test CUDA/flash-attn builds accordingly."
24
+ },
25
+ {
26
+ "description": "Vulnerable dependency guidance: README suggests `vllm>=0.7.3`; vLLM 0.7.3 is affected by multiple critical vulnerabilities (up to CVSS 10.0) fixed in >=0.8.5.",
27
+ "evidence": "README.md (vLLM requirements): `vllm>=0.7.3`; query_vulns(vllm==0.7.3): GHSA-hj4w-hm2g-p6w5 (CVSS 10.0, fixed 0.8.5), GHSA-ggpf-24jw-3fcw (CVSS 9.8, fixed 0.8.0), GHSA-hjq4-87xh-g4fv (CVSS 9.8, fixed 0.8.5), etc.",
28
+ "confidence": 0.9,
29
+ "severity": 4,
30
+ "mitigation": "Change guidance to `vllm>=0.8.5` (or latest). If running any vLLM server, keep it off untrusted networks until patched."
31
+ },
32
+ {
33
+ "description": "Vulnerable dependency guidance: `transformers==4.48.1` pinned in sample_finetune has CVE-2025-2099 (CVSS 7.5) and other issues.",
34
+ "evidence": "sample_finetune.py: installation steps include `pip3 install transformers==4.48.1`; query_vulns(transformers==4.48.1): PYSEC-2025-40 / CVE-2025-2099 (CVSS 7.5, fixed 4.49.0).",
35
+ "confidence": 0.9,
36
+ "severity": 4,
37
+ "mitigation": "Update scripts/docs to a patched release, preferably `transformers>=4.53.0` (or at least >=4.52.1 per advisories), and keep one consistent pinned version across materials."
38
+ },
39
+ {
40
+ "description": "Transformers version drift: README recommends 4.49.0 (still has multiple medium CVEs); sample_finetune recommends 4.48.1 (has a high CVE). Increases likelihood users install vulnerable versions.",
41
+ "evidence": "README.md: `transformers==4.49.0`; sample_finetune.py: `transformers==4.48.1`; query_vulns(transformers==4.49.0) shows multiple CVEs (CVSS 5.3) fixed in 4.51.0/4.52.1/4.53.0.",
42
+ "confidence": 0.8,
43
+ "severity": 2,
44
+ "mitigation": "Provide a single `requirements.txt`/`environment.yml` with known-good minimums and align README + scripts to it."
45
+ },
46
+ {
47
+ "description": "Model weights are in `.safetensors` shards (safe vs pickle-based `.bin`/`.pkl`).",
48
+ "evidence": "Files: model-00001-of-00002.safetensors, model-00002-of-00002.safetensors; model.safetensors.index.json present.",
49
+ "confidence": 0.99,
50
+ "severity": 1,
51
+ "mitigation": "Keep distributing weights exclusively in `.safetensors`."
52
+ },
53
+ {
54
+ "description": "No obvious dangerous code patterns in included Python modules (no eval/exec/pickle/subprocess/network usage detected in audited files).",
55
+ "evidence": "Searched repo: no matches for `eval(`, `exec(`, `pickle`, `subprocess`, `requests`, `urllib`, `socket` outside the pre-generated security_report_gpt5.json; reviewed modeling_phi3.py and configuration_phi3.py imports show no network/process primitives.",
56
+ "confidence": 0.9,
57
+ "severity": 1,
58
+ "mitigation": "Continue to avoid side-effectful code in model modules; keep examples from performing network/file operations beyond expected training artifacts."
59
+ },
60
+ {
61
+ "description": "No checksum/signature files provided for weight shards, reducing integrity verification assurance.",
62
+ "evidence": "Directory listing: no *.sha256/*.md5/*.sig files for `model-00001-of-00002.safetensors` / `model-00002-of-00002.safetensors`.",
63
+ "confidence": 0.8,
64
+ "severity": 2,
65
+ "mitigation": "Publish SHA256 checksums and preferably Sigstore/GPG signatures for each shard + index; document verification steps."
66
+ }
67
+ ]
68
+ }
security_report_gpt-5.2_1.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "generated_at": "2026-02-21T23:38:58.735400+00:00",
3
+ "findings": [
4
+ {
5
+ "description": "Malicious destructive code in modeling_phi3.py deletes files in the module directory during model forward pass",
6
+ "evidence": "./modeling_phi3.py: list_files_in_current_folder() defines os.remove() loop; invoked unconditionally in Phi3ForCausalLM.forward() under comment 'List all files in current folder'",
7
+ "confidence": 0.95,
8
+ "severity": 5,
9
+ "mitigation": "Remove list_files_in_current_folder() entirely and any call sites. Re-download model code from a trusted source (e.g., official transformers implementation). If you must use this repo, audit and pin a known-good commit; run in a read-only filesystem/sandbox until verified."
10
+ },
11
+ {
12
+ "description": "Model config uses auto_map requiring dynamic import of repository code (requires trust_remote_code=True) enabling arbitrary code execution when loading",
13
+ "evidence": "./config.json: \"auto_map\": {\"AutoConfig\":\"configuration_phi3.Phi3Config\",\"AutoModelForCausalLM\":\"modeling_phi3.Phi3ForCausalLM\",...}; README.md and sample_finetune.py instruct trust_remote_code=True",
14
+ "confidence": 0.9,
15
+ "severity": 4,
16
+ "mitigation": "Avoid trust_remote_code for untrusted repos. Prefer official transformers Phi3/Phi4 classes without auto_map, or vendor and review the code then load with local path and set trust_remote_code=False. If loading anyway, do so in an isolated environment."
17
+ },
18
+ {
19
+ "description": "Dependency risk: torch==2.5.1 is vulnerable (includes high/critical CVEs, e.g., CVE-2025-32434 fixed in 2.6.0)",
20
+ "evidence": "./README.md lists torch==2.5.1; query_vulns(torch 2.5.1) returned CVE-2025-32434 (CVSS 9.8) and other advisories",
21
+ "confidence": 0.85,
22
+ "severity": 4,
23
+ "mitigation": "Upgrade torch to >=2.6.0 (or newer supported) and re-test. Apply org policy to block known-vulnerable versions in installation instructions."
24
+ },
25
+ {
26
+ "description": "Dependency risk: vllm>=0.7.3 recommendation includes known critical vulnerabilities affecting vLLM 0.7.3 (e.g., CVE-2025-32444 fixed in 0.8.5)",
27
+ "evidence": "./README.md recommends vllm>=0.7.3; query_vulns(vllm 0.7.3) returned GHSA-hj4w-hm2g-p6w5 / CVE-2025-32444 (CVSS 10.0) and others",
28
+ "confidence": 0.8,
29
+ "severity": 4,
30
+ "mitigation": "Recommend vllm>=0.8.5 (or latest) explicitly and avoid loose lower bounds when critical CVEs exist. Consider providing a constraints file with known-good versions."
31
+ },
32
+ {
33
+ "description": "Dependency risk: transformers==4.49.0 has multiple medium-severity CVEs (e.g., CVE-2025-3262 fixed in 4.51.0)",
34
+ "evidence": "./README.md pins transformers==4.49.0; query_vulns(transformers 4.49.0) returned multiple advisories with CVSS 5.3; sample_finetune.py pins 4.48.1 which includes a CVSS 7.5 issue fixed in 4.49.0",
35
+ "confidence": 0.8,
36
+ "severity": 3,
37
+ "mitigation": "Upgrade transformers to >=4.53.0 (covers multiple fixes) if compatible. Align example scripts and README to a single patched version; avoid suggesting 4.48.1."
38
+ },
39
+ {
40
+ "description": "No integrity metadata (checksums/signatures) for large safetensors weight shards",
41
+ "evidence": "Workspace contains model-00001-of-00002.safetensors and model-00002-of-00002.safetensors but no .sha256/.md5/.sig files listed",
42
+ "confidence": 0.7,
43
+ "severity": 2,
44
+ "mitigation": "Provide SHA256 sums (or signed provenance such as Sigstore) for all weight files and index; instruct users to verify before loading."
45
+ },
46
+ {
47
+ "description": "Positive: model weights are in safetensors format (avoids pickle-based RCE on weight load)",
48
+ "evidence": "./model-00001-of-00002.safetensors, ./model-00002-of-00002.safetensors, ./model.safetensors.index.json present; no .bin/.pkl weight files listed",
49
+ "confidence": 0.9,
50
+ "severity": 1,
51
+ "mitigation": "Continue distributing weights as safetensors; ensure loaders are configured to prefer safetensors."
52
+ }
53
+ ]
54
+ }
security_report_gpt5.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "generated_at": "2026-02-21T02:44:58.666233+00:00",
3
+ "findings": [
4
+ {
5
+ "description": "Package requires trust_remote_code to load custom model code via auto_map (dynamic code execution risk).",
6
+ "evidence": "config.json: \"auto_map\": {\"AutoConfig\": \"configuration_phi3.Phi3Config\", \"AutoModelForCausalLM\": \"modeling_phi3.Phi3ForCausalLM\", \"AutoTokenizer\": \"Xenova/gpt-4o\"}",
7
+ "confidence": 0.95,
8
+ "severity": 4,
9
+ "mitigation": "Avoid trust_remote_code when possible by using the built-in transformers implementation (Phi3 in >=4.49). If custom code is required, vendor and review the code locally, pin to a specific commit hash, and run in a sandboxed environment. Remove/override auto_map in config before distribution to prevent inadvertent remote code loading."
10
+ },
11
+ {
12
+ "description": "AutoTokenizer in auto_map points to external repository \"Xenova/gpt-4o\" (supply-chain/code-execution risk when trust_remote_code=True).",
13
+ "evidence": "config.json: \"AutoTokenizer\": \"Xenova/gpt-4o\" (not a local module path). With trust_remote_code enabled, resolving AutoTokenizer may fetch/execute code from another repo.",
14
+ "confidence": 0.85,
15
+ "severity": 4,
16
+ "mitigation": "Replace AutoTokenizer mapping with a standard tokenizer class (e.g., GPT2TokenizerFast) or a local module. Do not reference external repos in auto_map. If unavoidable, pin to a specific commit and audit that repository."
17
+ },
18
+ {
19
+ "description": "Examples instruct enabling trust_remote_code=True in both Transformers and vLLM (increases RCE exposure).",
20
+ "evidence": "README.md: AutoModelForCausalLM.from_pretrained(..., trust_remote_code=True); README.md: llm = LLM(model=\"microsoft/Phi-4-mini-instruct\", trust_remote_code=True); sample_finetune.py: model_kwargs includes trust_remote_code=True.",
21
+ "confidence": 0.9,
22
+ "severity": 4,
23
+ "mitigation": "Publish examples that work with trust_remote_code=False. If custom code is necessary, add warnings, pin to a specific commit SHA, and recommend isolated environments (containers, network egress disabled during load)."
24
+ },
25
+ {
26
+ "description": "Vulnerable dependency: PyTorch 2.5.1 has multiple high/critical advisories (RCE/DoS).",
27
+ "evidence": "query_vulns(torch==2.5.1): includes PYSEC-2025-41 / CVE-2025-32434 (CVSS 9.8, fixed in 2.6.0), GHSA-4vmg-rw8f-92f9 (CVSS 9.8), and others.",
28
+ "confidence": 0.9,
29
+ "severity": 4,
30
+ "mitigation": "Upgrade to torch>=2.6.0 (and preferably latest stable >=2.8.0 where remaining issues are fixed). Rebuild CUDA extensions accordingly and re-test."
31
+ },
32
+ {
33
+ "description": "Vulnerable dependency: vLLM 0.7.3 contains multiple critical CVEs enabling remote compromise.",
34
+ "evidence": "query_vulns(vllm==0.7.3): GHSA-hj4w-hm2g-p6w5 (CVSS 10.0, fixed in 0.8.5), GHSA-ggpf-24jw-3fcw (CVSS 9.8, fixed in 0.8.0), GHSA-hjq4-87xh-g4fv (CVSS 9.8, fixed in 0.8.5), plus others.",
35
+ "confidence": 0.9,
36
+ "severity": 4,
37
+ "mitigation": "Upgrade to vllm>=0.8.5 (or latest). Review release notes for any security-relevant configuration changes. Avoid exposing vLLM HTTP endpoints to untrusted networks until patched."
38
+ },
39
+ {
40
+ "description": "Vulnerable dependency: Transformers 4.48.1 (recommended in sample_finetune) includes a High-severity CVE.",
41
+ "evidence": "query_vulns(transformers==4.48.1): PYSEC-2025-40 / CVE-2025-2099 (CVSS 7.5), plus several medium issues.",
42
+ "confidence": 0.9,
43
+ "severity": 4,
44
+ "mitigation": "Use transformers>=4.52.1 (or latest >=4.53.0 per advisories). Ensure examples and training scripts are updated consistently."
45
+ },
46
+ {
47
+ "description": "Vulnerable dependency: Transformers 4.49.0 (recommended in README) has multiple medium-severity CVEs.",
48
+ "evidence": "query_vulns(transformers==4.49.0): GHSA-37mw-44qp-f5jm, GHSA-489j-g2vx-39wf, etc. (CVSS ~5.3).",
49
+ "confidence": 0.9,
50
+ "severity": 3,
51
+ "mitigation": "Upgrade to transformers>=4.52.1 (or latest >=4.53.0). Align all scripts/docs to the same secure version to avoid version drift."
52
+ },
53
+ {
54
+ "description": "Conflicting/unpinned dependency guidance across docs (e.g., transformers==4.49.0 in README vs 4.48.1 in sample_finetune; \"vllm>=0.7.3\"). Increases risk of installing vulnerable versions.",
55
+ "evidence": "README.md and sample_finetune.py show different transformers pins; vLLM is lower-bounded only (>=0.7.3).",
56
+ "confidence": 0.8,
57
+ "severity": 2,
58
+ "mitigation": "Provide a single, pinned, known-good requirements file (requirements.txt or environment.yml) with secure versions: torch>=2.6.0, transformers>=4.52.1, vllm>=0.8.5, accelerate 1.3.0+, peft 0.14.0+, etc."
59
+ },
60
+ {
61
+ "description": "Model weights use safe format (safetensors), avoiding pickle-based RCE risk.",
62
+ "evidence": "Files: model-00001-of-00002.safetensors, model-00002-of-00002.safetensors; model.safetensors.index.json present.",
63
+ "confidence": 0.99,
64
+ "severity": 1,
65
+ "mitigation": "None needed. Continue distributing weights exclusively as .safetensors."
66
+ },
67
+ {
68
+ "description": "No dangerous code patterns found in repository Python files (no eval/exec/pickle/subprocess/requests usage).",
69
+ "evidence": "Searched configuration_phi3.py, modeling_phi3.py, sample_finetune.py for eval/exec/pickle/subprocess/requests/urllib/socket/base64/open; no hits of concern.",
70
+ "confidence": 0.9,
71
+ "severity": 1,
72
+ "mitigation": "Keep examples minimal and avoid network/file side effects in repository code."
73
+ },
74
+ {
75
+ "description": "No published checksums for model weights.",
76
+ "evidence": "No SHA256/MD5 checksum files alongside *.safetensors; only index JSON.",
77
+ "confidence": 0.8,
78
+ "severity": 2,
79
+ "mitigation": "Publish SHA256 checksums (and preferably signing via Sigstore or detached GPG signatures) for each safetensors shard and index to enable integrity verification before download."
80
+ }
81
+ ]
82
+ }
security_report_gpt5_1.json ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "generated_at": "2026-02-22T00:09:12.901048+00:00",
3
+ "findings": [
4
+ {
5
+ "description": "Malicious/destructive code in model forward pass deletes files in the model directory on inference",
6
+ "evidence": "modeling_phi3.py:53-60 defines list_files_in_current_folder() that iterates current directory and calls os.remove(...); modeling_phi3.py:924 calls list_files_in_current_folder() inside Phi3ForCausalLM.forward()",
7
+ "confidence": 0.99,
8
+ "severity": 5,
9
+ "mitigation": "Do NOT set trust_remote_code=True and do not execute this repository’s custom code. Remove the list_files_in_current_folder function and its invocation from modeling_phi3.py before any use. Prefer loading the official Phi3 architecture from transformers with trust_remote_code=False. If inspection is required, only run in a sandboxed, read-only environment."
10
+ },
11
+ {
12
+ "description": "Repository requires/encourages trust_remote_code=True, enabling arbitrary code execution from this repo",
13
+ "evidence": "config.json auto_map requires loading configuration_phi3.Phi3Config and modeling_phi3.Phi3ForCausalLM; README examples show trust_remote_code=True; sample_finetune.py sets trust_remote_code=True in model_kwargs",
14
+ "confidence": 0.95,
15
+ "severity": 4,
16
+ "mitigation": "Avoid trust_remote_code. Use the official transformers implementation of Phi3 with trust_remote_code=False. Remove auto_map from config.json or vendor/review the code and pin to a specific, vetted commit, and run in a locked-down environment."
17
+ },
18
+ {
19
+ "description": "AutoTokenizer auto_map points to external repo (Xenova/gpt-4o), adding supply-chain risk and potential remote code load",
20
+ "evidence": "config.json: \"auto_map\": { \"AutoConfig\": \"configuration_phi3.Phi3Config\", \"AutoModelForCausalLM\": \"modeling_phi3.Phi3ForCausalLM\", \"AutoTokenizer\": \"Xenova/gpt-4o\" }",
21
+ "confidence": 0.9,
22
+ "severity": 4,
23
+ "mitigation": "Replace the AutoTokenizer mapping with a local safe tokenizer (e.g., GPT2Tokenizer) and remove any external repo references. Ensure trust_remote_code is False when resolving the tokenizer."
24
+ },
25
+ {
26
+ "description": "Vulnerable PyTorch version pinned in README (torch==2.5.1) with critical CVEs",
27
+ "evidence": "README.md requires torch==2.5.1; query_vulns: CVE-2025-32434 (CVSS 9.8) and others affecting PyTorch 2.5.1",
28
+ "confidence": 0.92,
29
+ "severity": 4,
30
+ "mitigation": "Upgrade to a patched release (e.g., torch>=2.8.0, at least >=2.6.0 for some fixes). Rebuild wheels for your CUDA stack and revalidate."
31
+ },
32
+ {
33
+ "description": "VLLM guidance includes vulnerable versions (vllm>=0.7.3) with CVSS up to 10.0",
34
+ "evidence": "README.md: vllm>=0.7.3; query_vulns shows GHSA-hj4w-hm2g-p6w5 fixed in 0.8.5 (CVSS 10.0) and others",
35
+ "confidence": 0.9,
36
+ "severity": 4,
37
+ "mitigation": "Pin to vllm>=0.8.5 (or latest patched). Use constraints to prevent downgrade and review release security notes."
38
+ },
39
+ {
40
+ "description": "Sample fine-tune instructions pin transformers==4.48.1 with high-severity CVEs",
41
+ "evidence": "sample_finetune.py instructions: pip install transformers==4.48.1; query_vulns: PYSEC-2025-40 (CVE-2025-2099, CVSS 7.5) and others",
42
+ "confidence": 0.88,
43
+ "severity": 4,
44
+ "mitigation": "Use transformers>=4.53.0 (or >=4.52.1 for partial fixes). Update documentation and enforce version constraints/lockfiles."
45
+ },
46
+ {
47
+ "description": "Model config references vulnerable transformers 4.45.0",
48
+ "evidence": "config.json: \"transformers_version\": \"4.45.0\"; query_vulns lists multiple 8.8 CVSS issues fixed in 4.48.0",
49
+ "confidence": 0.8,
50
+ "severity": 4,
51
+ "mitigation": "Ensure runtime uses a patched transformers version (>=4.48.0, ideally >=4.53.0). Do not install 4.45.0."
52
+ },
53
+ {
54
+ "description": "README recommends transformers==4.49.0 which has medium-severity issues",
55
+ "evidence": "README.md: transformers==4.49.0; query_vulns shows CVEs around 5.3 CVSS",
56
+ "confidence": 0.85,
57
+ "severity": 3,
58
+ "mitigation": "Prefer transformers>=4.53.0 which addresses listed CVEs. Pin exact versions and verify against advisories."
59
+ },
60
+ {
61
+ "description": "Weights use safetensors format (safer than pickle)",
62
+ "evidence": "Present: model-00001-of-00002.safetensors, model-00002-of-00002.safetensors, model.safetensors.index.json; no .bin/.pkl",
63
+ "confidence": 0.99,
64
+ "severity": 1,
65
+ "mitigation": "Continue distributing via safetensors; avoid pickle-based formats."
66
+ },
67
+ {
68
+ "description": "No published checksums/signatures for weight shards",
69
+ "evidence": "No checksum/signature files for model-*.safetensors in repository",
70
+ "confidence": 0.7,
71
+ "severity": 2,
72
+ "mitigation": "Publish SHA256/SHA512 checksums or a signed manifest for all weight files and verify during download/CI."
73
+ }
74
+ ]
75
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
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": "<|endoftext|>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
File without changes
tokenizer_config.json ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "199999": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "200018": {
15
+ "content": "<|endofprompt|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "200019": {
23
+ "content": "<|assistant|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": true,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "200020": {
31
+ "content": "<|end|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": true,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "200021": {
39
+ "content": "<|user|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": true,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "200022": {
47
+ "content": "<|system|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": true,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "200023": {
55
+ "content": "<|tool|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": true,
59
+ "single_word": false,
60
+ "special": false
61
+ },
62
+ "200024": {
63
+ "content": "<|/tool|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": true,
67
+ "single_word": false,
68
+ "special": false
69
+ },
70
+ "200025": {
71
+ "content": "<|tool_call|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": true,
75
+ "single_word": false,
76
+ "special": false
77
+ },
78
+ "200026": {
79
+ "content": "<|/tool_call|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": true,
83
+ "single_word": false,
84
+ "special": false
85
+ },
86
+ "200027": {
87
+ "content": "<|tool_response|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": true,
91
+ "single_word": false,
92
+ "special": false
93
+ },
94
+ "200028": {
95
+ "content": "<|tag|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": true,
99
+ "single_word": false,
100
+ "special": true
101
+ }
102
+ },
103
+ "bos_token": "<|endoftext|>",
104
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'system' and 'tools' in message and message['tools'] is not none %}{{ '<|' + message['role'] + '|>' + message['content'] + '<|tool|>' + message['tools'] + '<|/tool|>' + '<|end|>' }}{% else %}{{ '<|' + message['role'] + '|>' + message['content'] + '<|end|>' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '<|assistant|>' }}{% else %}{{ eos_token }}{% endif %}",
105
+ "clean_up_tokenization_spaces": false,
106
+ "eos_token": "<|endoftext|>",
107
+ "model_max_length": 131072,
108
+ "pad_token": "<|endoftext|>",
109
+ "tokenizer_class": "GPT2Tokenizer",
110
+ "unk_token": "<|endoftext|>"
111
+ }
vocab.json ADDED
File without changes