TheBloke commited on
Commit
324d51b
1 Parent(s): 9f9fe8a

Upload README.md

Browse files
Files changed (1) hide show
  1. README.md +525 -0
README.md ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: microsoft/phi-2
3
+ inference: false
4
+ language:
5
+ - en
6
+ license: other
7
+ license_link: https://huggingface.co/microsoft/phi-2/resolve/main/LICENSE
8
+ license_name: microsoft-research-license
9
+ model_creator: Microsoft
10
+ model_name: Phi 2
11
+ model_type: phi-msft
12
+ pipeline_tag: text-generation
13
+ prompt_template: 'Instruct: {prompt}
14
+
15
+ Output:
16
+
17
+ '
18
+ quantized_by: TheBloke
19
+ tags:
20
+ - nlp
21
+ - code
22
+ ---
23
+ <!-- markdownlint-disable MD041 -->
24
+
25
+ <!-- header start -->
26
+ <!-- 200823 -->
27
+ <div style="width: auto; margin-left: auto; margin-right: auto">
28
+ <img src="https://i.imgur.com/EBdldam.jpg" alt="TheBlokeAI" style="width: 100%; min-width: 400px; display: block; margin: auto;">
29
+ </div>
30
+ <div style="display: flex; justify-content: space-between; width: 100%;">
31
+ <div style="display: flex; flex-direction: column; align-items: flex-start;">
32
+ <p style="margin-top: 0.5em; margin-bottom: 0em;"><a href="https://discord.gg/theblokeai">Chat & support: TheBloke's Discord server</a></p>
33
+ </div>
34
+ <div style="display: flex; flex-direction: column; align-items: flex-end;">
35
+ <p style="margin-top: 0.5em; margin-bottom: 0em;"><a href="https://www.patreon.com/TheBlokeAI">Want to contribute? TheBloke's Patreon page</a></p>
36
+ </div>
37
+ </div>
38
+ <div style="text-align:center; margin-top: 0em; margin-bottom: 0em"><p style="margin-top: 0.25em; margin-bottom: 0em;">TheBloke's LLM work is generously supported by a grant from <a href="https://a16z.com">andreessen horowitz (a16z)</a></p></div>
39
+ <hr style="margin-top: 1.0em; margin-bottom: 1.0em;">
40
+ <!-- header end -->
41
+
42
+ # Phi 2 - GPTQ
43
+ - Model creator: [Microsoft](https://huggingface.co/microsoft)
44
+ - Original model: [Phi 2](https://huggingface.co/microsoft/phi-2)
45
+
46
+ <!-- description start -->
47
+ # Description
48
+
49
+ This repo contains GPTQ model files for [Microsoft's Phi 2](https://huggingface.co/microsoft/phi-2).
50
+
51
+ Multiple GPTQ parameter permutations are provided; see Provided Files below for details of the options provided, their parameters, and the software used to create them.
52
+
53
+ <!-- description end -->
54
+ <!-- repositories-available start -->
55
+ ## Repositories available
56
+
57
+ * [GPTQ models for GPU inference, with multiple quantisation parameter options.](https://huggingface.co/TheBloke/phi-2-GPTQ)
58
+ * [Microsoft's original unquantised fp16 model in pytorch format, for GPU inference and for further conversions](https://huggingface.co/microsoft/phi-2)
59
+ <!-- repositories-available end -->
60
+
61
+ <!-- prompt-template start -->
62
+ ## Prompt template: Phi
63
+
64
+ ```
65
+ Instruct: {prompt}
66
+ Output:
67
+
68
+ ```
69
+
70
+ <!-- prompt-template end -->
71
+
72
+
73
+
74
+ <!-- README_GPTQ.md-compatible clients start -->
75
+ ## Known compatible clients / servers
76
+
77
+ GPTQ models are currently supported on Linux (NVidia/AMD) and Windows (NVidia only). macOS users: please use GGUF models.
78
+
79
+ These GPTQ models are known to work in the following inference servers/webuis.
80
+
81
+ - [text-generation-webui](https://github.com/oobabooga/text-generation-webui)
82
+ - [KoboldAI United](https://github.com/henk717/koboldai)
83
+ - [LoLLMS Web UI](https://github.com/ParisNeo/lollms-webui)
84
+ - [Hugging Face Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference)
85
+
86
+ This may not be a complete list; if you know of others, please let me know!
87
+ <!-- README_GPTQ.md-compatible clients end -->
88
+
89
+ <!-- README_GPTQ.md-provided-files start -->
90
+ ## Provided files, and GPTQ parameters
91
+
92
+ Multiple quantisation parameters are provided, to allow you to choose the best one for your hardware and requirements.
93
+
94
+ Each separate quant is in a different branch. See below for instructions on fetching from different branches.
95
+
96
+ Most GPTQ files are made with AutoGPTQ. Mistral models are currently made with Transformers.
97
+
98
+ <details>
99
+ <summary>Explanation of GPTQ parameters</summary>
100
+
101
+ - Bits: The bit size of the quantised model.
102
+ - GS: GPTQ group size. Higher numbers use less VRAM, but have lower quantisation accuracy. "None" is the lowest possible value.
103
+ - Act Order: True or False. Also known as `desc_act`. True results in better quantisation accuracy. Some GPTQ clients have had issues with models that use Act Order plus Group Size, but this is generally resolved now.
104
+ - Damp %: A GPTQ parameter that affects how samples are processed for quantisation. 0.01 is default, but 0.1 results in slightly better accuracy.
105
+ - GPTQ dataset: The calibration dataset used during quantisation. Using a dataset more appropriate to the model's training can improve quantisation accuracy. Note that the GPTQ calibration dataset is not the same as the dataset used to train the model - please refer to the original model repo for details of the training dataset(s).
106
+ - Sequence Length: The length of the dataset sequences used for quantisation. Ideally this is the same as the model sequence length. For some very long sequence models (16+K), a lower sequence length may have to be used. Note that a lower sequence length does not limit the sequence length of the quantised model. It only impacts the quantisation accuracy on longer inference sequences.
107
+ - ExLlama Compatibility: Whether this file can be loaded with ExLlama, which currently only supports Llama and Mistral models in 4-bit.
108
+
109
+ </details>
110
+
111
+ | Branch | Bits | GS | Act Order | Damp % | GPTQ Dataset | Seq Len | Size | ExLlama | Desc |
112
+ | ------ | ---- | -- | --------- | ------ | ------------ | ------- | ---- | ------- | ---- |
113
+ | main | 4 | 128 | Yes | 0.1 | [VMware Open Instruct](https://huggingface.co/datasets/VMware/open-instruct/viewer/) | 2048 | 1.84 GB | No | 4-bit, with Act Order and group size 128g. Uses even less VRAM than 64g, but with slightly lower accuracy. |
114
+ | gptq-4bit-32g-actorder_True | 4 | 32 | Yes | 0.1 | [VMware Open Instruct](https://huggingface.co/datasets/VMware/open-instruct/viewer/) | 2048 | 1.98 GB | No | 4-bit, with Act Order and group size 32g. Gives highest possible inference quality, with maximum VRAM usage. |
115
+ | gptq-8bit--1g-actorder_True | 8 | None | Yes | 0.1 | [VMware Open Instruct](https://huggingface.co/datasets/VMware/open-instruct/viewer/) | 2048 | 3.05 GB | No | 8-bit, with Act Order. No group size, to lower VRAM requirements. |
116
+ | gptq-8bit-128g-actorder_True | 8 | 128 | Yes | 0.1 | [VMware Open Instruct](https://huggingface.co/datasets/VMware/open-instruct/viewer/) | 2048 | 3.10 GB | No | 8-bit, with group size 128g for higher inference quality and with Act Order for even higher accuracy. |
117
+ | gptq-8bit-32g-actorder_True | 8 | 32 | Yes | 0.1 | [VMware Open Instruct](https://huggingface.co/datasets/VMware/open-instruct/viewer/) | 2048 | 3.28 GB | No | 8-bit, with group size 32g and Act Order for maximum inference quality. |
118
+ | gptq-4bit-64g-actorder_True | 4 | 64 | Yes | 0.1 | [VMware Open Instruct](https://huggingface.co/datasets/VMware/open-instruct/viewer/) | 2048 | 1.89 GB | No | 4-bit, with Act Order and group size 64g. Uses less VRAM than 32g, but with slightly lower accuracy. |
119
+
120
+ <!-- README_GPTQ.md-provided-files end -->
121
+
122
+ <!-- README_GPTQ.md-download-from-branches start -->
123
+ ## How to download, including from branches
124
+
125
+ ### In text-generation-webui
126
+
127
+ To download from the `main` branch, enter `TheBloke/phi-2-GPTQ` in the "Download model" box.
128
+
129
+ To download from another branch, add `:branchname` to the end of the download name, eg `TheBloke/phi-2-GPTQ:gptq-4bit-32g-actorder_True`
130
+
131
+ ### From the command line
132
+
133
+ I recommend using the `huggingface-hub` Python library:
134
+
135
+ ```shell
136
+ pip3 install huggingface-hub
137
+ ```
138
+
139
+ To download the `main` branch to a folder called `phi-2-GPTQ`:
140
+
141
+ ```shell
142
+ mkdir phi-2-GPTQ
143
+ huggingface-cli download TheBloke/phi-2-GPTQ --local-dir phi-2-GPTQ --local-dir-use-symlinks False
144
+ ```
145
+
146
+ To download from a different branch, add the `--revision` parameter:
147
+
148
+ ```shell
149
+ mkdir phi-2-GPTQ
150
+ huggingface-cli download TheBloke/phi-2-GPTQ --revision gptq-4bit-32g-actorder_True --local-dir phi-2-GPTQ --local-dir-use-symlinks False
151
+ ```
152
+
153
+ <details>
154
+ <summary>More advanced huggingface-cli download usage</summary>
155
+
156
+ If you remove the `--local-dir-use-symlinks False` parameter, the files will instead be stored in the central Hugging Face cache directory (default location on Linux is: `~/.cache/huggingface`), and symlinks will be added to the specified `--local-dir`, pointing to their real location in the cache. This allows for interrupted downloads to be resumed, and allows you to quickly clone the repo to multiple places on disk without triggering a download again. The downside, and the reason why I don't list that as the default option, is that the files are then hidden away in a cache folder and it's harder to know where your disk space is being used, and to clear it up if/when you want to remove a download model.
157
+
158
+ The cache location can be changed with the `HF_HOME` environment variable, and/or the `--cache-dir` parameter to `huggingface-cli`.
159
+
160
+ For more documentation on downloading with `huggingface-cli`, please see: [HF -> Hub Python Library -> Download files -> Download from the CLI](https://huggingface.co/docs/huggingface_hub/guides/download#download-from-the-cli).
161
+
162
+ To accelerate downloads on fast connections (1Gbit/s or higher), install `hf_transfer`:
163
+
164
+ ```shell
165
+ pip3 install hf_transfer
166
+ ```
167
+
168
+ And set environment variable `HF_HUB_ENABLE_HF_TRANSFER` to `1`:
169
+
170
+ ```shell
171
+ mkdir phi-2-GPTQ
172
+ HF_HUB_ENABLE_HF_TRANSFER=1 huggingface-cli download TheBloke/phi-2-GPTQ --local-dir phi-2-GPTQ --local-dir-use-symlinks False
173
+ ```
174
+
175
+ Windows Command Line users: You can set the environment variable by running `set HF_HUB_ENABLE_HF_TRANSFER=1` before the download command.
176
+ </details>
177
+
178
+ ### With `git` (**not** recommended)
179
+
180
+ To clone a specific branch with `git`, use a command like this:
181
+
182
+ ```shell
183
+ git clone --single-branch --branch gptq-4bit-32g-actorder_True https://huggingface.co/TheBloke/phi-2-GPTQ
184
+ ```
185
+
186
+ Note that using Git with HF repos is strongly discouraged. It will be much slower than using `huggingface-hub`, and will use twice as much disk space as it has to store the model files twice (it stores every byte both in the intended target folder, and again in the `.git` folder as a blob.)
187
+
188
+ <!-- README_GPTQ.md-download-from-branches end -->
189
+ <!-- README_GPTQ.md-text-generation-webui start -->
190
+ ## How to easily download and use this model in [text-generation-webui](https://github.com/oobabooga/text-generation-webui)
191
+
192
+ Please make sure you're using the latest version of [text-generation-webui](https://github.com/oobabooga/text-generation-webui).
193
+
194
+ It is strongly recommended to use the text-generation-webui one-click-installers unless you're sure you know how to make a manual install.
195
+
196
+ 1. Click the **Model tab**.
197
+ 2. Under **Download custom model or LoRA**, enter `TheBloke/phi-2-GPTQ`.
198
+
199
+ - To download from a specific branch, enter for example `TheBloke/phi-2-GPTQ:gptq-4bit-32g-actorder_True`
200
+ - see Provided Files above for the list of branches for each option.
201
+
202
+ 3. Click **Download**.
203
+ 4. The model will start downloading. Once it's finished it will say "Done".
204
+ 5. In the top left, click the refresh icon next to **Model**.
205
+ 6. In the **Model** dropdown, choose the model you just downloaded: `phi-2-GPTQ`
206
+ 7. The model will automatically load, and is now ready for use!
207
+ 8. If you want any custom settings, set them and then click **Save settings for this model** followed by **Reload the Model** in the top right.
208
+
209
+ - Note that you do not need to and should not set manual GPTQ parameters any more. These are set automatically from the file `quantize_config.json`.
210
+
211
+ 9. Once you're ready, click the **Text Generation** tab and enter a prompt to get started!
212
+
213
+ <!-- README_GPTQ.md-text-generation-webui end -->
214
+
215
+ <!-- README_GPTQ.md-use-from-tgi start -->
216
+ ## Serving this model from Text Generation Inference (TGI)
217
+
218
+ It's recommended to use TGI version 1.1.0 or later. The official Docker container is: `ghcr.io/huggingface/text-generation-inference:1.1.0`
219
+
220
+ Example Docker parameters:
221
+
222
+ ```shell
223
+ --model-id TheBloke/phi-2-GPTQ --port 3000 --quantize gptq --max-input-length 3696 --max-total-tokens 4096 --max-batch-prefill-tokens 4096
224
+ ```
225
+
226
+ Example Python code for interfacing with TGI (requires huggingface-hub 0.17.0 or later):
227
+
228
+ ```shell
229
+ pip3 install huggingface-hub
230
+ ```
231
+
232
+ ```python
233
+ from huggingface_hub import InferenceClient
234
+
235
+ endpoint_url = "https://your-endpoint-url-here"
236
+
237
+ prompt = "Tell me about AI"
238
+ prompt_template=f'''Instruct: {prompt}
239
+ Output:
240
+ '''
241
+
242
+ client = InferenceClient(endpoint_url)
243
+ response = client.text_generation(prompt,
244
+ max_new_tokens=128,
245
+ do_sample=True,
246
+ temperature=0.7,
247
+ top_p=0.95,
248
+ top_k=40,
249
+ repetition_penalty=1.1)
250
+
251
+ print(f"Model output: {response}")
252
+ ```
253
+ <!-- README_GPTQ.md-use-from-tgi end -->
254
+ <!-- README_GPTQ.md-use-from-python start -->
255
+ ## Python code example: inference from this GPTQ model
256
+
257
+ ### Install the necessary packages
258
+
259
+ Requires: Transformers 4.33.0 or later, Optimum 1.12.0 or later, and AutoGPTQ 0.4.2 or later.
260
+
261
+ ```shell
262
+ pip3 install --upgrade transformers optimum
263
+ # If using PyTorch 2.1 + CUDA 12.x:
264
+ pip3 install --upgrade auto-gptq
265
+ # or, if using PyTorch 2.1 + CUDA 11.x:
266
+ pip3 install --upgrade auto-gptq --extra-index-url https://huggingface.github.io/autogptq-index/whl/cu118/
267
+ ```
268
+
269
+ If you are using PyTorch 2.0, you will need to install AutoGPTQ from source. Likewise if you have problems with the pre-built wheels, you should try building from source:
270
+
271
+ ```shell
272
+ pip3 uninstall -y auto-gptq
273
+ git clone https://github.com/PanQiWei/AutoGPTQ
274
+ cd AutoGPTQ
275
+ git checkout v0.5.1
276
+ pip3 install .
277
+ ```
278
+
279
+ ### Example Python code
280
+
281
+ ```python
282
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
283
+
284
+ model_name_or_path = "TheBloke/phi-2-GPTQ"
285
+ # To use a different branch, change revision
286
+ # For example: revision="gptq-4bit-32g-actorder_True"
287
+ model = AutoModelForCausalLM.from_pretrained(model_name_or_path,
288
+ device_map="auto",
289
+ trust_remote_code=True,
290
+ revision="main")
291
+
292
+ tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=True)
293
+
294
+ prompt = "Write a story about llamas"
295
+ system_message = "You are a story writing assistant"
296
+ prompt_template=f'''Instruct: {prompt}
297
+ Output:
298
+ '''
299
+
300
+ print("\n\n*** Generate:")
301
+
302
+ input_ids = tokenizer(prompt_template, return_tensors='pt').input_ids.cuda()
303
+ output = model.generate(inputs=input_ids, temperature=0.7, do_sample=True, top_p=0.95, top_k=40, max_new_tokens=512)
304
+ print(tokenizer.decode(output[0]))
305
+
306
+ # Inference can also be done using transformers' pipeline
307
+
308
+ print("*** Pipeline:")
309
+ pipe = pipeline(
310
+ "text-generation",
311
+ model=model,
312
+ tokenizer=tokenizer,
313
+ max_new_tokens=512,
314
+ do_sample=True,
315
+ temperature=0.7,
316
+ top_p=0.95,
317
+ top_k=40,
318
+ repetition_penalty=1.1
319
+ )
320
+
321
+ print(pipe(prompt_template)[0]['generated_text'])
322
+ ```
323
+ <!-- README_GPTQ.md-use-from-python end -->
324
+
325
+ <!-- README_GPTQ.md-compatibility start -->
326
+ ## Compatibility
327
+
328
+ The files provided are tested to work with Transformers. For non-Mistral models, AutoGPTQ can also be used directly.
329
+
330
+ [ExLlama](https://github.com/turboderp/exllama) is compatible with Llama architecture models (including Mistral, Yi, DeepSeek, SOLAR, etc) in 4-bit. Please see the Provided Files table above for per-file compatibility.
331
+
332
+ For a list of clients/servers, please see "Known compatible clients / servers", above.
333
+ <!-- README_GPTQ.md-compatibility end -->
334
+
335
+ <!-- footer start -->
336
+ <!-- 200823 -->
337
+ ## Discord
338
+
339
+ For further support, and discussions on these models and AI in general, join us at:
340
+
341
+ [TheBloke AI's Discord server](https://discord.gg/theblokeai)
342
+
343
+ ## Thanks, and how to contribute
344
+
345
+ Thanks to the [chirper.ai](https://chirper.ai) team!
346
+
347
+ Thanks to Clay from [gpus.llm-utils.org](llm-utils)!
348
+
349
+ I've had a lot of people ask if they can contribute. I enjoy providing models and helping people, and would love to be able to spend even more time doing it, as well as expanding into new projects like fine tuning/training.
350
+
351
+ If you're able and willing to contribute it will be most gratefully received and will help me to keep providing more models, and to start work on new AI projects.
352
+
353
+ Donaters will get priority support on any and all AI/LLM/model questions and requests, access to a private Discord room, plus other benefits.
354
+
355
+ * Patreon: https://patreon.com/TheBlokeAI
356
+ * Ko-Fi: https://ko-fi.com/TheBlokeAI
357
+
358
+ **Special thanks to**: Aemon Algiz.
359
+
360
+ **Patreon special mentions**: Michael Levine, 阿明, Trailburnt, Nikolai Manek, John Detwiler, Randy H, Will Dee, Sebastain Graf, NimbleBox.ai, Eugene Pentland, Emad Mostaque, Ai Maven, Jim Angel, Jeff Scroggin, Michael Davis, Manuel Alberto Morcote, Stephen Murray, Robert, Justin Joy, Luke @flexchar, Brandon Frisco, Elijah Stavena, S_X, Dan Guido, Undi ., Komninos Chatzipapas, Shadi, theTransient, Lone Striker, Raven Klaugh, jjj, Cap'n Zoog, Michel-Marie MAUDET (LINAGORA), Matthew Berman, David, Fen Risland, Omer Bin Jawed, Luke Pendergrass, Kalila, OG, Erik Bjäreholt, Rooh Singh, Joseph William Delisle, Dan Lewis, TL, John Villwock, AzureBlack, Brad, Pedro Madruga, Caitlyn Gatomon, K, jinyuan sun, Mano Prime, Alex, Jeffrey Morgan, Alicia Loh, Illia Dulskyi, Chadd, transmissions 11, fincy, Rainer Wilmers, ReadyPlayerEmma, knownsqashed, Mandus, biorpg, Deo Leter, Brandon Phillips, SuperWojo, Sean Connelly, Iucharbius, Jack West, Harry Royden McLaughlin, Nicholas, terasurfer, Vitor Caleffi, Duane Dunston, Johann-Peter Hartmann, David Ziegler, Olakabola, Ken Nordquist, Trenton Dambrowitz, Tom X Nguyen, Vadim, Ajan Kanaga, Leonard Tan, Clay Pascal, Alexandros Triantafyllidis, JM33133, Xule, vamX, ya boyyy, subjectnull, Talal Aujan, Alps Aficionado, wassieverse, Ari Malik, James Bentley, Woland, Spencer Kim, Michael Dempsey, Fred von Graf, Elle, zynix, William Richards, Stanislav Ovsiannikov, Edmond Seymore, Jonathan Leane, Martin Kemka, usrbinkat, Enrico Ros
361
+
362
+
363
+ Thank you to all my generous patrons and donaters!
364
+
365
+ And thank you again to a16z for their generous grant.
366
+
367
+ <!-- footer end -->
368
+
369
+ # Original model card: Microsoft's Phi 2
370
+
371
+
372
+ ## Model Summary
373
+
374
+ Phi-2 is a Transformer with **2.7 billion** parameters. It was trained using the same data sources as [Phi-1.5](https://huggingface.co/microsoft/phi-1.5), augmented with a new data source that consists of various NLP synthetic texts and filtered websites (for safety and educational value). When assessed against benchmarks testing common sense, language understanding, and logical reasoning, Phi-2 showcased a nearly state-of-the-art performance among models with less than 13 billion parameters.
375
+
376
+ Our model hasn't been fine-tuned through reinforcement learning from human feedback. The intention behind crafting this open-source model is to provide the research community with a non-restricted small model to explore vital safety challenges, such as reducing toxicity, understanding societal biases, enhancing controllability, and more.
377
+
378
+ ## Intended Uses
379
+
380
+ Phi-2 is intended for research purposes only. Given the nature of the training data, the Phi-2 model is best suited for prompts using the QA format, the chat format, and the code format.
381
+
382
+ ### QA Format:
383
+
384
+ You can provide the prompt as a standalone question as follows:
385
+
386
+ ```markdown
387
+ Write a detailed analogy between mathematics and a lighthouse.
388
+ ```
389
+ where the model generates the text after "." .
390
+ To encourage the model to write more concise answers, you can also try the following QA format using "Instruct: \<prompt\>\nOutput:"
391
+ ```markdown
392
+ Instruct: Write a detailed analogy between mathematics and a lighthouse.
393
+ Output: Mathematics is like a lighthouse. Just as a lighthouse guides ships safely to shore, mathematics provides a guiding light in the world of numbers and logic. It helps us navigate through complex problems and find solutions. Just as a lighthouse emits a steady beam of light, mathematics provides a consistent framework for reasoning and problem-solving. It illuminates the path to understanding and helps us make sense of the world around us.
394
+ ```
395
+ where the model generates the text after "Output:".
396
+
397
+ ### Chat Format:
398
+
399
+ ```markdown
400
+ Alice: I don't know why, I'm struggling to maintain focus while studying. Any suggestions?
401
+ Bob: Well, have you tried creating a study schedule and sticking to it?
402
+ Alice: Yes, I have, but it doesn't seem to help much.
403
+ Bob: Hmm, maybe you should try studying in a quiet environment, like the library.
404
+ Alice: ...
405
+ ```
406
+
407
+ where the model generates the text after the first "Bob:".
408
+
409
+ ### Code Format:
410
+
411
+ ```python
412
+ def print_prime(n):
413
+ """
414
+ Print all primes between 1 and n
415
+ """
416
+ primes = []
417
+ for num in range(2, n+1):
418
+ is_prime = True
419
+ for i in range(2, int(math.sqrt(num))+1):
420
+ if num % i == 0:
421
+ is_prime = False
422
+ break
423
+ if is_prime:
424
+ primes.append(num)
425
+ print(primes)
426
+ ```
427
+ where the model generates the text after the comments.
428
+
429
+ **Notes:**
430
+ * Phi-2 is intended for research purposes. The model-generated text/code should be treated as a starting point rather than a definitive solution for potential use cases. Users should be cautious when employing these models in their applications.
431
+ * Direct adoption for production tasks is out of the scope of this research project. As a result, the Phi-2 model has not been tested to ensure that it performs adequately for any production-level application. Please refer to the limitation sections of this document for more details.
432
+ * If you are using `transformers>=4.36.0`, always load the model with `trust_remote_code=True` to prevent side-effects.
433
+
434
+ ## Sample Code
435
+
436
+ There are four types of execution mode:
437
+
438
+ 1. FP16 / Flash-Attention / CUDA:
439
+ ```python
440
+ model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype="auto", flash_attn=True, flash_rotary=True, fused_dense=True, device_map="cuda", trust_remote_code=True)
441
+ ```
442
+ 2. FP16 / CUDA:
443
+ ```python
444
+ model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype="auto", device_map="cuda", trust_remote_code=True)
445
+ ```
446
+ 3. FP32 / CUDA:
447
+ ```python
448
+ model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype=torch.float32, device_map="cuda", trust_remote_code=True)
449
+ ```
450
+ 4. FP32 / CPU:
451
+ ```python
452
+ model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype=torch.float32, device_map="cpu", trust_remote_code=True)
453
+ ```
454
+
455
+ To ensure the maximum compatibility, we recommend using the second execution mode (FP16 / CUDA), as follows:
456
+
457
+ ```python
458
+ import torch
459
+ from transformers import AutoModelForCausalLM, AutoTokenizer
460
+
461
+ torch.set_default_device("cuda")
462
+
463
+ model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype="auto", trust_remote_code=True)
464
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2", trust_remote_code=True)
465
+
466
+ inputs = tokenizer('''def print_prime(n):
467
+ """
468
+ Print all primes between 1 and n
469
+ """''', return_tensors="pt", return_attention_mask=False)
470
+
471
+ outputs = model.generate(**inputs, max_length=200)
472
+ text = tokenizer.batch_decode(outputs)[0]
473
+ print(text)
474
+ ```
475
+
476
+ **Remark:** In the generation function, our model currently does not support beam search (`num_beams > 1`).
477
+ Furthermore, in the forward pass of the model, we currently do not support outputting hidden states or attention values, or using custom input embeddings.
478
+
479
+ ## Limitations of Phi-2
480
+
481
+ * Generate Inaccurate Code and Facts: The model may produce incorrect code snippets and statements. Users should treat these outputs as suggestions or starting points, not as definitive or accurate solutions.
482
+
483
+ * Limited Scope for code: Majority of Phi-2 training data is based in Python and use common packages such as "typing, math, random, collections, datetime, itertools". If the model generates Python scripts that utilize other packages or scripts in other languages, we strongly recommend users manually verify all API uses.
484
+
485
+ * Unreliable Responses to Instruction: The model has not undergone instruction fine-tuning. As a result, it may struggle or fail to adhere to intricate or nuanced instructions provided by users.
486
+
487
+ * Language Limitations: The model is primarily designed to understand standard English. Informal English, slang, or any other languages might pose challenges to its comprehension, leading to potential misinterpretations or errors in response.
488
+
489
+ * Potential Societal Biases: Phi-2 is not entirely free from societal biases despite efforts in assuring trainig data safety. There's a possibility it may generate content that mirrors these societal biases, particularly if prompted or instructed to do so. We urge users to be aware of this and to exercise caution and critical thinking when interpreting model outputs.
490
+
491
+ * Toxicity: Despite being trained with carefully selected data, the model can still produce harmful content if explicitly prompted or instructed to do so. We chose to release the model for research purposes only -- We hope to help the open-source community develop the most effective ways to reduce the toxicity of a model directly after pretraining.
492
+
493
+ * Verbosity: Phi-2 being a base model often produces irrelevant or extra text and responses following its first answer to user prompts within a single turn. This is due to its training dataset being primarily textbooks, which results in textbook-like responses.
494
+
495
+ ## Training
496
+
497
+ ### Model
498
+
499
+ * Architecture: a Transformer-based model with next-word prediction objective
500
+
501
+ * Context length: 2048 tokens
502
+
503
+ * Dataset size: 250B tokens, combination of NLP synthetic data created by AOAI GPT-3.5 and filtered web data from Falcon RefinedWeb and SlimPajama, which was assessed by AOAI GPT-4.
504
+
505
+ * Training tokens: 1.4T tokens
506
+
507
+ * GPUs: 96xA100-80G
508
+
509
+ * Training time: 14 days
510
+
511
+ ### Software
512
+
513
+ * [PyTorch](https://github.com/pytorch/pytorch)
514
+
515
+ * [DeepSpeed](https://github.com/microsoft/DeepSpeed)
516
+
517
+ * [Flash-Attention](https://github.com/HazyResearch/flash-attention)
518
+
519
+ ### License
520
+
521
+ The model is licensed under the [microsoft-research-license](https://huggingface.co/microsoft/phi-2/resolve/main/LICENSE).
522
+
523
+ ## Trademarks
524
+
525
+ 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.