awni commited on
Commit
423f068
1 Parent(s): 31cd5ff

Upload folder using huggingface_hub

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