paulilioaica commited on
Commit
5508fb2
1 Parent(s): 7c79acf

Upload folder using huggingface_hub

Browse files
.amlignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ## This file was auto generated by the Azure Machine Learning Studio. Please do not remove.
2
+ ## Read more about the .amlignore file here: https://docs.microsoft.com/azure/machine-learning/how-to-save-write-experiment-files#storage-limits-of-experiment-snapshots
3
+
4
+ .ipynb_aml_checkpoints/
5
+ *.amltmp
6
+ *.amltemp
.amlignore.amltmp ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ## This file was auto generated by the Azure Machine Learning Studio. Please do not remove.
2
+ ## Read more about the .amlignore file here: https://docs.microsoft.com/azure/machine-learning/how-to-save-write-experiment-files#storage-limits-of-experiment-snapshots
3
+
4
+ .ipynb_aml_checkpoints/
5
+ *.amltmp
6
+ *.amltemp
README.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tags:
4
+ - moe
5
+ - frankenmoe
6
+ - merge
7
+ - mergekit
8
+ - lazymergekit
9
+ - microsoft/Phi-3-mini-128k-instruct
10
+ base_model:
11
+ - microsoft/Phi-3-mini-128k-instruct
12
+ - microsoft/Phi-3-mini-128k-instruct
13
+ ---
14
+
15
+ # MixtureOfPhi3
16
+
17
+ MixtureOfPhi3 is a Mixure of Experts (MoE) made with the following models using [LazyMergekit](https://colab.research.google.com/drive/1obulZ1ROXHjYLn6PPZJwRR6GzgQogxxb?usp=sharing):
18
+ * [microsoft/Phi-3-mini-128k-instruct](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct)
19
+ * [microsoft/Phi-3-mini-128k-instruct](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct)
20
+
21
+ ## 🧩 Configuration
22
+
23
+ ```yaml
24
+ base_model: microsoft/Phi-3-mini-128k-instruct
25
+ gate_mode: cheap_embed
26
+ dtype: float16
27
+ experts:
28
+ - source_model: microsoft/Phi-3-mini-128k-instruct
29
+ positive_prompts: ["research, logic, math, science"]
30
+ - source_model: microsoft/Phi-3-mini-128k-instruct
31
+ positive_prompts: ["creative, art"]
32
+ ```
33
+
34
+ ## 💻 Usage
35
+
36
+ ```python
37
+ !pip install -qU transformers bitsandbytes accelerate
38
+
39
+ from transformers import AutoTokenizer
40
+ import transformers
41
+ import torch
42
+
43
+ model = "paulilioaica/MixtureOfPhi3"
44
+
45
+ tokenizer = AutoTokenizer.from_pretrained(model)
46
+ pipeline = transformers.pipeline(
47
+ "text-generation",
48
+ model=model,
49
+ model_kwargs={"torch_dtype": torch.float16, "load_in_4bit": True},
50
+ )
51
+
52
+ messages = [{"role": "user", "content": "Explain what a Mixture of Experts is in less than 100 words."}]
53
+ prompt = pipeline.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
54
+ outputs = pipeline(prompt, max_new_tokens=256, do_sample=True, temperature=0.7, top_k=50, top_p=0.95)
55
+ print(outputs[0]["generated_text"])
56
+ ```
Test.ipynb ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 3,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "ename": "OSError",
10
+ "evalue": "Can't load tokenizer for 'paulilioaica/MixtureOfPhi3'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'paulilioaica/MixtureOfPhi3' is the correct path to a directory containing all relevant files for a LlamaTokenizerFast tokenizer.",
11
+ "output_type": "error",
12
+ "traceback": [
13
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
14
+ "\u001b[0;31mOSError\u001b[0m Traceback (most recent call last)",
15
+ "Cell \u001b[0;32mIn[3], line 7\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mtransformers\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m AutoModelForCausalLM, AutoTokenizer\n\u001b[1;32m 5\u001b[0m model \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mpaulilioaica/MixtureOfPhi3\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m----> 7\u001b[0m tokenizer \u001b[38;5;241m=\u001b[39m \u001b[43mAutoTokenizer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfrom_pretrained\u001b[49m\u001b[43m(\u001b[49m\u001b[43mmodel\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 8\u001b[0m model \u001b[38;5;241m=\u001b[39m AutoModelForCausalLM\u001b[38;5;241m.\u001b[39mfrom_pretrained(\n\u001b[1;32m 9\u001b[0m model, \n\u001b[1;32m 10\u001b[0m trust_remote_code\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m, \n\u001b[1;32m 11\u001b[0m )\n\u001b[1;32m 13\u001b[0m prompt\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mHow many continents are there?\u001b[39m\u001b[38;5;124m\"\u001b[39m\n",
16
+ "File \u001b[0;32m/anaconda/envs/azureml_py38/lib/python3.8/site-packages/transformers/models/auto/tokenization_auto.py:880\u001b[0m, in \u001b[0;36mAutoTokenizer.from_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, *inputs, **kwargs)\u001b[0m\n\u001b[1;32m 878\u001b[0m tokenizer_class_py, tokenizer_class_fast \u001b[38;5;241m=\u001b[39m TOKENIZER_MAPPING[\u001b[38;5;28mtype\u001b[39m(config)]\n\u001b[1;32m 879\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m tokenizer_class_fast \u001b[38;5;129;01mand\u001b[39;00m (use_fast \u001b[38;5;129;01mor\u001b[39;00m tokenizer_class_py \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m):\n\u001b[0;32m--> 880\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mtokenizer_class_fast\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfrom_pretrained\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpretrained_model_name_or_path\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43minputs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 881\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 882\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m tokenizer_class_py \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n",
17
+ "File \u001b[0;32m/anaconda/envs/azureml_py38/lib/python3.8/site-packages/transformers/tokenization_utils_base.py:2073\u001b[0m, in \u001b[0;36mPreTrainedTokenizerBase.from_pretrained\u001b[0;34m(cls, pretrained_model_name_or_path, cache_dir, force_download, local_files_only, token, revision, trust_remote_code, *init_inputs, **kwargs)\u001b[0m\n\u001b[1;32m 2067\u001b[0m logger\u001b[38;5;241m.\u001b[39minfo(\n\u001b[1;32m 2068\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCan\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mt load following files from cache: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00munresolved_files\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m and cannot check if these \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 2069\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mfiles are necessary for the tokenizer to operate.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 2070\u001b[0m )\n\u001b[1;32m 2072\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mall\u001b[39m(full_file_name \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;28;01mfor\u001b[39;00m full_file_name \u001b[38;5;129;01min\u001b[39;00m resolved_vocab_files\u001b[38;5;241m.\u001b[39mvalues()):\n\u001b[0;32m-> 2073\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mEnvironmentError\u001b[39;00m(\n\u001b[1;32m 2074\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mCan\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mt load tokenizer for \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpretrained_model_name_or_path\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m. If you were trying to load it from \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 2075\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mhttps://huggingface.co/models\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m, make sure you don\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mt have a local directory with the same name. \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 2076\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mOtherwise, make sure \u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpretrained_model_name_or_path\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m is the correct path to a directory \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 2077\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontaining all relevant files for a \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mcls\u001b[39m\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__name__\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m tokenizer.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 2078\u001b[0m )\n\u001b[1;32m 2080\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m file_id, file_path \u001b[38;5;129;01min\u001b[39;00m vocab_files\u001b[38;5;241m.\u001b[39mitems():\n\u001b[1;32m 2081\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m file_id \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m resolved_vocab_files:\n",
18
+ "\u001b[0;31mOSError\u001b[0m: Can't load tokenizer for 'paulilioaica/MixtureOfPhi3'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'paulilioaica/MixtureOfPhi3' is the correct path to a directory containing all relevant files for a LlamaTokenizerFast tokenizer."
19
+ ]
20
+ }
21
+ ],
22
+ "source": [
23
+ "import torch\n",
24
+ "from transformers import AutoModelForCausalLM, AutoTokenizer\n",
25
+ "\n",
26
+ "\n",
27
+ "model = \"paulilioaica/MixtureOfPhi3\"\n",
28
+ "\n",
29
+ "tokenizer = AutoTokenizer.from_pretrained(model)\n",
30
+ "model = AutoModelForCausalLM.from_pretrained(\n",
31
+ " model, \n",
32
+ " trust_remote_code=True, \n",
33
+ ")\n",
34
+ "\n",
35
+ "prompt=\"How many continents are there?\"\n",
36
+ "input = f\"<|system|>\\nYou are a helpful AI assistant.<|end|>\\n<|user|>{prompt}\\n<|assistant|>\"\n",
37
+ "tokenized_input = tokenizer.encode(input, return_tensors=\"pt\")\n",
38
+ "\n",
39
+ "outputs = model.generate(tokenized_input, max_new_tokens=128, do_sample=True, temperature=0.7, top_k=50, top_p=0.95)\n",
40
+ "print(outputs[0][\"generated_text\"])"
41
+ ]
42
+ }
43
+ ],
44
+ "metadata": {
45
+ "kernelspec": {
46
+ "display_name": "azureml_py38",
47
+ "language": "python",
48
+ "name": "python3"
49
+ },
50
+ "language_info": {
51
+ "codemirror_mode": {
52
+ "name": "ipython",
53
+ "version": 3
54
+ },
55
+ "file_extension": ".py",
56
+ "mimetype": "text/x-python",
57
+ "name": "python",
58
+ "nbconvert_exporter": "python",
59
+ "pygments_lexer": "ipython3",
60
+ "version": "3.8.5"
61
+ }
62
+ },
63
+ "nbformat": 4,
64
+ "nbformat_minor": 2
65
+ }
added_tokens.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|/code|>": 32014,
3
+ "<|/data|>": 32033,
4
+ "<|/inst|>": 32037,
5
+ "<|/query|>": 32031,
6
+ "<|/sys|>": 32035,
7
+ "<|assistant_mask|>": 32017,
8
+ "<|assistant|>": 32001,
9
+ "<|calc|>": 32012,
10
+ "<|code|>": 32013,
11
+ "<|continue|>": 32009,
12
+ "<|data|>": 32032,
13
+ "<|diff_marker|>": 32025,
14
+ "<|disc_sep|>": 32029,
15
+ "<|disc_start|>": 32028,
16
+ "<|disc_thread|><|query|>": 32030,
17
+ "<|endoftext|>": 32000,
18
+ "<|end|>": 32007,
19
+ "<|fim_middle|>": 32021,
20
+ "<|fim_prefix|>": 32020,
21
+ "<|fim_suffix|>": 32022,
22
+ "<|function_call|>": 32005,
23
+ "<|function_list|>": 32011,
24
+ "<|function_output|>": 32003,
25
+ "<|ghissue|>": 32026,
26
+ "<|ghreview|>": 32027,
27
+ "<|inst|>": 32036,
28
+ "<|ipynb_marker|>": 32024,
29
+ "<|message|>": 32019,
30
+ "<|meta_start|>": 32023,
31
+ "<|raw|>": 32008,
32
+ "<|resource|>": 32016,
33
+ "<|start|>": 32018,
34
+ "<|step|>": 32002,
35
+ "<|summary|>": 32015,
36
+ "<|system|>": 32006,
37
+ "<|sys|>": 32034,
38
+ "<|tag|>": 32004,
39
+ "<|user|>": 32010
40
+ }
config.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "microsoft/Phi-3-mini-128k-instruct",
3
+ "architectures": [
4
+ "Phi3ForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3.Phi3Config",
9
+ "AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "embd_pdrop": 0.0,
13
+ "eos_token_id": 32000,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 3072,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 8192,
18
+ "max_position_embeddings": 131072,
19
+ "model_type": "phi3",
20
+ "num_attention_heads": 32,
21
+ "num_experts_per_tok": 1,
22
+ "num_hidden_layers": 32,
23
+ "num_key_value_heads": 32,
24
+ "num_local_experts": 2,
25
+ "original_max_position_embeddings": 4096,
26
+ "output_router_logits": false,
27
+ "pad_token_id": 32000,
28
+ "resid_pdrop": 0.0,
29
+ "rms_norm_eps": 1e-05,
30
+ "rope_scaling": {
31
+ "long_factor": [
32
+ 1.0299999713897705,
33
+ 1.0499999523162842,
34
+ 1.0499999523162842,
35
+ 1.0799999237060547,
36
+ 1.2299998998641968,
37
+ 1.2299998998641968,
38
+ 1.2999999523162842,
39
+ 1.4499999284744263,
40
+ 1.5999999046325684,
41
+ 1.6499998569488525,
42
+ 1.8999998569488525,
43
+ 2.859999895095825,
44
+ 3.68999981880188,
45
+ 5.419999599456787,
46
+ 5.489999771118164,
47
+ 5.489999771118164,
48
+ 9.09000015258789,
49
+ 11.579999923706055,
50
+ 15.65999984741211,
51
+ 15.769999504089355,
52
+ 15.789999961853027,
53
+ 18.360000610351562,
54
+ 21.989999771118164,
55
+ 23.079999923706055,
56
+ 30.009998321533203,
57
+ 32.35000228881836,
58
+ 32.590003967285156,
59
+ 35.56000518798828,
60
+ 39.95000457763672,
61
+ 53.840003967285156,
62
+ 56.20000457763672,
63
+ 57.95000457763672,
64
+ 59.29000473022461,
65
+ 59.77000427246094,
66
+ 59.920005798339844,
67
+ 61.190006256103516,
68
+ 61.96000671386719,
69
+ 62.50000762939453,
70
+ 63.3700065612793,
71
+ 63.48000717163086,
72
+ 63.48000717163086,
73
+ 63.66000747680664,
74
+ 63.850006103515625,
75
+ 64.08000946044922,
76
+ 64.760009765625,
77
+ 64.80001068115234,
78
+ 64.81001281738281,
79
+ 64.81001281738281
80
+ ],
81
+ "short_factor": [
82
+ 1.05,
83
+ 1.05,
84
+ 1.05,
85
+ 1.1,
86
+ 1.1,
87
+ 1.1500000000000001,
88
+ 1.2000000000000002,
89
+ 1.2500000000000002,
90
+ 1.3000000000000003,
91
+ 1.3500000000000003,
92
+ 1.5000000000000004,
93
+ 2.000000000000001,
94
+ 2.000000000000001,
95
+ 2.000000000000001,
96
+ 2.000000000000001,
97
+ 2.000000000000001,
98
+ 2.000000000000001,
99
+ 2.000000000000001,
100
+ 2.000000000000001,
101
+ 2.000000000000001,
102
+ 2.000000000000001,
103
+ 2.000000000000001,
104
+ 2.000000000000001,
105
+ 2.000000000000001,
106
+ 2.000000000000001,
107
+ 2.000000000000001,
108
+ 2.000000000000001,
109
+ 2.000000000000001,
110
+ 2.000000000000001,
111
+ 2.000000000000001,
112
+ 2.000000000000001,
113
+ 2.000000000000001,
114
+ 2.0500000000000007,
115
+ 2.0500000000000007,
116
+ 2.0500000000000007,
117
+ 2.1000000000000005,
118
+ 2.1000000000000005,
119
+ 2.1000000000000005,
120
+ 2.1500000000000004,
121
+ 2.1500000000000004,
122
+ 2.3499999999999996,
123
+ 2.549999999999999,
124
+ 2.5999999999999988,
125
+ 2.5999999999999988,
126
+ 2.7499999999999982,
127
+ 2.849999999999998,
128
+ 2.849999999999998,
129
+ 2.9499999999999975
130
+ ],
131
+ "type": "su"
132
+ },
133
+ "rope_theta": 10000.0,
134
+ "router_aux_loss_coef": 0.001,
135
+ "router_jitter_noise": 0.0,
136
+ "sliding_window": null,
137
+ "tie_word_embeddings": false,
138
+ "torch_dtype": "float16",
139
+ "transformers_version": "4.40.1",
140
+ "use_cache": true,
141
+ "vocab_size": 32064
142
+ }
configuration_phi3.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ Phi-3 model configuration"""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json",
27
+ "microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class Phi3Config(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the
36
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32064):
43
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Phi3Model`].
45
+ hidden_size (`int`, *optional*, defaults to 3072):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 8192):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
62
+ Dropout probability for mlp outputs.
63
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the embeddings.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio after computing the attention scores.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model might ever be used with.
71
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
73
+ original RoPE embeddings when using long scaling.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon value used for the RMSNorm.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`dict`, *optional*):
86
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be either `su` or `yarn` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ The id of the "beginning-of-sequence" token.
92
+ eos_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the "end-of-sequence" token.
94
+ pad_token_id (`int`, *optional*, defaults to 32000):
95
+ The id of the padding token.
96
+ sliding_window (`int`, *optional*):
97
+ Sliding window attention window size. If `None`, no sliding window is applied.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import Phi3Model, Phi3Config
103
+
104
+ >>> # Initializing a Phi-3 style configuration
105
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = Phi3Model(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32064,
120
+ hidden_size=3072,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="silu",
129
+ max_position_embeddings=4096,
130
+ original_max_position_embeddings=4096,
131
+ initializer_range=0.02,
132
+ rms_norm_eps=1e-5,
133
+ use_cache=True,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ bos_token_id=1,
138
+ eos_token_id=32000,
139
+ pad_token_id=32000,
140
+ sliding_window=None,
141
+ num_experts=2,
142
+ num_experts_per_token=1,
143
+ **kwargs,
144
+ ):
145
+ self.vocab_size = vocab_size
146
+ self.hidden_size = hidden_size
147
+ self.intermediate_size = intermediate_size
148
+ self.num_hidden_layers = num_hidden_layers
149
+ self.num_attention_heads = num_attention_heads
150
+ self.num_experts = num_experts
151
+ self.num_experts_per_token = num_experts_per_token
152
+
153
+ if num_key_value_heads is None:
154
+ num_key_value_heads = num_attention_heads
155
+
156
+ self.num_key_value_heads = num_key_value_heads
157
+ self.resid_pdrop = resid_pdrop
158
+ self.embd_pdrop = embd_pdrop
159
+ self.attention_dropout = attention_dropout
160
+ self.hidden_act = hidden_act
161
+ self.max_position_embeddings = max_position_embeddings
162
+ self.original_max_position_embeddings = original_max_position_embeddings
163
+ self.initializer_range = initializer_range
164
+ self.rms_norm_eps = rms_norm_eps
165
+ self.use_cache = use_cache
166
+ self.rope_theta = rope_theta
167
+ self.rope_scaling = rope_scaling
168
+ self._rope_scaling_validation()
169
+ self.sliding_window = sliding_window
170
+
171
+ super().__init__(
172
+ bos_token_id=bos_token_id,
173
+ eos_token_id=eos_token_id,
174
+ pad_token_id=pad_token_id,
175
+ tie_word_embeddings=tie_word_embeddings,
176
+ **kwargs,
177
+ )
178
+
179
+ def _rope_scaling_validation(self):
180
+ """
181
+ Validate the `rope_scaling` configuration.
182
+ """
183
+ if self.rope_scaling is None:
184
+ return
185
+
186
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
187
+ raise ValueError(
188
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
189
+ f"got {self.rope_scaling}"
190
+ )
191
+ rope_scaling_type = self.rope_scaling.get("type", None)
192
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
193
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
194
+ if rope_scaling_type is None or rope_scaling_type not in ["su", "yarn"]:
195
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
196
+ if not (
197
+ isinstance(rope_scaling_short_factor, list)
198
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
199
+ ):
200
+ raise ValueError(
201
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
202
+ )
203
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
204
+ raise ValueError(
205
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
206
+ )
207
+ if not (
208
+ isinstance(rope_scaling_long_factor, list)
209
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
210
+ ):
211
+ raise ValueError(
212
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
213
+ )
214
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
215
+ raise ValueError(
216
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
217
+ )
mergekit_moe_config.yml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ base_model: microsoft/Phi-3-mini-128k-instruct
3
+ gate_mode: cheap_embed
4
+ dtype: float16
5
+ experts:
6
+ - source_model: microsoft/Phi-3-mini-128k-instruct
7
+ positive_prompts: ["research, logic, math, science"]
8
+ - source_model: microsoft/Phi-3-mini-128k-instruct
9
+ positive_prompts: ["creative, art"]
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c1a412c8664b87ea2aec7ef8e66815881235a6e40ac04343eb0773cc9c735ad
3
+ size 9957036944
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e96caa85b1302f9dbdcafd3c4a3b848f17fb61ff940371a99e2f5b519ade461
3
+ size 2517387096
model.safetensors.index.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"metadata": {"mergekit_version": "0.0.4"}, "weight_map": {"model.embed_tokens.weight": "model-00001-of-00002.safetensors", "lm_head.weight": "model-00001-of-00002.safetensors", "model.norm.weight": "model-00001-of-00002.safetensors", "model.layers.0.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.0.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.1.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.1.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.2.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.2.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.3.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.3.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.4.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.4.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.5.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.5.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.6.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.6.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.7.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.7.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.8.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.8.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.9.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.9.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.10.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.10.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.11.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.11.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.12.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.12.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.13.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.13.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.14.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.14.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.15.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.15.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.16.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.16.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.17.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.17.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.18.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.18.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.19.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.19.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.20.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.20.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.21.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.21.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.22.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.22.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.23.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.23.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.24.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.24.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.25.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.25.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.26.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.26.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.27.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.27.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.28.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.28.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.29.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.29.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.30.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.30.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.31.mlp.down_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.31.mlp.down_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.0.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.0.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.1.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.1.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.2.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.2.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.3.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.3.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.4.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.4.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.5.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.5.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.6.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.6.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.7.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.7.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.8.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.8.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.9.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.9.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.10.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.10.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.11.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.11.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.12.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.12.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.13.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.13.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.14.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.14.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.15.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.15.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.16.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.16.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.17.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.17.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.18.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.18.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.19.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.19.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.20.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.20.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.21.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.21.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.22.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.22.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.23.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.23.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.24.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.24.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.25.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.25.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.26.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.26.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.27.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.27.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.28.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.28.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.29.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.29.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.30.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.30.mlp.gate_up_proj.1.weight": "model-00001-of-00002.safetensors", "model.layers.31.mlp.gate_up_proj.0.weight": "model-00001-of-00002.safetensors", "model.layers.31.mlp.gate_up_proj.1.weight": "model-00002-of-00002.safetensors", "model.layers.0.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.1.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.2.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.3.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.4.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.5.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.6.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.7.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.8.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.9.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.10.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.11.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.12.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.13.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.14.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.15.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.16.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.17.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.18.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.19.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.20.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.0.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.1.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.2.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.3.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.4.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.5.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.6.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors", "model.layers.0.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.1.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.2.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.3.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.4.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.5.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.6.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.7.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.8.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.9.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.10.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.11.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.12.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.13.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.14.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.15.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.16.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.17.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.18.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.19.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.20.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.21.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.22.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.23.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.24.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.25.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.26.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.27.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.28.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.29.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.30.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.31.self_attn.qkv_proj.weight": "model-00002-of-00002.safetensors", "model.layers.0.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.1.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.2.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.3.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.4.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.5.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors", "model.layers.0.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.1.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.2.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.3.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.4.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.5.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.6.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.7.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.8.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.9.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.10.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.11.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.12.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.13.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.14.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.15.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.16.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.17.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.18.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.19.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.20.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.21.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.22.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.23.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.24.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.25.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.26.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.27.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.28.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.29.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.30.mlp.gate.weight": "model-00002-of-00002.safetensors", "model.layers.31.mlp.gate.weight": "model-00002-of-00002.safetensors"}}
modeling_phi3.py ADDED
@@ -0,0 +1,1598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi-3 model."""
17
+
18
+ import inspect
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_phi3 import Phi3Config
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
54
+ # if is_flash_attn_2_available():
55
+ _flash_supports_window_size = False
56
+ try:
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
61
+ except ImportError as error:
62
+ logger.warning(
63
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
64
+ )
65
+ if not _flash_supports_window_size:
66
+ logger.warning(
67
+ "Current `flash-attenton` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
68
+ )
69
+
70
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
71
+ _CONFIG_FOR_DOC = "Phi3Config"
72
+
73
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
74
+ "microsoft/Phi-3-mini-4k-instruct",
75
+ "microsoft/Phi-3-mini-128k-instruct",
76
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
77
+ ]
78
+
79
+
80
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
81
+ class Phi3RMSNorm(nn.Module):
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ """
84
+ Phi3RMSNorm is equivalent to T5LayerNorm
85
+ """
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+ self.variance_epsilon = eps
89
+
90
+ def forward(self, hidden_states):
91
+ input_dtype = hidden_states.dtype
92
+ hidden_states = hidden_states.to(torch.float32)
93
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
94
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
95
+ return self.weight * hidden_states.to(input_dtype)
96
+
97
+
98
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
99
+ def _get_unpad_data(attention_mask):
100
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
101
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
102
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
103
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
104
+ return (
105
+ indices,
106
+ cu_seqlens,
107
+ max_seqlen_in_batch,
108
+ )
109
+
110
+
111
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
112
+ class Phi3RotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ self.register_buffer("inv_freq", None, persistent=False)
120
+
121
+ @torch.no_grad()
122
+ def forward(self, x, position_ids, seq_len=None):
123
+ # x: [bs, num_attention_heads, seq_len, head_size]
124
+ if self.inv_freq is None:
125
+ self.inv_freq = 1.0 / (
126
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
127
+ )
128
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
129
+ position_ids_expanded = position_ids[:, None, :].float()
130
+ # Force float32 since bfloat16 loses precision on long contexts
131
+ # See https://github.com/huggingface/transformers/pull/29285
132
+ device_type = x.device.type
133
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
134
+ with torch.autocast(device_type=device_type, enabled=False):
135
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ cos = emb.cos()
138
+ sin = emb.sin()
139
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
140
+
141
+
142
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
143
+ def __init__(self, dim, config, device=None):
144
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
145
+
146
+ self.short_factor = config.rope_scaling["short_factor"]
147
+ self.long_factor = config.rope_scaling["long_factor"]
148
+ self.original_max_position_embeddings = config.original_max_position_embeddings
149
+
150
+ @torch.no_grad()
151
+ def forward(self, x, position_ids, seq_len=None):
152
+ seq_len = torch.max(position_ids) + 1
153
+ if seq_len > self.original_max_position_embeddings:
154
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
155
+ else:
156
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
157
+
158
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
159
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
160
+
161
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
162
+ position_ids_expanded = position_ids[:, None, :].float()
163
+
164
+ # Force float32 since bfloat16 loses precision on long contexts
165
+ # See https://github.com/huggingface/transformers/pull/29285
166
+ device_type = x.device.type
167
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
168
+ with torch.autocast(device_type=device_type, enabled=False):
169
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
170
+ emb = torch.cat((freqs, freqs), dim=-1)
171
+
172
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
173
+ if scale <= 1.0:
174
+ scaling_factor = 1.0
175
+ else:
176
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
177
+
178
+ cos = emb.cos() * scaling_factor
179
+ sin = emb.sin() * scaling_factor
180
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
181
+
182
+
183
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
184
+ def __init__(self, dim, config, device=None):
185
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
186
+
187
+ self.short_factor = config.rope_scaling["short_factor"]
188
+ self.long_factor = config.rope_scaling["long_factor"]
189
+ self.original_max_position_embeddings = config.original_max_position_embeddings
190
+
191
+ @torch.no_grad()
192
+ def forward(self, x, position_ids, seq_len=None):
193
+ seq_len = torch.max(position_ids) + 1
194
+ if seq_len > self.original_max_position_embeddings:
195
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
196
+ else:
197
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
198
+
199
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
200
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
201
+
202
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
203
+ position_ids_expanded = position_ids[:, None, :].float()
204
+
205
+ # Force float32 since bfloat16 loses precision on long contexts
206
+ # See https://github.com/huggingface/transformers/pull/29285
207
+ device_type = x.device.type
208
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
209
+ with torch.autocast(device_type=device_type, enabled=False):
210
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
211
+ emb = torch.cat((freqs, freqs), dim=-1)
212
+
213
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
214
+ if scale <= 1.0:
215
+ scaling_factor = 1.0
216
+ else:
217
+ scaling_factor = 0.1 * math.log(scale) + 1.0
218
+
219
+ cos = emb.cos() * scaling_factor
220
+ sin = emb.sin() * scaling_factor
221
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
222
+
223
+
224
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
225
+ def rotate_half(x):
226
+ """Rotates half the hidden dims of the input."""
227
+ x1 = x[..., : x.shape[-1] // 2]
228
+ x2 = x[..., x.shape[-1] // 2 :]
229
+ return torch.cat((-x2, x1), dim=-1)
230
+
231
+
232
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
233
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
234
+ """Applies Rotary Position Embedding to the query and key tensors.
235
+ Args:
236
+ q (`torch.Tensor`): The query tensor.
237
+ k (`torch.Tensor`): The key tensor.
238
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
239
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
240
+ position_ids (`torch.Tensor`, *optional*):
241
+ Deprecated and unused.
242
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
243
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
244
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
245
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
246
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
247
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
248
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
249
+ Returns:
250
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
251
+ """
252
+ cos = cos.unsqueeze(unsqueeze_dim)
253
+ sin = sin.unsqueeze(unsqueeze_dim)
254
+ q_embed = (q * cos) + (rotate_half(q) * sin)
255
+ k_embed = (k * cos) + (rotate_half(k) * sin)
256
+ return q_embed, k_embed
257
+
258
+
259
+ class Phi3MLP(nn.Module):
260
+ def __init__(self, config):
261
+ super().__init__()
262
+ self.config = config
263
+
264
+ self.gate = nn.Linear(config.hidden_size, self.config.num_experts, bias=False)
265
+ self.gate_up_proj = nn.ModuleList([nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False) for i in range(2)])
266
+ self.down_proj = nn.ModuleList([nn.Linear(config.intermediate_size, config.hidden_size, bias=False) for i in range(2)])
267
+ self.activation_fn = ACT2FN[config.hidden_act]
268
+
269
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
270
+
271
+ orig_shape = hidden_states.shape
272
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
273
+
274
+ experts_score = self.gate(hidden_states)
275
+ expert_weights, expert_indices = torch.topk(experts_score, self.config.num_experts_per_token, dim=-1)
276
+ expert_weights = expert_weights.softmax(dim=-1)
277
+
278
+ flat_expert_indices = expert_indices.view(-1)
279
+
280
+ y = torch.empty_like(hidden_states)
281
+
282
+ for i in range(self.config.num_experts):
283
+ current_mask = flat_expert_indices == i
284
+
285
+ up_states = self.gate_up_proj[i](hidden_states[current_mask])
286
+ gate, up_states = up_states.chunk(2, dim=-1)
287
+ up_states = up_states * self.activation_fn(gate)
288
+ out = self.down_proj[i](up_states)
289
+
290
+ y[current_mask] = out
291
+
292
+ y = (y.view(*expert_weights.shape, -1) * expert_weights.unsqueeze(-1)).sum(dim=1)
293
+ return y.view(*orig_shape)
294
+
295
+
296
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
297
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
298
+ """
299
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
300
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
301
+ """
302
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
303
+ if n_rep == 1:
304
+ return hidden_states
305
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
306
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
307
+
308
+
309
+ class Phi3Attention(nn.Module):
310
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
311
+
312
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
313
+ super().__init__()
314
+ self.config = config
315
+ self.layer_idx = layer_idx
316
+ if layer_idx is None:
317
+ logger.warning_once(
318
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
319
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
320
+ "when creating this class."
321
+ )
322
+
323
+ self.attention_dropout = config.attention_dropout
324
+ self.hidden_size = config.hidden_size
325
+ self.num_heads = config.num_attention_heads
326
+ self.head_dim = self.hidden_size // self.num_heads
327
+ self.num_key_value_heads = config.num_key_value_heads
328
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
329
+ self.max_position_embeddings = config.max_position_embeddings
330
+ self.original_max_position_embeddings = config.original_max_position_embeddings
331
+ self.rope_theta = config.rope_theta
332
+ self.rope_scaling = config.rope_scaling
333
+ self.is_causal = True
334
+
335
+ if (self.head_dim * self.num_heads) != self.hidden_size:
336
+ raise ValueError(
337
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
338
+ f" and `num_heads`: {self.num_heads})."
339
+ )
340
+
341
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
342
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
343
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
344
+ self._init_rope()
345
+
346
+ def _init_rope(self):
347
+ if self.rope_scaling is None:
348
+ self.rotary_emb = Phi3RotaryEmbedding(
349
+ self.head_dim,
350
+ max_position_embeddings=self.max_position_embeddings,
351
+ base=self.rope_theta,
352
+ )
353
+ else:
354
+ scaling_type = self.config.rope_scaling["type"]
355
+ if scaling_type == "su":
356
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
357
+ elif scaling_type == "yarn":
358
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
359
+ else:
360
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
361
+
362
+ def forward(
363
+ self,
364
+ hidden_states: torch.Tensor,
365
+ attention_mask: Optional[torch.Tensor] = None,
366
+ position_ids: Optional[torch.LongTensor] = None,
367
+ past_key_value: Optional[Cache] = None,
368
+ output_attentions: bool = False,
369
+ use_cache: bool = False,
370
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
371
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
372
+
373
+ bsz, q_len, _ = hidden_states.size()
374
+
375
+ qkv = self.qkv_proj(hidden_states)
376
+ query_pos = self.num_heads * self.head_dim
377
+ query_states = qkv[..., :query_pos]
378
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
379
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
380
+
381
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
382
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
383
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
384
+
385
+ kv_seq_len = key_states.shape[-2]
386
+ if past_key_value is not None:
387
+ if self.layer_idx is None:
388
+ raise ValueError(
389
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
390
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
391
+ "with a layer index."
392
+ )
393
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
394
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
395
+
396
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
397
+
398
+ if past_key_value is not None:
399
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
400
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
401
+
402
+ # repeat k/v heads if n_kv_heads < n_heads
403
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
404
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
405
+
406
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
407
+
408
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
409
+ raise ValueError(
410
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
411
+ f" {attn_weights.size()}"
412
+ )
413
+
414
+ if attention_mask is not None:
415
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
416
+ raise ValueError(
417
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
418
+ )
419
+ attn_weights = attn_weights + attention_mask
420
+
421
+ # upcast attention to fp32
422
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
423
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
424
+
425
+ attn_output = torch.matmul(attn_weights, value_states)
426
+
427
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
428
+ raise ValueError(
429
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
430
+ f" {attn_output.size()}"
431
+ )
432
+
433
+ attn_output = attn_output.transpose(1, 2).contiguous()
434
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
435
+
436
+ attn_output = self.o_proj(attn_output)
437
+
438
+ if not output_attentions:
439
+ attn_weights = None
440
+
441
+ return attn_output, attn_weights, past_key_value
442
+
443
+
444
+ class Phi3FlashAttention2(Phi3Attention):
445
+ """
446
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
447
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
448
+ flash attention and deal with padding tokens in case the input contains any of them.
449
+ """
450
+
451
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
452
+ def __init__(self, *args, **kwargs):
453
+ super().__init__(*args, **kwargs)
454
+
455
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
456
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
457
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
458
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
459
+
460
+ def forward(
461
+ self,
462
+ hidden_states: torch.Tensor,
463
+ attention_mask: Optional[torch.LongTensor] = None,
464
+ position_ids: Optional[torch.LongTensor] = None,
465
+ past_key_value: Optional[Cache] = None,
466
+ output_attentions: bool = False,
467
+ use_cache: bool = False,
468
+ **kwargs,
469
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
470
+ # Phi3FlashAttention2 attention does not support output_attentions
471
+
472
+ if not _flash_supports_window_size:
473
+ logger.warning_once(
474
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
475
+ )
476
+ raise ValueError("The current flash attention version does not support sliding window attention.")
477
+
478
+ output_attentions = False
479
+
480
+ if "padding_mask" in kwargs:
481
+ warnings.warn(
482
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
483
+ )
484
+
485
+ # overwrite attention_mask with padding_mask
486
+ attention_mask = kwargs.pop("padding_mask")
487
+
488
+ bsz, q_len, _ = hidden_states.size()
489
+
490
+ qkv = self.qkv_proj(hidden_states)
491
+ query_pos = self.num_heads * self.head_dim
492
+ query_states = qkv[..., :query_pos]
493
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
494
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
495
+
496
+ # Flash attention requires the input to have the shape
497
+ # batch_size x seq_length x head_dim x hidden_dim
498
+ # therefore we just need to keep the original shape
499
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
500
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
501
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
502
+
503
+ kv_seq_len = key_states.shape[-2]
504
+ if past_key_value is not None:
505
+ if self.layer_idx is None:
506
+ raise ValueError(
507
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
508
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
509
+ "with a layer index."
510
+ )
511
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
512
+
513
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
514
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
515
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
516
+
517
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
518
+
519
+ use_sliding_windows = (
520
+ _flash_supports_window_size
521
+ and getattr(self.config, "sliding_window", None) is not None
522
+ and kv_seq_len > self.config.sliding_window
523
+ )
524
+
525
+ if past_key_value is not None:
526
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
527
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
528
+ if (
529
+ getattr(self.config, "sliding_window", None) is not None
530
+ and kv_seq_len > self.config.sliding_window
531
+ and cache_has_contents
532
+ ):
533
+ slicing_tokens = 1 - self.config.sliding_window
534
+
535
+ past_key = past_key_value[self.layer_idx][0]
536
+ past_value = past_key_value[self.layer_idx][1]
537
+
538
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
539
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
540
+
541
+ if past_key.shape[-2] != self.config.sliding_window - 1:
542
+ raise ValueError(
543
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
544
+ f" {past_key.shape}"
545
+ )
546
+
547
+ if attention_mask is not None:
548
+ attention_mask = attention_mask[:, slicing_tokens:]
549
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
550
+
551
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
552
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
553
+
554
+ # repeat k/v heads if n_kv_heads < n_heads
555
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
556
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
557
+
558
+ attn_dropout = self.attention_dropout if self.training else 0.0
559
+
560
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
561
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
562
+ # cast them back in the correct dtype just to be sure everything works as expected.
563
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
564
+ # in fp32.
565
+
566
+ if query_states.dtype == torch.float32:
567
+ if torch.is_autocast_enabled():
568
+ target_dtype = torch.get_autocast_gpu_dtype()
569
+ # Handle the case where the model is quantized
570
+ elif hasattr(self.config, "_pre_quantization_dtype"):
571
+ target_dtype = self.config._pre_quantization_dtype
572
+ else:
573
+ target_dtype = self.qkv_proj.weight.dtype
574
+
575
+ logger.warning_once(
576
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
577
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
578
+ f" {target_dtype}."
579
+ )
580
+
581
+ query_states = query_states.to(target_dtype)
582
+ key_states = key_states.to(target_dtype)
583
+ value_states = value_states.to(target_dtype)
584
+
585
+ # Reashape to the expected shape for Flash Attention
586
+ query_states = query_states.transpose(1, 2)
587
+ key_states = key_states.transpose(1, 2)
588
+ value_states = value_states.transpose(1, 2)
589
+
590
+ attn_output = self._flash_attention_forward(
591
+ query_states,
592
+ key_states,
593
+ value_states,
594
+ attention_mask,
595
+ q_len,
596
+ dropout=attn_dropout,
597
+ use_sliding_windows=use_sliding_windows,
598
+ )
599
+
600
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
601
+ attn_output = self.o_proj(attn_output)
602
+
603
+ if not output_attentions:
604
+ attn_weights = None
605
+
606
+ return attn_output, attn_weights, past_key_value
607
+
608
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
609
+ def _flash_attention_forward(
610
+ self,
611
+ query_states,
612
+ key_states,
613
+ value_states,
614
+ attention_mask,
615
+ query_length,
616
+ dropout=0.0,
617
+ softmax_scale=None,
618
+ use_sliding_windows=False,
619
+ ):
620
+ """
621
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
622
+ first unpad the input, then computes the attention scores and pad the final attention scores.
623
+ Args:
624
+ query_states (`torch.Tensor`):
625
+ Input query states to be passed to Flash Attention API
626
+ key_states (`torch.Tensor`):
627
+ Input key states to be passed to Flash Attention API
628
+ value_states (`torch.Tensor`):
629
+ Input value states to be passed to Flash Attention API
630
+ attention_mask (`torch.Tensor`):
631
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
632
+ position of padding tokens and 1 for the position of non-padding tokens.
633
+ dropout (`float`):
634
+ Attention dropout
635
+ softmax_scale (`float`, *optional*):
636
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
637
+ use_sliding_windows (`bool`, *optional*):
638
+ Whether to activate sliding window attention.
639
+ """
640
+ if not self._flash_attn_uses_top_left_mask:
641
+ causal = self.is_causal
642
+ else:
643
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
644
+ causal = self.is_causal and query_length != 1
645
+
646
+ # Contains at least one padding token in the sequence
647
+ if attention_mask is not None:
648
+ batch_size = query_states.shape[0]
649
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
650
+ query_states, key_states, value_states, attention_mask, query_length
651
+ )
652
+
653
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
654
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
655
+
656
+ if not use_sliding_windows:
657
+ attn_output_unpad = flash_attn_varlen_func(
658
+ query_states,
659
+ key_states,
660
+ value_states,
661
+ cu_seqlens_q=cu_seqlens_q,
662
+ cu_seqlens_k=cu_seqlens_k,
663
+ max_seqlen_q=max_seqlen_in_batch_q,
664
+ max_seqlen_k=max_seqlen_in_batch_k,
665
+ dropout_p=dropout,
666
+ softmax_scale=softmax_scale,
667
+ causal=causal,
668
+ )
669
+ else:
670
+ attn_output_unpad = flash_attn_varlen_func(
671
+ query_states,
672
+ key_states,
673
+ value_states,
674
+ cu_seqlens_q=cu_seqlens_q,
675
+ cu_seqlens_k=cu_seqlens_k,
676
+ max_seqlen_q=max_seqlen_in_batch_q,
677
+ max_seqlen_k=max_seqlen_in_batch_k,
678
+ dropout_p=dropout,
679
+ softmax_scale=softmax_scale,
680
+ causal=causal,
681
+ window_size=(self.config.sliding_window, self.config.sliding_window),
682
+ )
683
+
684
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
685
+ else:
686
+ if not use_sliding_windows:
687
+ attn_output = flash_attn_func(
688
+ query_states,
689
+ key_states,
690
+ value_states,
691
+ dropout,
692
+ softmax_scale=softmax_scale,
693
+ causal=causal,
694
+ )
695
+ else:
696
+ attn_output = flash_attn_func(
697
+ query_states,
698
+ key_states,
699
+ value_states,
700
+ dropout,
701
+ softmax_scale=softmax_scale,
702
+ causal=causal,
703
+ window_size=(self.config.sliding_window, self.config.sliding_window),
704
+ )
705
+
706
+ return attn_output
707
+
708
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
709
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
710
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
711
+
712
+ # On the first iteration we need to properly re-create the padding mask
713
+ # by slicing it on the proper place
714
+ if kv_seq_len != attention_mask.shape[-1]:
715
+ attention_mask_num_tokens = attention_mask.shape[-1]
716
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
717
+
718
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
719
+
720
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
721
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
722
+
723
+ if query_length == kv_seq_len:
724
+ query_layer = index_first_axis(
725
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
726
+ )
727
+ cu_seqlens_q = cu_seqlens_k
728
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
729
+ indices_q = indices_k
730
+ elif query_length == 1:
731
+ max_seqlen_in_batch_q = 1
732
+ cu_seqlens_q = torch.arange(
733
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
734
+ ) # There is a memcpy here, that is very bad.
735
+ indices_q = cu_seqlens_q[:-1]
736
+ query_layer = query_layer.squeeze(1)
737
+ else:
738
+ # The -q_len: slice assumes left padding.
739
+ attention_mask = attention_mask[:, -query_length:]
740
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
741
+
742
+ return (
743
+ query_layer,
744
+ key_layer,
745
+ value_layer,
746
+ indices_q,
747
+ (cu_seqlens_q, cu_seqlens_k),
748
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
749
+ )
750
+
751
+
752
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
753
+ # TODO @Arthur no longer copied from LLama after static cache
754
+ class Phi3SdpaAttention(Phi3Attention):
755
+ """
756
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
757
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
758
+ SDPA API.
759
+ """
760
+
761
+ # Adapted from Phi3Attention.forward
762
+ def forward(
763
+ self,
764
+ hidden_states: torch.Tensor,
765
+ attention_mask: Optional[torch.Tensor] = None,
766
+ position_ids: Optional[torch.LongTensor] = None,
767
+ past_key_value: Optional[Cache] = None,
768
+ output_attentions: bool = False,
769
+ use_cache: bool = False,
770
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
771
+ if output_attentions:
772
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
773
+ logger.warning_once(
774
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
775
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
776
+ )
777
+ return super().forward(
778
+ hidden_states=hidden_states,
779
+ attention_mask=attention_mask,
780
+ position_ids=position_ids,
781
+ past_key_value=past_key_value,
782
+ output_attentions=output_attentions,
783
+ use_cache=use_cache,
784
+ )
785
+
786
+ bsz, q_len, _ = hidden_states.size()
787
+
788
+ qkv = self.qkv_proj(hidden_states)
789
+ query_pos = self.num_heads * self.head_dim
790
+ query_states = qkv[..., :query_pos]
791
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
792
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
793
+
794
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
795
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
796
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
797
+
798
+ kv_seq_len = key_states.shape[-2]
799
+ if past_key_value is not None:
800
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
801
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
802
+
803
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
804
+
805
+ if past_key_value is not None:
806
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
807
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
808
+
809
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
810
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
811
+
812
+ if attention_mask is not None:
813
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
814
+ raise ValueError(
815
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
816
+ )
817
+
818
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
819
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
820
+ if query_states.device.type == "cuda" and attention_mask is not None:
821
+ query_states = query_states.contiguous()
822
+ key_states = key_states.contiguous()
823
+ value_states = value_states.contiguous()
824
+
825
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
826
+ query_states,
827
+ key_states,
828
+ value_states,
829
+ attn_mask=attention_mask,
830
+ dropout_p=self.attention_dropout if self.training else 0.0,
831
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
832
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
833
+ )
834
+
835
+ attn_output = attn_output.transpose(1, 2).contiguous()
836
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
837
+
838
+ attn_output = self.o_proj(attn_output)
839
+
840
+ return attn_output, None, past_key_value
841
+
842
+
843
+ PHI3_ATTENTION_CLASSES = {
844
+ "eager": Phi3Attention,
845
+ "flash_attention_2": Phi3FlashAttention2,
846
+ "sdpa": Phi3SdpaAttention,
847
+ }
848
+
849
+
850
+ class Phi3DecoderLayer(nn.Module):
851
+ def __init__(self, config: Phi3Config, layer_idx: int):
852
+ super().__init__()
853
+
854
+ self.config = config
855
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
856
+
857
+ self.mlp = Phi3MLP(config)
858
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
859
+
860
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
861
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
862
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
863
+
864
+ def forward(
865
+ self,
866
+ hidden_states: torch.Tensor,
867
+ attention_mask: Optional[torch.Tensor] = None,
868
+ position_ids: Optional[torch.LongTensor] = None,
869
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
870
+ output_attentions: Optional[bool] = False,
871
+ use_cache: Optional[bool] = False,
872
+ **kwargs,
873
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
874
+ if "padding_mask" in kwargs:
875
+ warnings.warn(
876
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
877
+ )
878
+ """
879
+ Args:
880
+ hidden_states (`torch.FloatTensor`):
881
+ input to the layer of shape `(batch, seq_len, embed_dim)`
882
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
883
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
884
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
885
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
886
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
887
+ output_attentions (`bool`, *optional*):
888
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
889
+ returned tensors for more detail.
890
+ use_cache (`bool`, *optional*):
891
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
892
+ (see `past_key_values`).
893
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
894
+ """
895
+
896
+ residual = hidden_states
897
+
898
+ hidden_states = self.input_layernorm(hidden_states)
899
+
900
+ # Self Attention
901
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
902
+ hidden_states=hidden_states,
903
+ attention_mask=attention_mask,
904
+ position_ids=position_ids,
905
+ past_key_value=past_key_value,
906
+ output_attentions=output_attentions,
907
+ use_cache=use_cache,
908
+ )
909
+
910
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
911
+
912
+ residual = hidden_states
913
+ hidden_states = self.post_attention_layernorm(hidden_states)
914
+ hidden_states = self.mlp(hidden_states)
915
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
916
+
917
+ outputs = (hidden_states,)
918
+
919
+ if output_attentions:
920
+ outputs += (self_attn_weights,)
921
+
922
+ if use_cache:
923
+ outputs += (present_key_value,)
924
+
925
+ return outputs
926
+
927
+
928
+ PHI3_START_DOCSTRING = r"""
929
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
930
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
931
+ etc.)
932
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
933
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
934
+ and behavior.
935
+ Parameters:
936
+ config ([`Phi3Config`]):
937
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
938
+ load the weights associated with the model, only the configuration. Check out the
939
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
940
+ """
941
+
942
+
943
+ @add_start_docstrings(
944
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
945
+ PHI3_START_DOCSTRING,
946
+ )
947
+ class Phi3PreTrainedModel(PreTrainedModel):
948
+ config_class = Phi3Config
949
+ base_model_prefix = "model"
950
+ supports_gradient_checkpointing = True
951
+ _no_split_modules = ["Phi3DecoderLayer"]
952
+ _skip_keys_device_placement = "past_key_values"
953
+ _supports_flash_attn_2 = True
954
+ _supports_sdpa = False
955
+ _supports_cache_class = True
956
+
957
+ _version = "0.0.5"
958
+
959
+ def _init_weights(self, module):
960
+ std = self.config.initializer_range
961
+ if isinstance(module, nn.Linear):
962
+ module.weight.data.normal_(mean=0.0, std=std)
963
+ if module.bias is not None:
964
+ module.bias.data.zero_()
965
+ elif isinstance(module, nn.Embedding):
966
+ module.weight.data.normal_(mean=0.0, std=std)
967
+ if module.padding_idx is not None:
968
+ module.weight.data[module.padding_idx].zero_()
969
+
970
+
971
+ PHI3_INPUTS_DOCSTRING = r"""
972
+ Args:
973
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
974
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
975
+ it.
976
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
977
+ [`PreTrainedTokenizer.__call__`] for details.
978
+ [What are input IDs?](../glossary#input-ids)
979
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
980
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
981
+ - 1 for tokens that are **not masked**,
982
+ - 0 for tokens that are **masked**.
983
+ [What are attention masks?](../glossary#attention-mask)
984
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
985
+ [`PreTrainedTokenizer.__call__`] for details.
986
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
987
+ `past_key_values`).
988
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
989
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
990
+ information on the default strategy.
991
+ - 1 indicates the head is **not masked**,
992
+ - 0 indicates the head is **masked**.
993
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
994
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
995
+ config.n_positions - 1]`.
996
+ [What are position IDs?](../glossary#position-ids)
997
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
998
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
999
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1000
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1001
+ Two formats are allowed:
1002
+ - a [`~cache_utils.Cache`] instance;
1003
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1004
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1005
+ cache format.
1006
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1007
+ legacy cache format will be returned.
1008
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1009
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1010
+ of shape `(batch_size, sequence_length)`.
1011
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1012
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1013
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1014
+ model's internal embedding lookup matrix.
1015
+ use_cache (`bool`, *optional*):
1016
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1017
+ `past_key_values`).
1018
+ output_attentions (`bool`, *optional*):
1019
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1020
+ tensors for more detail.
1021
+ output_hidden_states (`bool`, *optional*):
1022
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1023
+ more detail.
1024
+ return_dict (`bool`, *optional*):
1025
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1026
+ """
1027
+
1028
+
1029
+ @add_start_docstrings(
1030
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
1031
+ PHI3_START_DOCSTRING,
1032
+ )
1033
+ class Phi3Model(Phi3PreTrainedModel):
1034
+ """
1035
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1036
+ Args:
1037
+ config: Phi3Config
1038
+ """
1039
+
1040
+ def __init__(self, config: Phi3Config):
1041
+ super().__init__(config)
1042
+ self.padding_idx = config.pad_token_id
1043
+ self.vocab_size = config.vocab_size
1044
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1045
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1046
+ self.layers = nn.ModuleList(
1047
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1048
+ )
1049
+ self._attn_implementation = config._attn_implementation
1050
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1051
+
1052
+ self.gradient_checkpointing = False
1053
+ # Initialize weights and apply final processing
1054
+ self.post_init()
1055
+
1056
+ def get_input_embeddings(self):
1057
+ return self.embed_tokens
1058
+
1059
+ def set_input_embeddings(self, value):
1060
+ self.embed_tokens = value
1061
+
1062
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1063
+ def forward(
1064
+ self,
1065
+ input_ids: torch.LongTensor = None,
1066
+ attention_mask: Optional[torch.Tensor] = None,
1067
+ position_ids: Optional[torch.LongTensor] = None,
1068
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1069
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1070
+ use_cache: Optional[bool] = None,
1071
+ output_attentions: Optional[bool] = None,
1072
+ output_hidden_states: Optional[bool] = None,
1073
+ return_dict: Optional[bool] = None,
1074
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1075
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1076
+ output_hidden_states = (
1077
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1078
+ )
1079
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1080
+
1081
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1082
+
1083
+ # retrieve input_ids and inputs_embeds
1084
+ if input_ids is not None and inputs_embeds is not None:
1085
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1086
+ elif input_ids is not None:
1087
+ batch_size, seq_length = input_ids.shape[:2]
1088
+ elif inputs_embeds is not None:
1089
+ batch_size, seq_length = inputs_embeds.shape[:2]
1090
+ else:
1091
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1092
+
1093
+ past_key_values_length = 0
1094
+
1095
+ if self.gradient_checkpointing and self.training:
1096
+ if use_cache:
1097
+ logger.warning_once(
1098
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1099
+ )
1100
+ use_cache = False
1101
+
1102
+ if use_cache:
1103
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1104
+ if use_legacy_cache:
1105
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1106
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1107
+
1108
+ if position_ids is None:
1109
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1110
+ position_ids = torch.arange(
1111
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1112
+ )
1113
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1114
+ else:
1115
+ position_ids = position_ids.view(-1, seq_length).long()
1116
+
1117
+ if inputs_embeds is None:
1118
+ inputs_embeds = self.embed_tokens(input_ids)
1119
+
1120
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1121
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1122
+ if is_padding_right:
1123
+ raise ValueError(
1124
+ "You are attempting to perform batched generation with padding_side='right'"
1125
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1126
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1127
+ )
1128
+
1129
+ if self._attn_implementation == "flash_attention_2":
1130
+ # 2d mask is passed through the layers
1131
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1132
+ else:
1133
+ # 4d mask is passed through the layers
1134
+ attention_mask = _prepare_4d_causal_attention_mask(
1135
+ attention_mask,
1136
+ (batch_size, seq_length),
1137
+ inputs_embeds,
1138
+ past_key_values_length,
1139
+ sliding_window=self.config.sliding_window,
1140
+ )
1141
+
1142
+ hidden_states = inputs_embeds
1143
+
1144
+ # decoder layers
1145
+ all_hidden_states = () if output_hidden_states else None
1146
+ all_self_attns = () if output_attentions else None
1147
+ next_decoder_cache = None
1148
+
1149
+ for decoder_layer in self.layers:
1150
+ if output_hidden_states:
1151
+ all_hidden_states += (hidden_states,)
1152
+
1153
+ if self.gradient_checkpointing and self.training:
1154
+ layer_outputs = self._gradient_checkpointing_func(
1155
+ decoder_layer.__call__,
1156
+ hidden_states,
1157
+ attention_mask,
1158
+ position_ids,
1159
+ past_key_values,
1160
+ output_attentions,
1161
+ use_cache,
1162
+ )
1163
+ else:
1164
+ layer_outputs = decoder_layer(
1165
+ hidden_states,
1166
+ attention_mask=attention_mask,
1167
+ position_ids=position_ids,
1168
+ past_key_value=past_key_values,
1169
+ output_attentions=output_attentions,
1170
+ use_cache=use_cache,
1171
+ )
1172
+
1173
+ hidden_states = layer_outputs[0]
1174
+
1175
+ if use_cache:
1176
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1177
+
1178
+ if output_attentions:
1179
+ all_self_attns += (layer_outputs[1],)
1180
+
1181
+ hidden_states = self.norm(hidden_states)
1182
+
1183
+ # add hidden states from the last decoder layer
1184
+ if output_hidden_states:
1185
+ all_hidden_states += (hidden_states,)
1186
+
1187
+ next_cache = None
1188
+ if use_cache:
1189
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1190
+ if not return_dict:
1191
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1192
+ return BaseModelOutputWithPast(
1193
+ last_hidden_state=hidden_states,
1194
+ past_key_values=next_cache,
1195
+ hidden_states=all_hidden_states,
1196
+ attentions=all_self_attns,
1197
+ )
1198
+
1199
+
1200
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1201
+ _tied_weights_keys = ["lm_head.weight"]
1202
+
1203
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1204
+ def __init__(self, config):
1205
+ super().__init__(config)
1206
+ self.model = Phi3Model(config)
1207
+ self.vocab_size = config.vocab_size
1208
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1209
+
1210
+ # Initialize weights and apply final processing
1211
+ self.post_init()
1212
+
1213
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1214
+ def get_input_embeddings(self):
1215
+ return self.model.embed_tokens
1216
+
1217
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1218
+ def set_input_embeddings(self, value):
1219
+ self.model.embed_tokens = value
1220
+
1221
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1222
+ def get_output_embeddings(self):
1223
+ return self.lm_head
1224
+
1225
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1226
+ def set_output_embeddings(self, new_embeddings):
1227
+ self.lm_head = new_embeddings
1228
+
1229
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1230
+ def set_decoder(self, decoder):
1231
+ self.model = decoder
1232
+
1233
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1234
+ def get_decoder(self):
1235
+ return self.model
1236
+
1237
+ # Ignore copy
1238
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1239
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1240
+ def forward(
1241
+ self,
1242
+ input_ids: torch.LongTensor = None,
1243
+ attention_mask: Optional[torch.Tensor] = None,
1244
+ position_ids: Optional[torch.LongTensor] = None,
1245
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1246
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1247
+ labels: Optional[torch.LongTensor] = None,
1248
+ use_cache: Optional[bool] = None,
1249
+ output_attentions: Optional[bool] = None,
1250
+ output_hidden_states: Optional[bool] = None,
1251
+ return_dict: Optional[bool] = None,
1252
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1253
+ r"""
1254
+ Args:
1255
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1256
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1257
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1258
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1259
+ Returns:
1260
+ Example:
1261
+ ```python
1262
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1263
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1264
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1265
+ >>> prompt = "This is an example script ."
1266
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1267
+ >>> # Generate
1268
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1269
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1270
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1271
+ ```"""
1272
+
1273
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1274
+ output_hidden_states = (
1275
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1276
+ )
1277
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1278
+
1279
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1280
+ outputs = self.model(
1281
+ input_ids=input_ids,
1282
+ attention_mask=attention_mask,
1283
+ position_ids=position_ids,
1284
+ past_key_values=past_key_values,
1285
+ inputs_embeds=inputs_embeds,
1286
+ use_cache=use_cache,
1287
+ output_attentions=output_attentions,
1288
+ output_hidden_states=output_hidden_states,
1289
+ return_dict=return_dict,
1290
+ )
1291
+
1292
+ hidden_states = outputs[0]
1293
+ logits = self.lm_head(hidden_states)
1294
+ logits = logits.float()
1295
+
1296
+ loss = None
1297
+ if labels is not None:
1298
+ # Shift so that tokens < n predict n
1299
+ shift_logits = logits[..., :-1, :].contiguous()
1300
+ shift_labels = labels[..., 1:].contiguous()
1301
+ # Flatten the tokens
1302
+ loss_fct = CrossEntropyLoss()
1303
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1304
+ shift_labels = shift_labels.view(-1)
1305
+ # Enable model parallelism
1306
+ shift_labels = shift_labels.to(shift_logits.device)
1307
+ loss = loss_fct(shift_logits, shift_labels)
1308
+
1309
+ if not return_dict:
1310
+ output = (logits,) + outputs[1:]
1311
+ return (loss,) + output if loss is not None else output
1312
+
1313
+ return CausalLMOutputWithPast(
1314
+ loss=loss,
1315
+ logits=logits,
1316
+ past_key_values=outputs.past_key_values,
1317
+ hidden_states=outputs.hidden_states,
1318
+ attentions=outputs.attentions,
1319
+ )
1320
+
1321
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1322
+ def prepare_inputs_for_generation(
1323
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1324
+ ):
1325
+ if past_key_values is not None:
1326
+ if isinstance(past_key_values, Cache):
1327
+ cache_length = past_key_values.get_seq_length()
1328
+ past_length = past_key_values.seen_tokens
1329
+ max_cache_length = past_key_values.get_max_length()
1330
+ else:
1331
+ cache_length = past_length = past_key_values[0][0].shape[2]
1332
+ max_cache_length = None
1333
+
1334
+ # Keep only the unprocessed tokens:
1335
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1336
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1337
+ # input)
1338
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1339
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1340
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1341
+ # input_ids based on the past_length.
1342
+ elif past_length < input_ids.shape[1]:
1343
+ input_ids = input_ids[:, past_length:]
1344
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1345
+
1346
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1347
+ if (
1348
+ max_cache_length is not None
1349
+ and attention_mask is not None
1350
+ and cache_length + input_ids.shape[1] > max_cache_length
1351
+ ):
1352
+ attention_mask = attention_mask[:, -max_cache_length:]
1353
+
1354
+ position_ids = kwargs.get("position_ids", None)
1355
+ if attention_mask is not None and position_ids is None:
1356
+ # create position_ids on the fly for batch generation
1357
+ position_ids = attention_mask.long().cumsum(-1) - 1
1358
+ position_ids.masked_fill_(attention_mask == 0, 1)
1359
+ if past_key_values:
1360
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1361
+
1362
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1363
+ if inputs_embeds is not None and past_key_values is None:
1364
+ model_inputs = {"inputs_embeds": inputs_embeds}
1365
+ else:
1366
+ model_inputs = {"input_ids": input_ids}
1367
+
1368
+ model_inputs.update(
1369
+ {
1370
+ "position_ids": position_ids,
1371
+ "past_key_values": past_key_values,
1372
+ "use_cache": kwargs.get("use_cache"),
1373
+ "attention_mask": attention_mask,
1374
+ }
1375
+ )
1376
+ return model_inputs
1377
+
1378
+ @staticmethod
1379
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1380
+ def _reorder_cache(past_key_values, beam_idx):
1381
+ reordered_past = ()
1382
+ for layer_past in past_key_values:
1383
+ reordered_past += (
1384
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1385
+ )
1386
+ return reordered_past
1387
+
1388
+
1389
+ @add_start_docstrings(
1390
+ """
1391
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1392
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1393
+ (e.g. GPT-2) do.
1394
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1395
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1396
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1397
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1398
+ each row of the batch).
1399
+ """,
1400
+ PHI3_START_DOCSTRING,
1401
+ )
1402
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1403
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1404
+ def __init__(self, config):
1405
+ super().__init__(config)
1406
+ self.num_labels = config.num_labels
1407
+ self.model = Phi3Model(config)
1408
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1409
+
1410
+ # Initialize weights and apply final processing
1411
+ self.post_init()
1412
+
1413
+ def get_input_embeddings(self):
1414
+ return self.model.embed_tokens
1415
+
1416
+ def set_input_embeddings(self, value):
1417
+ self.model.embed_tokens = value
1418
+
1419
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1420
+ def forward(
1421
+ self,
1422
+ input_ids: torch.LongTensor = None,
1423
+ attention_mask: Optional[torch.Tensor] = None,
1424
+ position_ids: Optional[torch.LongTensor] = None,
1425
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1426
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1427
+ labels: Optional[torch.LongTensor] = None,
1428
+ use_cache: Optional[bool] = None,
1429
+ output_attentions: Optional[bool] = None,
1430
+ output_hidden_states: Optional[bool] = None,
1431
+ return_dict: Optional[bool] = None,
1432
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1433
+ r"""
1434
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1435
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1436
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1437
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1438
+ """
1439
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1440
+
1441
+ model_outputs = self.model(
1442
+ input_ids,
1443
+ attention_mask=attention_mask,
1444
+ position_ids=position_ids,
1445
+ past_key_values=past_key_values,
1446
+ inputs_embeds=inputs_embeds,
1447
+ use_cache=use_cache,
1448
+ output_attentions=output_attentions,
1449
+ output_hidden_states=output_hidden_states,
1450
+ return_dict=return_dict,
1451
+ )
1452
+ hidden_states = model_outputs[0]
1453
+ logits = self.score(hidden_states)
1454
+
1455
+ if input_ids is not None:
1456
+ batch_size = input_ids.shape[0]
1457
+ else:
1458
+ batch_size = inputs_embeds.shape[0]
1459
+
1460
+ if self.config.pad_token_id is None and batch_size != 1:
1461
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1462
+ if self.config.pad_token_id is None:
1463
+ sequence_lengths = -1
1464
+ else:
1465
+ if input_ids is not None:
1466
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1467
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1468
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1469
+ sequence_lengths = sequence_lengths.to(logits.device)
1470
+ else:
1471
+ sequence_lengths = -1
1472
+
1473
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1474
+
1475
+ loss = None
1476
+ if labels is not None:
1477
+ labels = labels.to(logits.device)
1478
+ if self.config.problem_type is None:
1479
+ if self.num_labels == 1:
1480
+ self.config.problem_type = "regression"
1481
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1482
+ self.config.problem_type = "single_label_classification"
1483
+ else:
1484
+ self.config.problem_type = "multi_label_classification"
1485
+
1486
+ if self.config.problem_type == "regression":
1487
+ loss_fct = MSELoss()
1488
+ if self.num_labels == 1:
1489
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1490
+ else:
1491
+ loss = loss_fct(pooled_logits, labels)
1492
+ elif self.config.problem_type == "single_label_classification":
1493
+ loss_fct = CrossEntropyLoss()
1494
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1495
+ elif self.config.problem_type == "multi_label_classification":
1496
+ loss_fct = BCEWithLogitsLoss()
1497
+ loss = loss_fct(pooled_logits, labels)
1498
+ if not return_dict:
1499
+ output = (pooled_logits,) + model_outputs[1:]
1500
+ return ((loss,) + output) if loss is not None else output
1501
+
1502
+ return SequenceClassifierOutputWithPast(
1503
+ loss=loss,
1504
+ logits=pooled_logits,
1505
+ past_key_values=model_outputs.past_key_values,
1506
+ hidden_states=model_outputs.hidden_states,
1507
+ attentions=model_outputs.attentions,
1508
+ )
1509
+
1510
+
1511
+ @add_start_docstrings(
1512
+ """
1513
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1514
+ Named-Entity-Recognition (NER) tasks.
1515
+ """,
1516
+ PHI3_START_DOCSTRING,
1517
+ )
1518
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1519
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1520
+ def __init__(self, config: Phi3Config):
1521
+ super().__init__(config)
1522
+ self.num_labels = config.num_labels
1523
+
1524
+ self.model = Phi3Model(config)
1525
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1526
+ classifier_dropout = config.classifier_dropout
1527
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1528
+ classifier_dropout = config.hidden_dropout
1529
+ else:
1530
+ classifier_dropout = 0.1
1531
+ self.dropout = nn.Dropout(classifier_dropout)
1532
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1533
+
1534
+ # Initialize weights and apply final processing
1535
+ self.post_init()
1536
+
1537
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1538
+ @add_code_sample_docstrings(
1539
+ checkpoint=_CHECKPOINT_FOR_DOC,
1540
+ output_type=TokenClassifierOutput,
1541
+ config_class=_CONFIG_FOR_DOC,
1542
+ )
1543
+ def forward(
1544
+ self,
1545
+ input_ids: Optional[torch.LongTensor] = None,
1546
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1547
+ attention_mask: Optional[torch.Tensor] = None,
1548
+ inputs_embeds: Optional[torch.Tensor] = None,
1549
+ labels: Optional[torch.Tensor] = None,
1550
+ use_cache: Optional[bool] = None,
1551
+ output_attentions: Optional[bool] = None,
1552
+ output_hidden_states: Optional[bool] = None,
1553
+ return_dict: Optional[bool] = None,
1554
+ **deprecated_arguments,
1555
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1556
+ r"""
1557
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1558
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1559
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1560
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1561
+ """
1562
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1563
+
1564
+ model_outputs = self.model(
1565
+ input_ids,
1566
+ past_key_values=past_key_values,
1567
+ attention_mask=attention_mask,
1568
+ inputs_embeds=inputs_embeds,
1569
+ use_cache=use_cache,
1570
+ output_attentions=output_attentions,
1571
+ output_hidden_states=output_hidden_states,
1572
+ return_dict=return_dict,
1573
+ )
1574
+
1575
+ hidden_states = model_outputs[0]
1576
+ hidden_states = self.dropout(hidden_states)
1577
+ logits = self.classifier(hidden_states)
1578
+
1579
+ loss = None
1580
+ if labels is not None:
1581
+ # move labels to correct device to enable model parallelism
1582
+ labels = labels.to(logits.device)
1583
+ batch_size, seq_length = labels.shape
1584
+ loss_fct = CrossEntropyLoss()
1585
+ loss = loss_fct(
1586
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1587
+ )
1588
+
1589
+ if not return_dict:
1590
+ output = (logits,) + model_outputs[2:]
1591
+ return ((loss,) + output) if loss is not None else output
1592
+
1593
+ return TokenClassifierOutput(
1594
+ loss=loss,
1595
+ logits=logits,
1596
+ hidden_states=model_outputs.hidden_states,
1597
+ attentions=model_outputs.attentions,
1598
+ )
modeling_phi3.py.amltmp ADDED
@@ -0,0 +1,1603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi-3 model."""
17
+
18
+ import inspect
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_phi3 import Phi3Config
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
54
+ # if is_flash_attn_2_available():
55
+ _flash_supports_window_size = False
56
+ try:
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
61
+ except ImportError as error:
62
+ logger.warning(
63
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
64
+ )
65
+ if not _flash_supports_window_size:
66
+ logger.warning(
67
+ "Current `flash-attenton` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
68
+ )
69
+
70
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
71
+ _CONFIG_FOR_DOC = "Phi3Config"
72
+
73
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
74
+ "microsoft/Phi-3-mini-4k-instruct",
75
+ "microsoft/Phi-3-mini-128k-instruct",
76
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
77
+ ]
78
+
79
+
80
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
81
+ class Phi3RMSNorm(nn.Module):
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ """
84
+ Phi3RMSNorm is equivalent to T5LayerNorm
85
+ """
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+ self.variance_epsilon = eps
89
+
90
+ def forward(self, hidden_states):
91
+ input_dtype = hidden_states.dtype
92
+ hidden_states = hidden_states.to(torch.float32)
93
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
94
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
95
+ return self.weight * hidden_states.to(input_dtype)
96
+
97
+
98
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
99
+ def _get_unpad_data(attention_mask):
100
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
101
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
102
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
103
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
104
+ return (
105
+ indices,
106
+ cu_seqlens,
107
+ max_seqlen_in_batch,
108
+ )
109
+
110
+
111
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
112
+ class Phi3RotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ self.register_buffer("inv_freq", None, persistent=False)
120
+
121
+ @torch.no_grad()
122
+ def forward(self, x, position_ids, seq_len=None):
123
+ # x: [bs, num_attention_heads, seq_len, head_size]
124
+ if self.inv_freq is None:
125
+ self.inv_freq = 1.0 / (
126
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
127
+ )
128
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
129
+ position_ids_expanded = position_ids[:, None, :].float()
130
+ # Force float32 since bfloat16 loses precision on long contexts
131
+ # See https://github.com/huggingface/transformers/pull/29285
132
+ device_type = x.device.type
133
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
134
+ with torch.autocast(device_type=device_type, enabled=False):
135
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ cos = emb.cos()
138
+ sin = emb.sin()
139
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
140
+
141
+
142
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
143
+ def __init__(self, dim, config, device=None):
144
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
145
+
146
+ self.short_factor = config.rope_scaling["short_factor"]
147
+ self.long_factor = config.rope_scaling["long_factor"]
148
+ self.original_max_position_embeddings = config.original_max_position_embeddings
149
+
150
+ @torch.no_grad()
151
+ def forward(self, x, position_ids, seq_len=None):
152
+ seq_len = torch.max(position_ids) + 1
153
+ if seq_len > self.original_max_position_embeddings:
154
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
155
+ else:
156
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
157
+
158
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
159
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
160
+
161
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
162
+ position_ids_expanded = position_ids[:, None, :].float()
163
+
164
+ # Force float32 since bfloat16 loses precision on long contexts
165
+ # See https://github.com/huggingface/transformers/pull/29285
166
+ device_type = x.device.type
167
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
168
+ with torch.autocast(device_type=device_type, enabled=False):
169
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
170
+ emb = torch.cat((freqs, freqs), dim=-1)
171
+
172
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
173
+ if scale <= 1.0:
174
+ scaling_factor = 1.0
175
+ else:
176
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
177
+
178
+ cos = emb.cos() * scaling_factor
179
+ sin = emb.sin() * scaling_factor
180
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
181
+
182
+
183
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
184
+ def __init__(self, dim, config, device=None):
185
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
186
+
187
+ self.short_factor = config.rope_scaling["short_factor"]
188
+ self.long_factor = config.rope_scaling["long_factor"]
189
+ self.original_max_position_embeddings = config.original_max_position_embeddings
190
+
191
+ @torch.no_grad()
192
+ def forward(self, x, position_ids, seq_len=None):
193
+ seq_len = torch.max(position_ids) + 1
194
+ if seq_len > self.original_max_position_embeddings:
195
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
196
+ else:
197
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
198
+
199
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
200
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
201
+
202
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
203
+ position_ids_expanded = position_ids[:, None, :].float()
204
+
205
+ # Force float32 since bfloat16 loses precision on long contexts
206
+ # See https://github.com/huggingface/transformers/pull/29285
207
+ device_type = x.device.type
208
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
209
+ with torch.autocast(device_type=device_type, enabled=False):
210
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
211
+ emb = torch.cat((freqs, freqs), dim=-1)
212
+
213
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
214
+ if scale <= 1.0:
215
+ scaling_factor = 1.0
216
+ else:
217
+ scaling_factor = 0.1 * math.log(scale) + 1.0
218
+
219
+ cos = emb.cos() * scaling_factor
220
+ sin = emb.sin() * scaling_factor
221
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
222
+
223
+
224
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
225
+ def rotate_half(x):
226
+ """Rotates half the hidden dims of the input."""
227
+ x1 = x[..., : x.shape[-1] // 2]
228
+ x2 = x[..., x.shape[-1] // 2 :]
229
+ return torch.cat((-x2, x1), dim=-1)
230
+
231
+
232
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
233
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
234
+ """Applies Rotary Position Embedding to the query and key tensors.
235
+ Args:
236
+ q (`torch.Tensor`): The query tensor.
237
+ k (`torch.Tensor`): The key tensor.
238
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
239
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
240
+ position_ids (`torch.Tensor`, *optional*):
241
+ Deprecated and unused.
242
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
243
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
244
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
245
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
246
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
247
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
248
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
249
+ Returns:
250
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
251
+ """
252
+ cos = cos.unsqueeze(unsqueeze_dim)
253
+ sin = sin.unsqueeze(unsqueeze_dim)
254
+ q_embed = (q * cos) + (rotate_half(q) * sin)
255
+ k_embed = (k * cos) + (rotate_half(k) * sin)
256
+ return q_embed, k_embed
257
+
258
+
259
+ class Phi3MLP(nn.Module):
260
+ def __init__(self, config):
261
+ super().__init__()
262
+ self.gate = nn.Linear(config.hidden_size, 2, bias=False)
263
+ self.config = config
264
+ self.gate_up_proj = nn.ModuleList([nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False) for i in range(2)])
265
+ self.down_proj = nn.ModuleList([nn.Linear(config.intermediate_size, config.hidden_size, bias=False) for i in range(2)])
266
+ self.activation_fn = ACT2FN[config.hidden_act]
267
+
268
+ # def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
269
+
270
+ # orig_shape = hidden_states.shape
271
+ # hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
272
+
273
+ # experts_score = self.gate(hidden_states)
274
+ # expert_weights, expert_indices = torch.topk(experts_score, 1, dim=-1)
275
+ # expert_weights = expert_weights.softmax(dim=-1)
276
+
277
+ # flat_expert_indices = expert_indices.view(-1)
278
+
279
+ # y = torch.empty_like(hidden_states)
280
+
281
+ # for i, _ in enumerate(self.gate_up_proj):
282
+ # current_mask = flat_expert_indices == i
283
+
284
+ # up_states = self.gate_up_proj[i](hidden_states[current_mask])
285
+ # gate, up_states = up_states.chunk(2, dim=-1)
286
+ # up_states = up_states * self.activation_fn(gate)
287
+ # out = self.down_proj[i](up_states)
288
+
289
+ # y[current_mask] = out
290
+
291
+ # y = y.view(*expert_weights.shape, -1)
292
+ # return y.view(*orig_shape)
293
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
294
+ up_states = self.gate_up_proj[0](hidden_states)
295
+
296
+ gate, up_states = up_states.chunk(2, dim=-1)
297
+ up_states = up_states * self.activation_fn(gate)
298
+
299
+ return self.down_proj[0](up_states)
300
+
301
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
302
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
303
+ """
304
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
305
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
306
+ """
307
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
308
+ if n_rep == 1:
309
+ return hidden_states
310
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
311
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
312
+
313
+
314
+ class Phi3Attention(nn.Module):
315
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
316
+
317
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
318
+ super().__init__()
319
+ self.config = config
320
+ self.layer_idx = layer_idx
321
+ if layer_idx is None:
322
+ logger.warning_once(
323
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
324
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
325
+ "when creating this class."
326
+ )
327
+
328
+ self.attention_dropout = config.attention_dropout
329
+ self.hidden_size = config.hidden_size
330
+ self.num_heads = config.num_attention_heads
331
+ self.head_dim = self.hidden_size // self.num_heads
332
+ self.num_key_value_heads = config.num_key_value_heads
333
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
334
+ self.max_position_embeddings = config.max_position_embeddings
335
+ self.original_max_position_embeddings = config.original_max_position_embeddings
336
+ self.rope_theta = config.rope_theta
337
+ self.rope_scaling = config.rope_scaling
338
+ self.is_causal = True
339
+
340
+ if (self.head_dim * self.num_heads) != self.hidden_size:
341
+ raise ValueError(
342
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
343
+ f" and `num_heads`: {self.num_heads})."
344
+ )
345
+
346
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
347
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
348
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
349
+ self._init_rope()
350
+
351
+ def _init_rope(self):
352
+ if self.rope_scaling is None:
353
+ self.rotary_emb = Phi3RotaryEmbedding(
354
+ self.head_dim,
355
+ max_position_embeddings=self.max_position_embeddings,
356
+ base=self.rope_theta,
357
+ )
358
+ else:
359
+ scaling_type = self.config.rope_scaling["type"]
360
+ if scaling_type == "su":
361
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
362
+ elif scaling_type == "yarn":
363
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
364
+ else:
365
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
366
+
367
+ def forward(
368
+ self,
369
+ hidden_states: torch.Tensor,
370
+ attention_mask: Optional[torch.Tensor] = None,
371
+ position_ids: Optional[torch.LongTensor] = None,
372
+ past_key_value: Optional[Cache] = None,
373
+ output_attentions: bool = False,
374
+ use_cache: bool = False,
375
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
376
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
377
+
378
+ bsz, q_len, _ = hidden_states.size()
379
+
380
+ qkv = self.qkv_proj(hidden_states)
381
+ query_pos = self.num_heads * self.head_dim
382
+ query_states = qkv[..., :query_pos]
383
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
384
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
385
+
386
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
387
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
388
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
389
+
390
+ kv_seq_len = key_states.shape[-2]
391
+ if past_key_value is not None:
392
+ if self.layer_idx is None:
393
+ raise ValueError(
394
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
395
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
396
+ "with a layer index."
397
+ )
398
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
399
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
400
+
401
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
402
+
403
+ if past_key_value is not None:
404
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
405
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
406
+
407
+ # repeat k/v heads if n_kv_heads < n_heads
408
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
409
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
410
+
411
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
412
+
413
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
414
+ raise ValueError(
415
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
416
+ f" {attn_weights.size()}"
417
+ )
418
+
419
+ if attention_mask is not None:
420
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
421
+ raise ValueError(
422
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
423
+ )
424
+ attn_weights = attn_weights + attention_mask
425
+
426
+ # upcast attention to fp32
427
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
428
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
429
+
430
+ attn_output = torch.matmul(attn_weights, value_states)
431
+
432
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
433
+ raise ValueError(
434
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
435
+ f" {attn_output.size()}"
436
+ )
437
+
438
+ attn_output = attn_output.transpose(1, 2).contiguous()
439
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
440
+
441
+ attn_output = self.o_proj(attn_output)
442
+
443
+ if not output_attentions:
444
+ attn_weights = None
445
+
446
+ return attn_output, attn_weights, past_key_value
447
+
448
+
449
+ class Phi3FlashAttention2(Phi3Attention):
450
+ """
451
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
452
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
453
+ flash attention and deal with padding tokens in case the input contains any of them.
454
+ """
455
+
456
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
457
+ def __init__(self, *args, **kwargs):
458
+ super().__init__(*args, **kwargs)
459
+
460
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
461
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
462
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
463
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
464
+
465
+ def forward(
466
+ self,
467
+ hidden_states: torch.Tensor,
468
+ attention_mask: Optional[torch.LongTensor] = None,
469
+ position_ids: Optional[torch.LongTensor] = None,
470
+ past_key_value: Optional[Cache] = None,
471
+ output_attentions: bool = False,
472
+ use_cache: bool = False,
473
+ **kwargs,
474
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
475
+ # Phi3FlashAttention2 attention does not support output_attentions
476
+
477
+ if not _flash_supports_window_size:
478
+ logger.warning_once(
479
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
480
+ )
481
+ raise ValueError("The current flash attention version does not support sliding window attention.")
482
+
483
+ output_attentions = False
484
+
485
+ if "padding_mask" in kwargs:
486
+ warnings.warn(
487
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
488
+ )
489
+
490
+ # overwrite attention_mask with padding_mask
491
+ attention_mask = kwargs.pop("padding_mask")
492
+
493
+ bsz, q_len, _ = hidden_states.size()
494
+
495
+ qkv = self.qkv_proj(hidden_states)
496
+ query_pos = self.num_heads * self.head_dim
497
+ query_states = qkv[..., :query_pos]
498
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
499
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
500
+
501
+ # Flash attention requires the input to have the shape
502
+ # batch_size x seq_length x head_dim x hidden_dim
503
+ # therefore we just need to keep the original shape
504
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
505
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
506
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
507
+
508
+ kv_seq_len = key_states.shape[-2]
509
+ if past_key_value is not None:
510
+ if self.layer_idx is None:
511
+ raise ValueError(
512
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
513
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
514
+ "with a layer index."
515
+ )
516
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
517
+
518
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
519
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
520
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
521
+
522
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
523
+
524
+ use_sliding_windows = (
525
+ _flash_supports_window_size
526
+ and getattr(self.config, "sliding_window", None) is not None
527
+ and kv_seq_len > self.config.sliding_window
528
+ )
529
+
530
+ if past_key_value is not None:
531
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
532
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
533
+ if (
534
+ getattr(self.config, "sliding_window", None) is not None
535
+ and kv_seq_len > self.config.sliding_window
536
+ and cache_has_contents
537
+ ):
538
+ slicing_tokens = 1 - self.config.sliding_window
539
+
540
+ past_key = past_key_value[self.layer_idx][0]
541
+ past_value = past_key_value[self.layer_idx][1]
542
+
543
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
544
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
545
+
546
+ if past_key.shape[-2] != self.config.sliding_window - 1:
547
+ raise ValueError(
548
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
549
+ f" {past_key.shape}"
550
+ )
551
+
552
+ if attention_mask is not None:
553
+ attention_mask = attention_mask[:, slicing_tokens:]
554
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
555
+
556
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
557
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
558
+
559
+ # repeat k/v heads if n_kv_heads < n_heads
560
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
561
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
562
+
563
+ attn_dropout = self.attention_dropout if self.training else 0.0
564
+
565
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
566
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
567
+ # cast them back in the correct dtype just to be sure everything works as expected.
568
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
569
+ # in fp32.
570
+
571
+ if query_states.dtype == torch.float32:
572
+ if torch.is_autocast_enabled():
573
+ target_dtype = torch.get_autocast_gpu_dtype()
574
+ # Handle the case where the model is quantized
575
+ elif hasattr(self.config, "_pre_quantization_dtype"):
576
+ target_dtype = self.config._pre_quantization_dtype
577
+ else:
578
+ target_dtype = self.qkv_proj.weight.dtype
579
+
580
+ logger.warning_once(
581
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
582
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
583
+ f" {target_dtype}."
584
+ )
585
+
586
+ query_states = query_states.to(target_dtype)
587
+ key_states = key_states.to(target_dtype)
588
+ value_states = value_states.to(target_dtype)
589
+
590
+ # Reashape to the expected shape for Flash Attention
591
+ query_states = query_states.transpose(1, 2)
592
+ key_states = key_states.transpose(1, 2)
593
+ value_states = value_states.transpose(1, 2)
594
+
595
+ attn_output = self._flash_attention_forward(
596
+ query_states,
597
+ key_states,
598
+ value_states,
599
+ attention_mask,
600
+ q_len,
601
+ dropout=attn_dropout,
602
+ use_sliding_windows=use_sliding_windows,
603
+ )
604
+
605
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
606
+ attn_output = self.o_proj(attn_output)
607
+
608
+ if not output_attentions:
609
+ attn_weights = None
610
+
611
+ return attn_output, attn_weights, past_key_value
612
+
613
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
614
+ def _flash_attention_forward(
615
+ self,
616
+ query_states,
617
+ key_states,
618
+ value_states,
619
+ attention_mask,
620
+ query_length,
621
+ dropout=0.0,
622
+ softmax_scale=None,
623
+ use_sliding_windows=False,
624
+ ):
625
+ """
626
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
627
+ first unpad the input, then computes the attention scores and pad the final attention scores.
628
+ Args:
629
+ query_states (`torch.Tensor`):
630
+ Input query states to be passed to Flash Attention API
631
+ key_states (`torch.Tensor`):
632
+ Input key states to be passed to Flash Attention API
633
+ value_states (`torch.Tensor`):
634
+ Input value states to be passed to Flash Attention API
635
+ attention_mask (`torch.Tensor`):
636
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
637
+ position of padding tokens and 1 for the position of non-padding tokens.
638
+ dropout (`float`):
639
+ Attention dropout
640
+ softmax_scale (`float`, *optional*):
641
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
642
+ use_sliding_windows (`bool`, *optional*):
643
+ Whether to activate sliding window attention.
644
+ """
645
+ if not self._flash_attn_uses_top_left_mask:
646
+ causal = self.is_causal
647
+ else:
648
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
649
+ causal = self.is_causal and query_length != 1
650
+
651
+ # Contains at least one padding token in the sequence
652
+ if attention_mask is not None:
653
+ batch_size = query_states.shape[0]
654
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
655
+ query_states, key_states, value_states, attention_mask, query_length
656
+ )
657
+
658
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
659
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
660
+
661
+ if not use_sliding_windows:
662
+ attn_output_unpad = flash_attn_varlen_func(
663
+ query_states,
664
+ key_states,
665
+ value_states,
666
+ cu_seqlens_q=cu_seqlens_q,
667
+ cu_seqlens_k=cu_seqlens_k,
668
+ max_seqlen_q=max_seqlen_in_batch_q,
669
+ max_seqlen_k=max_seqlen_in_batch_k,
670
+ dropout_p=dropout,
671
+ softmax_scale=softmax_scale,
672
+ causal=causal,
673
+ )
674
+ else:
675
+ attn_output_unpad = flash_attn_varlen_func(
676
+ query_states,
677
+ key_states,
678
+ value_states,
679
+ cu_seqlens_q=cu_seqlens_q,
680
+ cu_seqlens_k=cu_seqlens_k,
681
+ max_seqlen_q=max_seqlen_in_batch_q,
682
+ max_seqlen_k=max_seqlen_in_batch_k,
683
+ dropout_p=dropout,
684
+ softmax_scale=softmax_scale,
685
+ causal=causal,
686
+ window_size=(self.config.sliding_window, self.config.sliding_window),
687
+ )
688
+
689
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
690
+ else:
691
+ if not use_sliding_windows:
692
+ attn_output = flash_attn_func(
693
+ query_states,
694
+ key_states,
695
+ value_states,
696
+ dropout,
697
+ softmax_scale=softmax_scale,
698
+ causal=causal,
699
+ )
700
+ else:
701
+ attn_output = flash_attn_func(
702
+ query_states,
703
+ key_states,
704
+ value_states,
705
+ dropout,
706
+ softmax_scale=softmax_scale,
707
+ causal=causal,
708
+ window_size=(self.config.sliding_window, self.config.sliding_window),
709
+ )
710
+
711
+ return attn_output
712
+
713
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
714
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
715
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
716
+
717
+ # On the first iteration we need to properly re-create the padding mask
718
+ # by slicing it on the proper place
719
+ if kv_seq_len != attention_mask.shape[-1]:
720
+ attention_mask_num_tokens = attention_mask.shape[-1]
721
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
722
+
723
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
724
+
725
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
726
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
727
+
728
+ if query_length == kv_seq_len:
729
+ query_layer = index_first_axis(
730
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
731
+ )
732
+ cu_seqlens_q = cu_seqlens_k
733
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
734
+ indices_q = indices_k
735
+ elif query_length == 1:
736
+ max_seqlen_in_batch_q = 1
737
+ cu_seqlens_q = torch.arange(
738
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
739
+ ) # There is a memcpy here, that is very bad.
740
+ indices_q = cu_seqlens_q[:-1]
741
+ query_layer = query_layer.squeeze(1)
742
+ else:
743
+ # The -q_len: slice assumes left padding.
744
+ attention_mask = attention_mask[:, -query_length:]
745
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
746
+
747
+ return (
748
+ query_layer,
749
+ key_layer,
750
+ value_layer,
751
+ indices_q,
752
+ (cu_seqlens_q, cu_seqlens_k),
753
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
754
+ )
755
+
756
+
757
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
758
+ # TODO @Arthur no longer copied from LLama after static cache
759
+ class Phi3SdpaAttention(Phi3Attention):
760
+ """
761
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
762
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
763
+ SDPA API.
764
+ """
765
+
766
+ # Adapted from Phi3Attention.forward
767
+ def forward(
768
+ self,
769
+ hidden_states: torch.Tensor,
770
+ attention_mask: Optional[torch.Tensor] = None,
771
+ position_ids: Optional[torch.LongTensor] = None,
772
+ past_key_value: Optional[Cache] = None,
773
+ output_attentions: bool = False,
774
+ use_cache: bool = False,
775
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
776
+ if output_attentions:
777
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
778
+ logger.warning_once(
779
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
780
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
781
+ )
782
+ return super().forward(
783
+ hidden_states=hidden_states,
784
+ attention_mask=attention_mask,
785
+ position_ids=position_ids,
786
+ past_key_value=past_key_value,
787
+ output_attentions=output_attentions,
788
+ use_cache=use_cache,
789
+ )
790
+
791
+ bsz, q_len, _ = hidden_states.size()
792
+
793
+ qkv = self.qkv_proj(hidden_states)
794
+ query_pos = self.num_heads * self.head_dim
795
+ query_states = qkv[..., :query_pos]
796
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
797
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
798
+
799
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
800
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
801
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
802
+
803
+ kv_seq_len = key_states.shape[-2]
804
+ if past_key_value is not None:
805
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
806
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
807
+
808
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
809
+
810
+ if past_key_value is not None:
811
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
812
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
813
+
814
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
815
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
816
+
817
+ if attention_mask is not None:
818
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
819
+ raise ValueError(
820
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
821
+ )
822
+
823
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
824
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
825
+ if query_states.device.type == "cuda" and attention_mask is not None:
826
+ query_states = query_states.contiguous()
827
+ key_states = key_states.contiguous()
828
+ value_states = value_states.contiguous()
829
+
830
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
831
+ query_states,
832
+ key_states,
833
+ value_states,
834
+ attn_mask=attention_mask,
835
+ dropout_p=self.attention_dropout if self.training else 0.0,
836
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
837
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
838
+ )
839
+
840
+ attn_output = attn_output.transpose(1, 2).contiguous()
841
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
842
+
843
+ attn_output = self.o_proj(attn_output)
844
+
845
+ return attn_output, None, past_key_value
846
+
847
+
848
+ PHI3_ATTENTION_CLASSES = {
849
+ "eager": Phi3Attention,
850
+ "flash_attention_2": Phi3FlashAttention2,
851
+ "sdpa": Phi3SdpaAttention,
852
+ }
853
+
854
+
855
+ class Phi3DecoderLayer(nn.Module):
856
+ def __init__(self, config: Phi3Config, layer_idx: int):
857
+ super().__init__()
858
+
859
+ self.config = config
860
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
861
+
862
+ self.mlp = Phi3MLP(config)
863
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
864
+
865
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
866
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
867
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
868
+
869
+ def forward(
870
+ self,
871
+ hidden_states: torch.Tensor,
872
+ attention_mask: Optional[torch.Tensor] = None,
873
+ position_ids: Optional[torch.LongTensor] = None,
874
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
875
+ output_attentions: Optional[bool] = False,
876
+ use_cache: Optional[bool] = False,
877
+ **kwargs,
878
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
879
+ if "padding_mask" in kwargs:
880
+ warnings.warn(
881
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
882
+ )
883
+ """
884
+ Args:
885
+ hidden_states (`torch.FloatTensor`):
886
+ input to the layer of shape `(batch, seq_len, embed_dim)`
887
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
888
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
889
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
890
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
891
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
892
+ output_attentions (`bool`, *optional*):
893
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
894
+ returned tensors for more detail.
895
+ use_cache (`bool`, *optional*):
896
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
897
+ (see `past_key_values`).
898
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
899
+ """
900
+
901
+ residual = hidden_states
902
+
903
+ hidden_states = self.input_layernorm(hidden_states)
904
+
905
+ # Self Attention
906
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
907
+ hidden_states=hidden_states,
908
+ attention_mask=attention_mask,
909
+ position_ids=position_ids,
910
+ past_key_value=past_key_value,
911
+ output_attentions=output_attentions,
912
+ use_cache=use_cache,
913
+ )
914
+
915
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
916
+
917
+ residual = hidden_states
918
+ hidden_states = self.post_attention_layernorm(hidden_states)
919
+ hidden_states = self.mlp(hidden_states)
920
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
921
+
922
+ outputs = (hidden_states,)
923
+
924
+ if output_attentions:
925
+ outputs += (self_attn_weights,)
926
+
927
+ if use_cache:
928
+ outputs += (present_key_value,)
929
+
930
+ return outputs
931
+
932
+
933
+ PHI3_START_DOCSTRING = r"""
934
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
935
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
936
+ etc.)
937
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
938
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
939
+ and behavior.
940
+ Parameters:
941
+ config ([`Phi3Config`]):
942
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
943
+ load the weights associated with the model, only the configuration. Check out the
944
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
945
+ """
946
+
947
+
948
+ @add_start_docstrings(
949
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
950
+ PHI3_START_DOCSTRING,
951
+ )
952
+ class Phi3PreTrainedModel(PreTrainedModel):
953
+ config_class = Phi3Config
954
+ base_model_prefix = "model"
955
+ supports_gradient_checkpointing = True
956
+ _no_split_modules = ["Phi3DecoderLayer"]
957
+ _skip_keys_device_placement = "past_key_values"
958
+ _supports_flash_attn_2 = True
959
+ _supports_sdpa = False
960
+ _supports_cache_class = True
961
+
962
+ _version = "0.0.5"
963
+
964
+ def _init_weights(self, module):
965
+ std = self.config.initializer_range
966
+ if isinstance(module, nn.Linear):
967
+ module.weight.data.normal_(mean=0.0, std=std)
968
+ if module.bias is not None:
969
+ module.bias.data.zero_()
970
+ elif isinstance(module, nn.Embedding):
971
+ module.weight.data.normal_(mean=0.0, std=std)
972
+ if module.padding_idx is not None:
973
+ module.weight.data[module.padding_idx].zero_()
974
+
975
+
976
+ PHI3_INPUTS_DOCSTRING = r"""
977
+ Args:
978
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
979
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
980
+ it.
981
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
982
+ [`PreTrainedTokenizer.__call__`] for details.
983
+ [What are input IDs?](../glossary#input-ids)
984
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
985
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
986
+ - 1 for tokens that are **not masked**,
987
+ - 0 for tokens that are **masked**.
988
+ [What are attention masks?](../glossary#attention-mask)
989
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
990
+ [`PreTrainedTokenizer.__call__`] for details.
991
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
992
+ `past_key_values`).
993
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
994
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
995
+ information on the default strategy.
996
+ - 1 indicates the head is **not masked**,
997
+ - 0 indicates the head is **masked**.
998
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
999
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1000
+ config.n_positions - 1]`.
1001
+ [What are position IDs?](../glossary#position-ids)
1002
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1003
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1004
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1005
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1006
+ Two formats are allowed:
1007
+ - a [`~cache_utils.Cache`] instance;
1008
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1009
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1010
+ cache format.
1011
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1012
+ legacy cache format will be returned.
1013
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1014
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1015
+ of shape `(batch_size, sequence_length)`.
1016
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1017
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1018
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1019
+ model's internal embedding lookup matrix.
1020
+ use_cache (`bool`, *optional*):
1021
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1022
+ `past_key_values`).
1023
+ output_attentions (`bool`, *optional*):
1024
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1025
+ tensors for more detail.
1026
+ output_hidden_states (`bool`, *optional*):
1027
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1028
+ more detail.
1029
+ return_dict (`bool`, *optional*):
1030
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1031
+ """
1032
+
1033
+
1034
+ @add_start_docstrings(
1035
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
1036
+ PHI3_START_DOCSTRING,
1037
+ )
1038
+ class Phi3Model(Phi3PreTrainedModel):
1039
+ """
1040
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1041
+ Args:
1042
+ config: Phi3Config
1043
+ """
1044
+
1045
+ def __init__(self, config: Phi3Config):
1046
+ super().__init__(config)
1047
+ self.padding_idx = config.pad_token_id
1048
+ self.vocab_size = config.vocab_size
1049
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1050
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1051
+ self.layers = nn.ModuleList(
1052
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1053
+ )
1054
+ self._attn_implementation = config._attn_implementation
1055
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1056
+
1057
+ self.gradient_checkpointing = False
1058
+ # Initialize weights and apply final processing
1059
+ self.post_init()
1060
+
1061
+ def get_input_embeddings(self):
1062
+ return self.embed_tokens
1063
+
1064
+ def set_input_embeddings(self, value):
1065
+ self.embed_tokens = value
1066
+
1067
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1068
+ def forward(
1069
+ self,
1070
+ input_ids: torch.LongTensor = None,
1071
+ attention_mask: Optional[torch.Tensor] = None,
1072
+ position_ids: Optional[torch.LongTensor] = None,
1073
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1074
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1075
+ use_cache: Optional[bool] = None,
1076
+ output_attentions: Optional[bool] = None,
1077
+ output_hidden_states: Optional[bool] = None,
1078
+ return_dict: Optional[bool] = None,
1079
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1080
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1081
+ output_hidden_states = (
1082
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1083
+ )
1084
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1085
+
1086
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1087
+
1088
+ # retrieve input_ids and inputs_embeds
1089
+ if input_ids is not None and inputs_embeds is not None:
1090
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1091
+ elif input_ids is not None:
1092
+ batch_size, seq_length = input_ids.shape[:2]
1093
+ elif inputs_embeds is not None:
1094
+ batch_size, seq_length = inputs_embeds.shape[:2]
1095
+ else:
1096
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1097
+
1098
+ past_key_values_length = 0
1099
+
1100
+ if self.gradient_checkpointing and self.training:
1101
+ if use_cache:
1102
+ logger.warning_once(
1103
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1104
+ )
1105
+ use_cache = False
1106
+
1107
+ if use_cache:
1108
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1109
+ if use_legacy_cache:
1110
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1111
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1112
+
1113
+ if position_ids is None:
1114
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1115
+ position_ids = torch.arange(
1116
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1117
+ )
1118
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1119
+ else:
1120
+ position_ids = position_ids.view(-1, seq_length).long()
1121
+
1122
+ if inputs_embeds is None:
1123
+ inputs_embeds = self.embed_tokens(input_ids)
1124
+
1125
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1126
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1127
+ if is_padding_right:
1128
+ raise ValueError(
1129
+ "You are attempting to perform batched generation with padding_side='right'"
1130
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1131
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1132
+ )
1133
+
1134
+ if self._attn_implementation == "flash_attention_2":
1135
+ # 2d mask is passed through the layers
1136
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1137
+ else:
1138
+ # 4d mask is passed through the layers
1139
+ attention_mask = _prepare_4d_causal_attention_mask(
1140
+ attention_mask,
1141
+ (batch_size, seq_length),
1142
+ inputs_embeds,
1143
+ past_key_values_length,
1144
+ sliding_window=self.config.sliding_window,
1145
+ )
1146
+
1147
+ hidden_states = inputs_embeds
1148
+
1149
+ # decoder layers
1150
+ all_hidden_states = () if output_hidden_states else None
1151
+ all_self_attns = () if output_attentions else None
1152
+ next_decoder_cache = None
1153
+
1154
+ for decoder_layer in self.layers:
1155
+ if output_hidden_states:
1156
+ all_hidden_states += (hidden_states,)
1157
+
1158
+ if self.gradient_checkpointing and self.training:
1159
+ layer_outputs = self._gradient_checkpointing_func(
1160
+ decoder_layer.__call__,
1161
+ hidden_states,
1162
+ attention_mask,
1163
+ position_ids,
1164
+ past_key_values,
1165
+ output_attentions,
1166
+ use_cache,
1167
+ )
1168
+ else:
1169
+ layer_outputs = decoder_layer(
1170
+ hidden_states,
1171
+ attention_mask=attention_mask,
1172
+ position_ids=position_ids,
1173
+ past_key_value=past_key_values,
1174
+ output_attentions=output_attentions,
1175
+ use_cache=use_cache,
1176
+ )
1177
+
1178
+ hidden_states = layer_outputs[0]
1179
+
1180
+ if use_cache:
1181
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1182
+
1183
+ if output_attentions:
1184
+ all_self_attns += (layer_outputs[1],)
1185
+
1186
+ hidden_states = self.norm(hidden_states)
1187
+
1188
+ # add hidden states from the last decoder layer
1189
+ if output_hidden_states:
1190
+ all_hidden_states += (hidden_states,)
1191
+
1192
+ next_cache = None
1193
+ if use_cache:
1194
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1195
+ if not return_dict:
1196
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1197
+ return BaseModelOutputWithPast(
1198
+ last_hidden_state=hidden_states,
1199
+ past_key_values=next_cache,
1200
+ hidden_states=all_hidden_states,
1201
+ attentions=all_self_attns,
1202
+ )
1203
+
1204
+
1205
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1206
+ _tied_weights_keys = ["lm_head.weight"]
1207
+
1208
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1209
+ def __init__(self, config):
1210
+ super().__init__(config)
1211
+ self.model = Phi3Model(config)
1212
+ self.vocab_size = config.vocab_size
1213
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1214
+
1215
+ # Initialize weights and apply final processing
1216
+ self.post_init()
1217
+
1218
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1219
+ def get_input_embeddings(self):
1220
+ return self.model.embed_tokens
1221
+
1222
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1223
+ def set_input_embeddings(self, value):
1224
+ self.model.embed_tokens = value
1225
+
1226
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1227
+ def get_output_embeddings(self):
1228
+ return self.lm_head
1229
+
1230
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1231
+ def set_output_embeddings(self, new_embeddings):
1232
+ self.lm_head = new_embeddings
1233
+
1234
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1235
+ def set_decoder(self, decoder):
1236
+ self.model = decoder
1237
+
1238
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1239
+ def get_decoder(self):
1240
+ return self.model
1241
+
1242
+ # Ignore copy
1243
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1244
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1245
+ def forward(
1246
+ self,
1247
+ input_ids: torch.LongTensor = None,
1248
+ attention_mask: Optional[torch.Tensor] = None,
1249
+ position_ids: Optional[torch.LongTensor] = None,
1250
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1251
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1252
+ labels: Optional[torch.LongTensor] = None,
1253
+ use_cache: Optional[bool] = None,
1254
+ output_attentions: Optional[bool] = None,
1255
+ output_hidden_states: Optional[bool] = None,
1256
+ return_dict: Optional[bool] = None,
1257
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1258
+ r"""
1259
+ Args:
1260
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1261
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1262
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1263
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1264
+ Returns:
1265
+ Example:
1266
+ ```python
1267
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1268
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1269
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1270
+ >>> prompt = "This is an example script ."
1271
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1272
+ >>> # Generate
1273
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1274
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1275
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1276
+ ```"""
1277
+
1278
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1279
+ output_hidden_states = (
1280
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1281
+ )
1282
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1283
+
1284
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1285
+ outputs = self.model(
1286
+ input_ids=input_ids,
1287
+ attention_mask=attention_mask,
1288
+ position_ids=position_ids,
1289
+ past_key_values=past_key_values,
1290
+ inputs_embeds=inputs_embeds,
1291
+ use_cache=use_cache,
1292
+ output_attentions=output_attentions,
1293
+ output_hidden_states=output_hidden_states,
1294
+ return_dict=return_dict,
1295
+ )
1296
+
1297
+ hidden_states = outputs[0]
1298
+ logits = self.lm_head(hidden_states)
1299
+ logits = logits.float()
1300
+
1301
+ loss = None
1302
+ if labels is not None:
1303
+ # Shift so that tokens < n predict n
1304
+ shift_logits = logits[..., :-1, :].contiguous()
1305
+ shift_labels = labels[..., 1:].contiguous()
1306
+ # Flatten the tokens
1307
+ loss_fct = CrossEntropyLoss()
1308
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1309
+ shift_labels = shift_labels.view(-1)
1310
+ # Enable model parallelism
1311
+ shift_labels = shift_labels.to(shift_logits.device)
1312
+ loss = loss_fct(shift_logits, shift_labels)
1313
+
1314
+ if not return_dict:
1315
+ output = (logits,) + outputs[1:]
1316
+ return (loss,) + output if loss is not None else output
1317
+
1318
+ return CausalLMOutputWithPast(
1319
+ loss=loss,
1320
+ logits=logits,
1321
+ past_key_values=outputs.past_key_values,
1322
+ hidden_states=outputs.hidden_states,
1323
+ attentions=outputs.attentions,
1324
+ )
1325
+
1326
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1327
+ def prepare_inputs_for_generation(
1328
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1329
+ ):
1330
+ if past_key_values is not None:
1331
+ if isinstance(past_key_values, Cache):
1332
+ cache_length = past_key_values.get_seq_length()
1333
+ past_length = past_key_values.seen_tokens
1334
+ max_cache_length = past_key_values.get_max_length()
1335
+ else:
1336
+ cache_length = past_length = past_key_values[0][0].shape[2]
1337
+ max_cache_length = None
1338
+
1339
+ # Keep only the unprocessed tokens:
1340
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1341
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1342
+ # input)
1343
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1344
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1345
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1346
+ # input_ids based on the past_length.
1347
+ elif past_length < input_ids.shape[1]:
1348
+ input_ids = input_ids[:, past_length:]
1349
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1350
+
1351
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1352
+ if (
1353
+ max_cache_length is not None
1354
+ and attention_mask is not None
1355
+ and cache_length + input_ids.shape[1] > max_cache_length
1356
+ ):
1357
+ attention_mask = attention_mask[:, -max_cache_length:]
1358
+
1359
+ position_ids = kwargs.get("position_ids", None)
1360
+ if attention_mask is not None and position_ids is None:
1361
+ # create position_ids on the fly for batch generation
1362
+ position_ids = attention_mask.long().cumsum(-1) - 1
1363
+ position_ids.masked_fill_(attention_mask == 0, 1)
1364
+ if past_key_values:
1365
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1366
+
1367
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1368
+ if inputs_embeds is not None and past_key_values is None:
1369
+ model_inputs = {"inputs_embeds": inputs_embeds}
1370
+ else:
1371
+ model_inputs = {"input_ids": input_ids}
1372
+
1373
+ model_inputs.update(
1374
+ {
1375
+ "position_ids": position_ids,
1376
+ "past_key_values": past_key_values,
1377
+ "use_cache": kwargs.get("use_cache"),
1378
+ "attention_mask": attention_mask,
1379
+ }
1380
+ )
1381
+ return model_inputs
1382
+
1383
+ @staticmethod
1384
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1385
+ def _reorder_cache(past_key_values, beam_idx):
1386
+ reordered_past = ()
1387
+ for layer_past in past_key_values:
1388
+ reordered_past += (
1389
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1390
+ )
1391
+ return reordered_past
1392
+
1393
+
1394
+ @add_start_docstrings(
1395
+ """
1396
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1397
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1398
+ (e.g. GPT-2) do.
1399
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1400
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1401
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1402
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1403
+ each row of the batch).
1404
+ """,
1405
+ PHI3_START_DOCSTRING,
1406
+ )
1407
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1408
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1409
+ def __init__(self, config):
1410
+ super().__init__(config)
1411
+ self.num_labels = config.num_labels
1412
+ self.model = Phi3Model(config)
1413
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1414
+
1415
+ # Initialize weights and apply final processing
1416
+ self.post_init()
1417
+
1418
+ def get_input_embeddings(self):
1419
+ return self.model.embed_tokens
1420
+
1421
+ def set_input_embeddings(self, value):
1422
+ self.model.embed_tokens = value
1423
+
1424
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1425
+ def forward(
1426
+ self,
1427
+ input_ids: torch.LongTensor = None,
1428
+ attention_mask: Optional[torch.Tensor] = None,
1429
+ position_ids: Optional[torch.LongTensor] = None,
1430
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1431
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1432
+ labels: Optional[torch.LongTensor] = None,
1433
+ use_cache: Optional[bool] = None,
1434
+ output_attentions: Optional[bool] = None,
1435
+ output_hidden_states: Optional[bool] = None,
1436
+ return_dict: Optional[bool] = None,
1437
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1438
+ r"""
1439
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1440
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1441
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1442
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1443
+ """
1444
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1445
+
1446
+ model_outputs = self.model(
1447
+ input_ids,
1448
+ attention_mask=attention_mask,
1449
+ position_ids=position_ids,
1450
+ past_key_values=past_key_values,
1451
+ inputs_embeds=inputs_embeds,
1452
+ use_cache=use_cache,
1453
+ output_attentions=output_attentions,
1454
+ output_hidden_states=output_hidden_states,
1455
+ return_dict=return_dict,
1456
+ )
1457
+ hidden_states = model_outputs[0]
1458
+ logits = self.score(hidden_states)
1459
+
1460
+ if input_ids is not None:
1461
+ batch_size = input_ids.shape[0]
1462
+ else:
1463
+ batch_size = inputs_embeds.shape[0]
1464
+
1465
+ if self.config.pad_token_id is None and batch_size != 1:
1466
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1467
+ if self.config.pad_token_id is None:
1468
+ sequence_lengths = -1
1469
+ else:
1470
+ if input_ids is not None:
1471
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1472
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1473
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1474
+ sequence_lengths = sequence_lengths.to(logits.device)
1475
+ else:
1476
+ sequence_lengths = -1
1477
+
1478
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1479
+
1480
+ loss = None
1481
+ if labels is not None:
1482
+ labels = labels.to(logits.device)
1483
+ if self.config.problem_type is None:
1484
+ if self.num_labels == 1:
1485
+ self.config.problem_type = "regression"
1486
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1487
+ self.config.problem_type = "single_label_classification"
1488
+ else:
1489
+ self.config.problem_type = "multi_label_classification"
1490
+
1491
+ if self.config.problem_type == "regression":
1492
+ loss_fct = MSELoss()
1493
+ if self.num_labels == 1:
1494
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1495
+ else:
1496
+ loss = loss_fct(pooled_logits, labels)
1497
+ elif self.config.problem_type == "single_label_classification":
1498
+ loss_fct = CrossEntropyLoss()
1499
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1500
+ elif self.config.problem_type == "multi_label_classification":
1501
+ loss_fct = BCEWithLogitsLoss()
1502
+ loss = loss_fct(pooled_logits, labels)
1503
+ if not return_dict:
1504
+ output = (pooled_logits,) + model_outputs[1:]
1505
+ return ((loss,) + output) if loss is not None else output
1506
+
1507
+ return SequenceClassifierOutputWithPast(
1508
+ loss=loss,
1509
+ logits=pooled_logits,
1510
+ past_key_values=model_outputs.past_key_values,
1511
+ hidden_states=model_outputs.hidden_states,
1512
+ attentions=model_outputs.attentions,
1513
+ )
1514
+
1515
+
1516
+ @add_start_docstrings(
1517
+ """
1518
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1519
+ Named-Entity-Recognition (NER) tasks.
1520
+ """,
1521
+ PHI3_START_DOCSTRING,
1522
+ )
1523
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1524
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1525
+ def __init__(self, config: Phi3Config):
1526
+ super().__init__(config)
1527
+ self.num_labels = config.num_labels
1528
+
1529
+ self.model = Phi3Model(config)
1530
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1531
+ classifier_dropout = config.classifier_dropout
1532
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1533
+ classifier_dropout = config.hidden_dropout
1534
+ else:
1535
+ classifier_dropout = 0.1
1536
+ self.dropout = nn.Dropout(classifier_dropout)
1537
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1538
+
1539
+ # Initialize weights and apply final processing
1540
+ self.post_init()
1541
+
1542
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1543
+ @add_code_sample_docstrings(
1544
+ checkpoint=_CHECKPOINT_FOR_DOC,
1545
+ output_type=TokenClassifierOutput,
1546
+ config_class=_CONFIG_FOR_DOC,
1547
+ )
1548
+ def forward(
1549
+ self,
1550
+ input_ids: Optional[torch.LongTensor] = None,
1551
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1552
+ attention_mask: Optional[torch.Tensor] = None,
1553
+ inputs_embeds: Optional[torch.Tensor] = None,
1554
+ labels: Optional[torch.Tensor] = None,
1555
+ use_cache: Optional[bool] = None,
1556
+ output_attentions: Optional[bool] = None,
1557
+ output_hidden_states: Optional[bool] = None,
1558
+ return_dict: Optional[bool] = None,
1559
+ **deprecated_arguments,
1560
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1561
+ r"""
1562
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1563
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1564
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1565
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1566
+ """
1567
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1568
+
1569
+ model_outputs = self.model(
1570
+ input_ids,
1571
+ past_key_values=past_key_values,
1572
+ attention_mask=attention_mask,
1573
+ inputs_embeds=inputs_embeds,
1574
+ use_cache=use_cache,
1575
+ output_attentions=output_attentions,
1576
+ output_hidden_states=output_hidden_states,
1577
+ return_dict=return_dict,
1578
+ )
1579
+
1580
+ hidden_states = model_outputs[0]
1581
+ hidden_states = self.dropout(hidden_states)
1582
+ logits = self.classifier(hidden_states)
1583
+
1584
+ loss = None
1585
+ if labels is not None:
1586
+ # move labels to correct device to enable model parallelism
1587
+ labels = labels.to(logits.device)
1588
+ batch_size, seq_length = labels.shape
1589
+ loss_fct = CrossEntropyLoss()
1590
+ loss = loss_fct(
1591
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1592
+ )
1593
+
1594
+ if not return_dict:
1595
+ output = (logits,) + model_outputs[2:]
1596
+ return ((loss,) + output) if loss is not None else output
1597
+
1598
+ return TokenClassifierOutput(
1599
+ loss=loss,
1600
+ logits=logits,
1601
+ hidden_states=model_outputs.hidden_states,
1602
+ attentions=model_outputs.attentions,
1603
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|/inst|>"
4
+ ],
5
+ "bos_token": {
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "eos_token": {
13
+ "content": "<|endoftext|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false
18
+ },
19
+ "pad_token": "<s>",
20
+ "unk_token": {
21
+ "content": "<unk>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ }
27
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": true,
26
+ "single_word": false,
27
+ "special": false
28
+ },
29
+ "32000": {
30
+ "content": "<|endoftext|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "32001": {
38
+ "content": "<|assistant|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": true,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "32002": {
46
+ "content": "<|step|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": true,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "32003": {
54
+ "content": "<|function_output|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": true,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "32004": {
62
+ "content": "<|tag|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": true,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "32005": {
70
+ "content": "<|function_call|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": true,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "32006": {
78
+ "content": "<|system|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": true,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "32007": {
86
+ "content": "<|end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": true,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "32008": {
94
+ "content": "<|raw|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": true,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "32009": {
102
+ "content": "<|continue|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": true,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "32010": {
110
+ "content": "<|user|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": true,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "32011": {
118
+ "content": "<|function_list|>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": true,
122
+ "single_word": false,
123
+ "special": true
124
+ },
125
+ "32012": {
126
+ "content": "<|calc|>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": true,
130
+ "single_word": false,
131
+ "special": true
132
+ },
133
+ "32013": {
134
+ "content": "<|code|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": true,
138
+ "single_word": false,
139
+ "special": true
140
+ },
141
+ "32014": {
142
+ "content": "<|/code|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": true,
146
+ "single_word": false,
147
+ "special": true
148
+ },
149
+ "32015": {
150
+ "content": "<|summary|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": true,
154
+ "single_word": false,
155
+ "special": true
156
+ },
157
+ "32016": {
158
+ "content": "<|resource|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": true,
162
+ "single_word": false,
163
+ "special": true
164
+ },
165
+ "32017": {
166
+ "content": "<|assistant_mask|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": true,
170
+ "single_word": false,
171
+ "special": true
172
+ },
173
+ "32018": {
174
+ "content": "<|start|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": true,
178
+ "single_word": false,
179
+ "special": true
180
+ },
181
+ "32019": {
182
+ "content": "<|message|>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": true,
186
+ "single_word": false,
187
+ "special": true
188
+ },
189
+ "32020": {
190
+ "content": "<|fim_prefix|>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": true,
194
+ "single_word": false,
195
+ "special": true
196
+ },
197
+ "32021": {
198
+ "content": "<|fim_middle|>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": true,
202
+ "single_word": false,
203
+ "special": true
204
+ },
205
+ "32022": {
206
+ "content": "<|fim_suffix|>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": true,
210
+ "single_word": false,
211
+ "special": true
212
+ },
213
+ "32023": {
214
+ "content": "<|meta_start|>",
215
+ "lstrip": false,
216
+ "normalized": false,
217
+ "rstrip": true,
218
+ "single_word": false,
219
+ "special": true
220
+ },
221
+ "32024": {
222
+ "content": "<|ipynb_marker|>",
223
+ "lstrip": false,
224
+ "normalized": false,
225
+ "rstrip": true,
226
+ "single_word": false,
227
+ "special": true
228
+ },
229
+ "32025": {
230
+ "content": "<|diff_marker|>",
231
+ "lstrip": false,
232
+ "normalized": false,
233
+ "rstrip": true,
234
+ "single_word": false,
235
+ "special": true
236
+ },
237
+ "32026": {
238
+ "content": "<|ghissue|>",
239
+ "lstrip": false,
240
+ "normalized": false,
241
+ "rstrip": true,
242
+ "single_word": false,
243
+ "special": true
244
+ },
245
+ "32027": {
246
+ "content": "<|ghreview|>",
247
+ "lstrip": false,
248
+ "normalized": false,
249
+ "rstrip": true,
250
+ "single_word": false,
251
+ "special": true
252
+ },
253
+ "32028": {
254
+ "content": "<|disc_start|>",
255
+ "lstrip": false,
256
+ "normalized": false,
257
+ "rstrip": true,
258
+ "single_word": false,
259
+ "special": true
260
+ },
261
+ "32029": {
262
+ "content": "<|disc_sep|>",
263
+ "lstrip": false,
264
+ "normalized": false,
265
+ "rstrip": true,
266
+ "single_word": false,
267
+ "special": true
268
+ },
269
+ "32030": {
270
+ "content": "<|disc_thread|><|query|>",
271
+ "lstrip": false,
272
+ "normalized": false,
273
+ "rstrip": true,
274
+ "single_word": false,
275
+ "special": true
276
+ },
277
+ "32031": {
278
+ "content": "<|/query|>",
279
+ "lstrip": false,
280
+ "normalized": false,
281
+ "rstrip": true,
282
+ "single_word": false,
283
+ "special": true
284
+ },
285
+ "32032": {
286
+ "content": "<|data|>",
287
+ "lstrip": false,
288
+ "normalized": false,
289
+ "rstrip": true,
290
+ "single_word": false,
291
+ "special": true
292
+ },
293
+ "32033": {
294
+ "content": "<|/data|>",
295
+ "lstrip": false,
296
+ "normalized": false,
297
+ "rstrip": true,
298
+ "single_word": false,
299
+ "special": true
300
+ },
301
+ "32034": {
302
+ "content": "<|sys|>",
303
+ "lstrip": false,
304
+ "normalized": false,
305
+ "rstrip": true,
306
+ "single_word": false,
307
+ "special": true
308
+ },
309
+ "32035": {
310
+ "content": "<|/sys|>",
311
+ "lstrip": false,
312
+ "normalized": false,
313
+ "rstrip": true,
314
+ "single_word": false,
315
+ "special": true
316
+ },
317
+ "32036": {
318
+ "content": "<|inst|>",
319
+ "lstrip": false,
320
+ "normalized": false,
321
+ "rstrip": true,
322
+ "single_word": false,
323
+ "special": true
324
+ },
325
+ "32037": {
326
+ "content": "<|/inst|>",
327
+ "lstrip": false,
328
+ "normalized": false,
329
+ "rstrip": true,
330
+ "single_word": false,
331
+ "special": true
332
+ }
333
+ },
334
+ "additional_special_tokens": [
335
+ "<|/inst|>"
336
+ ],
337
+ "bos_token": "<s>",
338
+ "chat_template": "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'system') %}{{'<|system|>' + '\n' + message['content'] + '<|end|>' + '\n'}}{% elif (message['role'] == 'user') %}{{'<|user|>' + '\n' + message['content'] + '<|end|>' + '\n' + '<|assistant|>' + '\n'}}{% elif message['role'] == 'assistant' %}{{message['content'] + '<|end|>' + '\n'}}{% endif %}{% endfor %}",
339
+ "clean_up_tokenization_spaces": false,
340
+ "eos_token": "<|endoftext|>",
341
+ "legacy": false,
342
+ "model_max_length": 131072,
343
+ "pad_token": "<s>",
344
+ "padding_side": "left",
345
+ "sp_model_kwargs": {},
346
+ "tokenizer_class": "LlamaTokenizer",
347
+ "unk_token": "<unk>",
348
+ "use_default_system_prompt": false
349
+ }