sj2704 commited on
Commit
f5fb76c
·
verified ·
1 Parent(s): 6bf9da2

Upload folder using huggingface_hub

Browse files
added_tokens.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "\t\t": 50294,
3
+ "\t\t\t": 50293,
4
+ "\t\t\t\t": 50292,
5
+ "\t\t\t\t\t": 50291,
6
+ "\t\t\t\t\t\t": 50290,
7
+ "\t\t\t\t\t\t\t": 50289,
8
+ "\t\t\t\t\t\t\t\t": 50288,
9
+ "\t\t\t\t\t\t\t\t\t": 50287,
10
+ " ": 50286,
11
+ " ": 50285,
12
+ " ": 50284,
13
+ " ": 50283,
14
+ " ": 50282,
15
+ " ": 50281,
16
+ " ": 50280,
17
+ " ": 50279,
18
+ " ": 50278,
19
+ " ": 50277,
20
+ " ": 50276,
21
+ " ": 50275,
22
+ " ": 50274,
23
+ " ": 50273,
24
+ " ": 50272,
25
+ " ": 50271,
26
+ " ": 50270,
27
+ " ": 50269,
28
+ " ": 50268,
29
+ " ": 50267,
30
+ " ": 50266,
31
+ " ": 50265,
32
+ " ": 50264,
33
+ " ": 50263,
34
+ " ": 50262,
35
+ " ": 50261,
36
+ " ": 50260,
37
+ " ": 50259,
38
+ " ": 50258,
39
+ " ": 50257
40
+ }
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "microsoft/phi-2",
3
+ "architectures": [
4
+ "PhiForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi_2.PhiConfig",
9
+ "AutoModelForCausalLM": "modeling_phi_2.PhiForCausalLM"
10
+ },
11
+ "bos_token_id": 50256,
12
+ "embd_pdrop": 0.0,
13
+ "eos_token_id": 50256,
14
+ "hidden_act": "gelu_new",
15
+ "hidden_size": 2560,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 10240,
18
+ "layer_norm_eps": 1e-05,
19
+ "max_position_embeddings": 2048,
20
+ "model_type": "phi",
21
+ "num_attention_heads": 32,
22
+ "num_experts_per_tok": 2,
23
+ "num_hidden_layers": 32,
24
+ "num_key_value_heads": 32,
25
+ "num_local_experts": 2,
26
+ "partial_rotary_factor": 0.4,
27
+ "qk_layernorm": false,
28
+ "resid_pdrop": 0.1,
29
+ "rope_scaling": null,
30
+ "rope_theta": 10000.0,
31
+ "sliding_window": null,
32
+ "tie_word_embeddings": false,
33
+ "torch_dtype": "float16",
34
+ "transformers_version": "4.41.2",
35
+ "use_cache": true,
36
+ "vocab_size": 51200
37
+ }
configuration_phi_2.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 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
+
26
+ class PhiConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the Phi
31
+ [microsoft/phi-1](https://huggingface.co/microsoft/phi-1).
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 51200):
38
+ Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`PhiModel`].
40
+ hidden_size (`int`, *optional*, defaults to 2048):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 8192):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 24):
45
+ Number of hidden layers in the Transformer decoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer decoder.
48
+ num_key_value_heads (`int`, *optional*):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
55
+ `num_attention_heads`.
56
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
57
+ Dropout probability for mlp outputs.
58
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
59
+ The dropout ratio for the embeddings.
60
+ attention_dropout (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio after computing the attention scores.
62
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
63
+ The non-linear activation function (function or string) in the decoder.
64
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
65
+ The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
66
+ tokens.
67
+ initializer_range (`float`, *optional*, defaults to 0.02):
68
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
69
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
70
+ The epsilon used by the rms normalization layers.
71
+ use_cache (`bool`, *optional*, defaults to `True`):
72
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
73
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
74
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
75
+ Whether to tie weight embeddings
76
+ rope_theta (`float`, *optional*, defaults to 10000.0):
77
+ The base period of the RoPE embeddings.
78
+ rope_scaling (`Dict`, *optional*):
79
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
80
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
81
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
82
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
83
+ these scaling strategies behave:
84
+ https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
85
+ is an experimental feature, subject to breaking API changes in future versions.
86
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
87
+ Percentage of the query and keys which will have rotary embedding.
88
+ qk_layernorm (`bool`, *optional*, defaults to `False`):
89
+ Whether or not to normalize the Queries and Keys after projecting the hidden states.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ Denotes beginning of sequences token id.
92
+ eos_token_id (`int`, *optional*, defaults to 2):
93
+ Denotes end of sequences token id.
94
+
95
+ Example:
96
+
97
+ ```python
98
+ >>> from transformers import PhiModel, PhiConfig
99
+
100
+ >>> # Initializing a Phi-1 style configuration
101
+ >>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
102
+
103
+ >>> # Initializing a model from the configuration
104
+ >>> model = PhiModel(configuration)
105
+
106
+ >>> # Accessing the model configuration
107
+ >>> configuration = model.config
108
+ ```"""
109
+
110
+ model_type = "phi"
111
+ keys_to_ignore_at_inference = ["past_key_values"]
112
+
113
+ def __init__(
114
+ self,
115
+ vocab_size=51200,
116
+ hidden_size=2048,
117
+ intermediate_size=8192,
118
+ num_hidden_layers=24,
119
+ num_attention_heads=32,
120
+ num_key_value_heads=None,
121
+ resid_pdrop=0.0,
122
+ embd_pdrop=0.0,
123
+ attention_dropout=0.0,
124
+ hidden_act="gelu_new",
125
+ max_position_embeddings=2048,
126
+ initializer_range=0.02,
127
+ layer_norm_eps=1e-5,
128
+ use_cache=True,
129
+ tie_word_embeddings=False,
130
+ rope_theta=10000.0,
131
+ rope_scaling=None,
132
+ partial_rotary_factor=0.5,
133
+ qk_layernorm=False,
134
+ bos_token_id=1,
135
+ eos_token_id=2,
136
+ num_experts=2,
137
+ num_experts_per_token=1,
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
+ self.num_experts = num_experts
146
+ self.num_experts_per_token = num_experts_per_token
147
+ if num_key_value_heads is None:
148
+ num_key_value_heads = num_attention_heads
149
+
150
+ self.num_key_value_heads = num_key_value_heads
151
+ self.resid_pdrop = resid_pdrop
152
+ self.embd_pdrop = embd_pdrop
153
+ self.attention_dropout = attention_dropout
154
+ self.hidden_act = hidden_act
155
+ self.max_position_embeddings = max_position_embeddings
156
+ self.initializer_range = initializer_range
157
+ self.layer_norm_eps = layer_norm_eps
158
+ self.use_cache = use_cache
159
+ self.rope_theta = rope_theta
160
+ self.rope_scaling = rope_scaling
161
+ self.partial_rotary_factor = partial_rotary_factor
162
+ self.qk_layernorm = qk_layernorm
163
+ self._rope_scaling_validation()
164
+
165
+ super().__init__(
166
+ bos_token_id=bos_token_id,
167
+ eos_token_id=eos_token_id,
168
+ tie_word_embeddings=tie_word_embeddings,
169
+ **kwargs,
170
+ )
171
+
172
+ # Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
173
+ def _rope_scaling_validation(self):
174
+ """
175
+ Validate the `rope_scaling` configuration.
176
+ """
177
+ if self.rope_scaling is None:
178
+ return
179
+
180
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
181
+ raise ValueError(
182
+ "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
183
+ )
184
+ rope_scaling_type = self.rope_scaling.get("type", None)
185
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
186
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
187
+ raise ValueError(
188
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
189
+ )
190
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
191
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
mergekit_moe_config.yml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ base_model: microsoft/phi-2
2
+ gate_mode: hidden
3
+ dtype: float16
4
+ experts:
5
+ - source_model: "microsoft/phi-2"
6
+ positive_prompts:
7
+ - "Chat"
8
+ - "Summarize"
9
+ - "Help"
10
+ - source_model: "vimal52/phi2_medical"
11
+ positive_prompts:
12
+ - "Doctor"
13
+ - "Patient"
14
+ - "Medical"
15
+ - "Chat"
16
+ - "Summarize"
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc7726bc7b470c39181525fb48ecb9c7f7fe6ae20b6514bc1d2b2b9d52eb1d9f
3
+ size 1993424456
model-00002-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07eb0f3e204f548505ac308b6077da67d811a631bd509d5c3050f55fcd591a9b
3
+ size 1993617704
model-00003-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f46eccb2116ff90e9eaee33cf11422bf07c6bd0ac3481542b4a68fcb3c07002c
3
+ size 1992633184
model-00004-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db3a9aa20e85066a8feff00e14593491f7c9c522962865e4a20afa7257b9ca72
3
+ size 1992298752
model-00005-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e12095c360c8f884efca5b51ebb6412ec9df884252229a7584e8f87b7673882
3
+ size 944051344
model.safetensors.index.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"metadata": {"mergekit_version": "0.0.4"}, "weight_map": {"model.embed_tokens.weight": "model-00001-of-00005.safetensors", "lm_head.bias": "model-00001-of-00005.safetensors", "lm_head.weight": "model-00001-of-00005.safetensors", "model.final_layernorm.bias": "model-00001-of-00005.safetensors", "model.final_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.0.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.1.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.2.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.3.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.4.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.5.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.6.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.7.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.8.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.9.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.10.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.11.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.12.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.13.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.14.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.15.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.16.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.17.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.18.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.19.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.20.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.21.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.22.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.23.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.24.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.25.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.26.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.27.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.28.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.29.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.30.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.31.input_layernorm.bias": "model-00001-of-00005.safetensors", "model.layers.0.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.1.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.2.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.3.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.4.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.5.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.6.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.7.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.8.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.9.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.10.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.11.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.12.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.13.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.14.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.15.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.16.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.17.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.18.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.19.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.20.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.21.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.22.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.23.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.24.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.25.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.26.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.27.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.28.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.29.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.30.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.31.input_layernorm.weight": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.4.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.5.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.6.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.7.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.8.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.9.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.10.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.11.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.12.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.13.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.14.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.15.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.16.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.17.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.18.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.19.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.20.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.21.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.22.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.23.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.24.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.25.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.26.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.27.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.28.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.29.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.30.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.31.self_attn.dense.bias": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.4.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.5.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.6.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.7.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.8.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.9.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.10.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.11.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.12.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.13.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.14.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.15.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.16.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.17.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.18.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.19.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.20.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.21.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.22.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.23.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.24.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.25.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.26.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.27.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.28.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.29.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.30.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.31.self_attn.dense.weight": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.6.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.7.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.8.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.9.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.10.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.11.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.12.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.13.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.14.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.15.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.16.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.17.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.18.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.19.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.20.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.21.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.22.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.23.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.24.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.25.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.26.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.27.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.28.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.29.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.30.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.31.self_attn.q_proj.bias": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.12.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.13.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.14.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.15.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.16.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.17.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.18.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.19.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.20.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.21.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.22.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.23.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.24.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.25.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.26.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.27.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.28.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.29.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.30.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.31.self_attn.q_proj.weight": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.6.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.7.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.8.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.9.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.10.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.11.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.12.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.13.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.14.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.15.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.16.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.17.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.18.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.19.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.20.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.21.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.22.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.23.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.24.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.25.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.26.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.27.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.28.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.29.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.30.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.31.self_attn.k_proj.bias": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.12.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.13.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.14.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.15.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.16.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.17.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.18.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.19.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.20.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.21.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.22.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.23.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.24.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.25.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.26.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.27.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.28.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.29.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.30.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.31.self_attn.k_proj.weight": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.6.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.7.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.8.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.9.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.10.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.11.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.12.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.13.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.14.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.15.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.16.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.17.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.18.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.19.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.20.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.21.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.22.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.23.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.24.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.25.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.26.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.27.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.28.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.29.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.30.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.31.self_attn.v_proj.bias": "model-00001-of-00005.safetensors", "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.11.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.12.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.13.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.14.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.15.self_attn.v_proj.weight": "model-00001-of-00005.safetensors", "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.21.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.23.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.24.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.25.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.26.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.27.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.28.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.29.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.30.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.31.self_attn.v_proj.weight": "model-00002-of-00005.safetensors", "model.layers.0.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.0.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.1.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.1.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.2.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.2.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.3.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.3.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.4.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.4.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.5.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.5.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.6.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.6.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.7.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.7.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.8.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.8.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.9.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.9.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.10.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.10.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.11.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.11.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.12.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.12.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.13.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.13.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.14.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.14.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.15.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.15.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.16.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.16.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.17.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.17.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.18.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.18.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.19.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.19.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.20.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.20.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.21.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.21.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.22.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.22.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.23.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.23.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.24.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.24.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.25.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.25.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.26.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.26.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.27.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.27.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.28.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.28.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.29.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.29.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.30.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.30.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.31.moe.mlp.0.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.31.moe.mlp.1.fc1.bias": "model-00002-of-00005.safetensors", "model.layers.0.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.0.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.1.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.1.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.2.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.2.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.3.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.3.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.4.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.4.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.5.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.5.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.6.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.6.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.7.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.7.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.8.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.8.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.9.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.9.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.10.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.10.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.11.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.11.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.12.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.12.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.13.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.13.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.14.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.14.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.15.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.15.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.16.moe.mlp.0.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.16.moe.mlp.1.fc1.weight": "model-00002-of-00005.safetensors", "model.layers.17.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.17.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.18.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.18.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.19.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.19.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.20.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.20.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.21.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.21.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.22.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.22.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.23.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.23.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.24.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.24.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.25.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.25.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.26.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.26.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.27.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.27.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.28.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.28.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.29.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.29.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.30.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.30.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.31.moe.mlp.0.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.31.moe.mlp.1.fc1.weight": "model-00003-of-00005.safetensors", "model.layers.0.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.0.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.1.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.1.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.2.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.2.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.3.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.3.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.4.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.4.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.5.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.5.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.6.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.6.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.7.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.7.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.8.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.8.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.9.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.9.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.10.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.10.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.11.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.11.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.12.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.12.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.13.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.13.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.14.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.14.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.15.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.15.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.16.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.16.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.17.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.17.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.18.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.18.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.19.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.19.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.20.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.20.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.21.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.21.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.22.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.22.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.23.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.23.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.24.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.24.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.25.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.25.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.26.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.26.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.27.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.27.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.28.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.28.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.29.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.29.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.30.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.30.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.31.moe.mlp.0.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.31.moe.mlp.1.fc2.bias": "model-00003-of-00005.safetensors", "model.layers.0.moe.mlp.0.fc2.weight": "model-00003-of-00005.safetensors", "model.layers.0.moe.mlp.1.fc2.weight": "model-00003-of-00005.safetensors", "model.layers.1.moe.mlp.0.fc2.weight": "model-00003-of-00005.safetensors", "model.layers.1.moe.mlp.1.fc2.weight": "model-00003-of-00005.safetensors", "model.layers.2.moe.mlp.0.fc2.weight": "model-00003-of-00005.safetensors", "model.layers.2.moe.mlp.1.fc2.weight": "model-00003-of-00005.safetensors", "model.layers.3.moe.mlp.0.fc2.weight": "model-00003-of-00005.safetensors", "model.layers.3.moe.mlp.1.fc2.weight": "model-00003-of-00005.safetensors", "model.layers.4.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.4.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.5.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.5.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.6.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.6.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.7.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.7.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.8.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.8.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.9.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.9.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.10.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.10.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.11.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.11.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.12.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.12.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.13.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.13.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.14.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.14.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.15.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.15.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.16.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.16.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.17.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.17.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.18.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.18.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.19.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.19.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.20.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.20.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.21.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.21.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.22.moe.mlp.0.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.22.moe.mlp.1.fc2.weight": "model-00004-of-00005.safetensors", "model.layers.23.moe.mlp.0.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.23.moe.mlp.1.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.24.moe.mlp.0.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.24.moe.mlp.1.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.25.moe.mlp.0.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.25.moe.mlp.1.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.26.moe.mlp.0.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.26.moe.mlp.1.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.27.moe.mlp.0.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.27.moe.mlp.1.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.28.moe.mlp.0.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.28.moe.mlp.1.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.29.moe.mlp.0.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.29.moe.mlp.1.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.30.moe.mlp.0.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.30.moe.mlp.1.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.31.moe.mlp.0.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.31.moe.mlp.1.fc2.weight": "model-00005-of-00005.safetensors", "model.layers.0.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.1.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.2.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.3.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.4.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.5.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.6.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.7.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.8.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.9.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.10.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.11.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.12.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.13.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.14.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.15.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.16.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.17.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.18.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.19.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.20.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.21.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.22.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.23.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.24.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.25.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.26.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.27.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.28.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.29.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.30.moe.gate.weight": "model-00005-of-00005.safetensors", "model.layers.31.moe.gate.weight": "model-00005-of-00005.safetensors"}}
modeling_phi_2.py ADDED
@@ -0,0 +1,1515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 model."""
17
+
18
+
19
+ import math
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from packaging import version
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 (
32
+ _prepare_4d_causal_attention_mask,
33
+ _prepare_4d_causal_attention_mask_for_sdpa,
34
+ )
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.utils import (
43
+ add_code_sample_docstrings,
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ get_torch_version,
47
+ is_flash_attn_2_available,
48
+ is_flash_attn_greater_or_equal_2_10,
49
+ logging,
50
+ replace_return_docstrings,
51
+ )
52
+ from .configuration_phi_2 import PhiConfig
53
+
54
+ if is_flash_attn_2_available():
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ _CHECKPOINT_FOR_DOC = "microsoft/phi-1"
62
+ _CONFIG_FOR_DOC = "PhiConfig"
63
+
64
+
65
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
66
+ def _get_unpad_data(attention_mask):
67
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
68
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
69
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
70
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
71
+ return (
72
+ indices,
73
+ cu_seqlens,
74
+ max_seqlen_in_batch,
75
+ )
76
+
77
+
78
+ # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Phi
79
+ class PhiRotaryEmbedding(nn.Module):
80
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
81
+ super().__init__()
82
+
83
+ self.dim = dim
84
+ self.max_position_embeddings = max_position_embeddings
85
+ self.base = base
86
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
87
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
88
+
89
+ # Build here to make `torch.jit.trace` work.
90
+ self._set_cos_sin_cache(
91
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
92
+ )
93
+
94
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
95
+ self.max_seq_len_cached = seq_len
96
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
97
+
98
+ freqs = torch.outer(t, self.inv_freq)
99
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
100
+ emb = torch.cat((freqs, freqs), dim=-1)
101
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
102
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
103
+
104
+ def forward(self, x, seq_len=None):
105
+ # x: [bs, num_attention_heads, seq_len, head_size]
106
+ if seq_len > self.max_seq_len_cached:
107
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
108
+
109
+ return (
110
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
111
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
112
+ )
113
+
114
+
115
+ # Copied from transformers.models.falcon.modeling_falcon.FalconLinearScalingRotaryEmbedding with Falcon->Phi
116
+ class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
117
+ """PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
118
+
119
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
120
+ self.scaling_factor = scaling_factor
121
+ super().__init__(dim, max_position_embeddings, base, device)
122
+
123
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
124
+ self.max_seq_len_cached = seq_len
125
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
126
+ t = t / self.scaling_factor
127
+
128
+ freqs = torch.outer(t, self.inv_freq)
129
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
130
+ emb = torch.cat((freqs, freqs), dim=-1)
131
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
132
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
133
+
134
+
135
+ # Copied from transformers.models.falcon.modeling_falcon.FalconDynamicNTKScalingRotaryEmbedding with Falcon->Phi
136
+ class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
137
+ """PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
138
+
139
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
140
+ self.scaling_factor = scaling_factor
141
+ super().__init__(dim, max_position_embeddings, base, device)
142
+
143
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
144
+ self.max_seq_len_cached = seq_len
145
+
146
+ if seq_len > self.max_position_embeddings:
147
+ base = self.base * (
148
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
149
+ ) ** (self.dim / (self.dim - 2))
150
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
151
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
152
+
153
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
154
+
155
+ freqs = torch.outer(t, self.inv_freq)
156
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
157
+ emb = torch.cat((freqs, freqs), dim=-1)
158
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
159
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
160
+
161
+
162
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
163
+ def rotate_half(x):
164
+ """Rotates half the hidden dims of the input."""
165
+ x1 = x[..., : x.shape[-1] // 2]
166
+ x2 = x[..., x.shape[-1] // 2 :]
167
+ return torch.cat((-x2, x1), dim=-1)
168
+
169
+
170
+ # Copied from transformers.models.mistral.modeling_mistral.apply_rotary_pos_emb
171
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
172
+ """Applies Rotary Position Embedding to the query and key tensors.
173
+
174
+ Args:
175
+ q (`torch.Tensor`): The query tensor.
176
+ k (`torch.Tensor`): The key tensor.
177
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
178
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
179
+ position_ids (`torch.Tensor`):
180
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
181
+ used to pass offsetted position ids when working with a KV-cache.
182
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
183
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
184
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
185
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
186
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
187
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
188
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
189
+ Returns:
190
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
191
+ """
192
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
193
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
194
+ q_embed = (q * cos) + (rotate_half(q) * sin)
195
+ k_embed = (k * cos) + (rotate_half(k) * sin)
196
+ return q_embed, k_embed
197
+
198
+
199
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
200
+ class PhiMLP(nn.Module):
201
+ def __init__(self, config):
202
+ super().__init__()
203
+ self.config = config
204
+ self.activation_fn = ACT2FN[config.hidden_act]
205
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
206
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
207
+
208
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
209
+ hidden_states = self.fc1(hidden_states)
210
+ hidden_states = self.activation_fn(hidden_states)
211
+ hidden_states = self.fc2(hidden_states)
212
+ return hidden_states
213
+
214
+
215
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
216
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
217
+ """
218
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
219
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
220
+ """
221
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
222
+ if n_rep == 1:
223
+ return hidden_states
224
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
225
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
226
+
227
+
228
+ class PhiAttention(nn.Module):
229
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
230
+
231
+ def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
232
+ super().__init__()
233
+ self.config = config
234
+ self.layer_idx = layer_idx
235
+ if layer_idx is None:
236
+ logger.warning_once(
237
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
238
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
239
+ "when creating this class."
240
+ )
241
+
242
+ self.attention_dropout = config.attention_dropout
243
+ self.hidden_size = config.hidden_size
244
+ self.num_heads = config.num_attention_heads
245
+ self.head_dim = self.hidden_size // self.num_heads
246
+ self.num_key_value_heads = config.num_key_value_heads
247
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
248
+ self.max_position_embeddings = config.max_position_embeddings
249
+ self.rope_theta = config.rope_theta
250
+ self.partial_rotary_factor = config.partial_rotary_factor
251
+ self.is_causal = True
252
+
253
+ if (self.head_dim * self.num_heads) != self.hidden_size:
254
+ raise ValueError(
255
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
256
+ f" and `num_heads`: {self.num_heads})."
257
+ )
258
+
259
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
260
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
261
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
262
+ self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
263
+
264
+ self.qk_layernorm = config.qk_layernorm
265
+ if self.qk_layernorm:
266
+ self.q_layernorm = nn.LayerNorm(
267
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
268
+ )
269
+ self.k_layernorm = nn.LayerNorm(
270
+ config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
271
+ )
272
+
273
+ self._init_rope()
274
+
275
+ def _init_rope(self):
276
+ if self.config.rope_scaling is None:
277
+ self.rotary_emb = PhiRotaryEmbedding(
278
+ int(self.partial_rotary_factor * self.head_dim),
279
+ max_position_embeddings=self.max_position_embeddings,
280
+ base=self.rope_theta,
281
+ )
282
+ else:
283
+ scaling_type = self.config.rope_scaling["type"]
284
+ scaling_factor = self.config.rope_scaling["factor"]
285
+ if scaling_type == "linear":
286
+ self.rotary_emb = PhiLinearScalingRotaryEmbedding(
287
+ int(self.partial_rotary_factor * self.head_dim),
288
+ max_position_embeddings=self.max_position_embeddings,
289
+ scaling_factor=scaling_factor,
290
+ base=self.rope_theta,
291
+ )
292
+ elif scaling_type == "dynamic":
293
+ self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
294
+ int(self.partial_rotary_factor * self.head_dim),
295
+ max_position_embeddings=self.max_position_embeddings,
296
+ scaling_factor=scaling_factor,
297
+ base=self.rope_theta,
298
+ )
299
+ else:
300
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
301
+
302
+ def forward(
303
+ self,
304
+ hidden_states: torch.Tensor,
305
+ attention_mask: Optional[torch.Tensor] = None,
306
+ position_ids: Optional[torch.LongTensor] = None,
307
+ past_key_value: Optional[Cache] = None,
308
+ output_attentions: bool = False,
309
+ use_cache: bool = False,
310
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
311
+ bsz, q_len, _ = hidden_states.size()
312
+
313
+ query_states = self.q_proj(hidden_states)
314
+ key_states = self.k_proj(hidden_states)
315
+ value_states = self.v_proj(hidden_states)
316
+
317
+ if self.qk_layernorm:
318
+ query_states = self.q_layernorm(query_states)
319
+ key_states = self.k_layernorm(key_states)
320
+
321
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
322
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
323
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
324
+
325
+ kv_seq_len = key_states.shape[-2]
326
+ if past_key_value is not None:
327
+ if self.layer_idx is None:
328
+ raise ValueError(
329
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
330
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
331
+ "with a layer index."
332
+ )
333
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
334
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
335
+
336
+ # Partial rotary embedding
337
+ query_rot, query_pass = (
338
+ query_states[..., : self.rotary_emb.dim],
339
+ query_states[..., self.rotary_emb.dim :],
340
+ )
341
+ key_rot, key_pass = (
342
+ key_states[..., : self.rotary_emb.dim],
343
+ key_states[..., self.rotary_emb.dim :],
344
+ )
345
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
346
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
347
+
348
+ # [batch_size, seq_length, num_heads, head_dim]
349
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
350
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
351
+
352
+ if past_key_value is not None:
353
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
354
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
355
+
356
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
357
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
358
+
359
+ # Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
360
+ attn_weights = torch.matmul(
361
+ query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
362
+ ) / math.sqrt(self.head_dim)
363
+
364
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
365
+ raise ValueError(
366
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
367
+ f" {attn_weights.size()}"
368
+ )
369
+
370
+ if attention_mask is not None:
371
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
372
+ raise ValueError(
373
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
374
+ )
375
+ attn_weights = attn_weights + attention_mask
376
+
377
+ # upcast attention to fp32
378
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
379
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
380
+
381
+ attn_output = torch.matmul(attn_weights, value_states)
382
+
383
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
384
+ raise ValueError(
385
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
386
+ f" {attn_output.size()}"
387
+ )
388
+
389
+ attn_output = attn_output.transpose(1, 2).contiguous()
390
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
391
+
392
+ attn_output = self.dense(attn_output)
393
+
394
+ if not output_attentions:
395
+ attn_weights = None
396
+
397
+ return attn_output, attn_weights, past_key_value
398
+
399
+
400
+ class PhiFlashAttention2(PhiAttention):
401
+ """
402
+ Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
403
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
404
+ flash attention and deal with padding tokens in case the input contains any of them.
405
+ """
406
+
407
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
408
+ def __init__(self, *args, **kwargs):
409
+ super().__init__(*args, **kwargs)
410
+
411
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
412
+ # 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.
413
+ # 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).
414
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
415
+
416
+ def forward(
417
+ self,
418
+ hidden_states: torch.Tensor,
419
+ attention_mask: Optional[torch.LongTensor] = None,
420
+ position_ids: Optional[torch.LongTensor] = None,
421
+ past_key_value: Optional[Cache] = None,
422
+ output_attentions: bool = False,
423
+ use_cache: bool = False,
424
+ **kwargs,
425
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
426
+ # PhiFlashAttention2 attention does not support output_attentions
427
+
428
+ output_attentions = False
429
+
430
+ bsz, q_len, _ = hidden_states.size()
431
+
432
+ query_states = self.q_proj(hidden_states)
433
+ key_states = self.k_proj(hidden_states)
434
+ value_states = self.v_proj(hidden_states)
435
+
436
+ if self.qk_layernorm:
437
+ query_states = self.q_layernorm(query_states)
438
+ key_states = self.k_layernorm(key_states)
439
+
440
+ # Flash attention requires the input to have the shape
441
+ # batch_size x seq_length x head_dim x hidden_dim
442
+ # therefore we just need to keep the original shape
443
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
444
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
445
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
446
+
447
+ kv_seq_len = key_states.shape[-2]
448
+ if past_key_value is not None:
449
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
450
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
451
+
452
+ # Partial rotary embedding
453
+ query_rot, query_pass = (
454
+ query_states[..., : self.rotary_emb.dim],
455
+ query_states[..., self.rotary_emb.dim :],
456
+ )
457
+ key_rot, key_pass = (
458
+ key_states[..., : self.rotary_emb.dim],
459
+ key_states[..., self.rotary_emb.dim :],
460
+ )
461
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
462
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
463
+
464
+ # [batch_size, seq_length, num_heads, head_dim]
465
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
466
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
467
+
468
+ if past_key_value is not None:
469
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
470
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
471
+
472
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
473
+ # to be able to avoid many of these transpose/reshape/view.
474
+ query_states = query_states.transpose(1, 2)
475
+ key_states = key_states.transpose(1, 2)
476
+ value_states = value_states.transpose(1, 2)
477
+
478
+ attn_dropout = self.attention_dropout if self.training else 0.0
479
+
480
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
481
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
482
+ # cast them back in the correct dtype just to be sure everything works as expected.
483
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
484
+ # in fp32.
485
+
486
+ if query_states.dtype == torch.float32:
487
+ if torch.is_autocast_enabled():
488
+ target_dtype = torch.get_autocast_gpu_dtype()
489
+ # Handle the case where the model is quantized
490
+ elif hasattr(self.config, "_pre_quantization_dtype"):
491
+ target_dtype = self.config._pre_quantization_dtype
492
+ else:
493
+ target_dtype = self.q_proj.weight.dtype
494
+
495
+ logger.warning_once(
496
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
497
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
498
+ f" {target_dtype}."
499
+ )
500
+
501
+ query_states = query_states.to(target_dtype)
502
+ key_states = key_states.to(target_dtype)
503
+ value_states = value_states.to(target_dtype)
504
+
505
+ attn_output = self._flash_attention_forward(
506
+ query_states, key_states, value_states, attention_mask, q_len, dropout=attn_dropout, softmax_scale=None
507
+ )
508
+
509
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
510
+ attn_output = self.dense(attn_output)
511
+
512
+ if not output_attentions:
513
+ attn_weights = None
514
+
515
+ return attn_output, attn_weights, past_key_value
516
+
517
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
518
+ def _flash_attention_forward(
519
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
520
+ ):
521
+ """
522
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
523
+ first unpad the input, then computes the attention scores and pad the final attention scores.
524
+
525
+ Args:
526
+ query_states (`torch.Tensor`):
527
+ Input query states to be passed to Flash Attention API
528
+ key_states (`torch.Tensor`):
529
+ Input key states to be passed to Flash Attention API
530
+ value_states (`torch.Tensor`):
531
+ Input value states to be passed to Flash Attention API
532
+ attention_mask (`torch.Tensor`):
533
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
534
+ position of padding tokens and 1 for the position of non-padding tokens.
535
+ dropout (`float`):
536
+ Attention dropout
537
+ softmax_scale (`float`, *optional*):
538
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
539
+ """
540
+ if not self._flash_attn_uses_top_left_mask:
541
+ causal = self.is_causal
542
+ else:
543
+ # 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__.
544
+ causal = self.is_causal and query_length != 1
545
+
546
+ # Contains at least one padding token in the sequence
547
+ if attention_mask is not None:
548
+ batch_size = query_states.shape[0]
549
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
550
+ query_states, key_states, value_states, attention_mask, query_length
551
+ )
552
+
553
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
554
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
555
+
556
+ attn_output_unpad = flash_attn_varlen_func(
557
+ query_states,
558
+ key_states,
559
+ value_states,
560
+ cu_seqlens_q=cu_seqlens_q,
561
+ cu_seqlens_k=cu_seqlens_k,
562
+ max_seqlen_q=max_seqlen_in_batch_q,
563
+ max_seqlen_k=max_seqlen_in_batch_k,
564
+ dropout_p=dropout,
565
+ softmax_scale=softmax_scale,
566
+ causal=causal,
567
+ )
568
+
569
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
570
+ else:
571
+ attn_output = flash_attn_func(
572
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
573
+ )
574
+
575
+ return attn_output
576
+
577
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
578
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
579
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
580
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
581
+
582
+ key_layer = index_first_axis(
583
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
584
+ )
585
+ value_layer = index_first_axis(
586
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
587
+ )
588
+ if query_length == kv_seq_len:
589
+ query_layer = index_first_axis(
590
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
591
+ )
592
+ cu_seqlens_q = cu_seqlens_k
593
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
594
+ indices_q = indices_k
595
+ elif query_length == 1:
596
+ max_seqlen_in_batch_q = 1
597
+ cu_seqlens_q = torch.arange(
598
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
599
+ ) # There is a memcpy here, that is very bad.
600
+ indices_q = cu_seqlens_q[:-1]
601
+ query_layer = query_layer.squeeze(1)
602
+ else:
603
+ # The -q_len: slice assumes left padding.
604
+ attention_mask = attention_mask[:, -query_length:]
605
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
606
+
607
+ return (
608
+ query_layer,
609
+ key_layer,
610
+ value_layer,
611
+ indices_q,
612
+ (cu_seqlens_q, cu_seqlens_k),
613
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
614
+ )
615
+
616
+
617
+ class PhiSdpaAttention(PhiAttention):
618
+ def __init__(self, *args, **kwargs):
619
+ super().__init__(*args, **kwargs)
620
+ self.require_contiguous_qkv = version.parse(get_torch_version()) < version.parse("2.2.0")
621
+
622
+ """
623
+ SDPA attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
624
+ `PhiAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
625
+ SDPA API.
626
+ """
627
+
628
+ # Adapted from PhiAttention.forward
629
+ def forward(
630
+ self,
631
+ hidden_states: torch.Tensor,
632
+ attention_mask: Optional[torch.Tensor] = None,
633
+ position_ids: Optional[torch.LongTensor] = None,
634
+ past_key_value: Optional[Cache] = None,
635
+ output_attentions: bool = False,
636
+ use_cache: bool = False,
637
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
638
+ if output_attentions:
639
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
640
+ logger.warning_once(
641
+ "PhiModel is using PhiSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not "
642
+ "support `output_attentions=True`. Falling back to the manual attention implementation, but specifying "
643
+ "the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can "
644
+ 'be removed using the argument `attn_implementation="eager"` when loading the model.'
645
+ )
646
+ return super().forward(
647
+ hidden_states=hidden_states,
648
+ attention_mask=attention_mask,
649
+ position_ids=position_ids,
650
+ past_key_value=past_key_value,
651
+ output_attentions=output_attentions,
652
+ use_cache=use_cache,
653
+ )
654
+
655
+ bsz, q_len, _ = hidden_states.size()
656
+
657
+ query_states = self.q_proj(hidden_states)
658
+ key_states = self.k_proj(hidden_states)
659
+ value_states = self.v_proj(hidden_states)
660
+
661
+ if self.qk_layernorm:
662
+ query_states = self.q_layernorm(query_states)
663
+ key_states = self.k_layernorm(key_states)
664
+
665
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
666
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
667
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
668
+
669
+ kv_seq_len = key_states.shape[-2]
670
+ if past_key_value is not None:
671
+ if self.layer_idx is None:
672
+ raise ValueError(
673
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
674
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
675
+ "with a layer index."
676
+ )
677
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
678
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
679
+
680
+ # Partial rotary embedding
681
+ query_rot, query_pass = (
682
+ query_states[..., : self.rotary_emb.dim],
683
+ query_states[..., self.rotary_emb.dim :],
684
+ )
685
+ key_rot, key_pass = (
686
+ key_states[..., : self.rotary_emb.dim],
687
+ key_states[..., self.rotary_emb.dim :],
688
+ )
689
+ # [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
690
+ query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
691
+
692
+ # [batch_size, seq_length, num_heads, head_dim]
693
+ query_states = torch.cat((query_rot, query_pass), dim=-1)
694
+ key_states = torch.cat((key_rot, key_pass), dim=-1)
695
+
696
+ if past_key_value is not None:
697
+ cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
698
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
699
+
700
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
701
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
702
+
703
+ # SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
704
+ # attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
705
+ # Reference: https://github.com/pytorch/pytorch/issues/112577
706
+ if self.require_contiguous_qkv and query_states.device.type == "cuda" and attention_mask is not None:
707
+ query_states = query_states.contiguous()
708
+ key_states = key_states.contiguous()
709
+ value_states = value_states.contiguous()
710
+
711
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
712
+ query_states,
713
+ key_states,
714
+ value_states,
715
+ attn_mask=attention_mask,
716
+ dropout_p=self.attention_dropout if self.training else 0.0,
717
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
718
+ )
719
+
720
+ attn_output = attn_output.transpose(1, 2).contiguous()
721
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
722
+
723
+ attn_output = self.dense(attn_output)
724
+
725
+ return attn_output, None, past_key_value
726
+
727
+
728
+ PHI_ATTENTION_CLASSES = {
729
+ "eager": PhiAttention,
730
+ "flash_attention_2": PhiFlashAttention2,
731
+ "sdpa": PhiSdpaAttention,
732
+ }
733
+
734
+ class Phi2MoE(nn.Module):
735
+ def __init__(self, config):
736
+ super().__init__()
737
+ self.config = config
738
+ self.hidden_size = config.hidden_size
739
+ self.num_local_experts = config.num_local_experts
740
+ self.num_experts_per_tok = config.num_experts_per_tok
741
+ self.mlp = nn.ModuleList(
742
+ [PhiMLP(config) for i in range(self.num_local_experts)]
743
+ )
744
+ self.gate = nn.Linear(self.hidden_size, self.num_local_experts, bias=False)
745
+
746
+ def forward(self, x):
747
+ orig_shape = x.shape
748
+ x = x.view(-1, x.shape[-1])
749
+
750
+ scores = self.gate(x)
751
+ expert_weights, expert_indices = torch.topk(
752
+ scores, self.num_experts_per_tok, dim=-1
753
+ )
754
+ expert_weights = expert_weights.softmax(dim=-1)
755
+ flat_expert_indices = expert_indices.view(-1)
756
+
757
+ x = x.repeat_interleave(self.num_experts_per_tok, dim=0)
758
+ y = torch.empty_like(x)
759
+ for i, expert in enumerate(self.mlp):
760
+ y[flat_expert_indices == i] = expert(x[flat_expert_indices == i])
761
+ y = (y.view(*expert_weights.shape, -1) * expert_weights.unsqueeze(-1)).sum(
762
+ dim=1
763
+ )
764
+ return y.view(*orig_shape)
765
+
766
+ class PhiDecoderLayer(nn.Module):
767
+ def __init__(self, config: PhiConfig, layer_idx: int):
768
+ super().__init__()
769
+ self.self_attn = PHI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
770
+ self.moe = Phi2MoE(config)
771
+ self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
772
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
773
+
774
+ def forward(
775
+ self,
776
+ hidden_states: torch.Tensor,
777
+ attention_mask: Optional[torch.Tensor] = None,
778
+ position_ids: Optional[torch.LongTensor] = None,
779
+ output_attentions: Optional[bool] = False,
780
+ use_cache: Optional[bool] = False,
781
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
782
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
783
+ """
784
+ Args:
785
+ hidden_states (`torch.FloatTensor`):
786
+ input to the layer of shape `(batch, seq_len, embed_dim)`
787
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
788
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
789
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
790
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
791
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
792
+ output_attentions (`bool`, *optional*):
793
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
794
+ returned tensors for more detail.
795
+ use_cache (`bool`, *optional*):
796
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
797
+ (see `past_key_values`).
798
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
799
+ """
800
+
801
+ residual = hidden_states
802
+
803
+ hidden_states = self.input_layernorm(hidden_states)
804
+
805
+ # Self Attention
806
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
807
+ hidden_states=hidden_states,
808
+ attention_mask=attention_mask,
809
+ position_ids=position_ids,
810
+ past_key_value=past_key_value,
811
+ output_attentions=output_attentions,
812
+ use_cache=use_cache,
813
+ )
814
+ attn_outputs = self.resid_dropout(attn_outputs)
815
+
816
+ feed_forward_hidden_states = self.resid_dropout(self.moe(hidden_states))
817
+ hidden_states = attn_outputs + feed_forward_hidden_states + residual
818
+ outputs = (hidden_states,)
819
+
820
+ if output_attentions:
821
+ outputs += (self_attn_weights,)
822
+
823
+ if use_cache:
824
+ outputs += (present_key_value,)
825
+
826
+ return outputs
827
+
828
+
829
+ PHI_START_DOCSTRING = r"""
830
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
831
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
832
+ etc.)
833
+
834
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
835
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
836
+ and behavior.
837
+
838
+ Parameters:
839
+ config ([`PhiConfig`]):
840
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
841
+ load the weights associated with the model, only the configuration. Check out the
842
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
843
+ """
844
+
845
+
846
+ @add_start_docstrings(
847
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
848
+ PHI_START_DOCSTRING,
849
+ )
850
+ class PhiPreTrainedModel(PreTrainedModel):
851
+ config_class = PhiConfig
852
+ base_model_prefix = "model"
853
+ supports_gradient_checkpointing = True
854
+ _no_split_modules = ["PhiDecoderLayer"]
855
+ _skip_keys_device_placement = "past_key_values"
856
+ _supports_flash_attn_2 = True
857
+ _supports_sdpa = True
858
+
859
+ def _init_weights(self, module):
860
+ std = self.config.initializer_range
861
+ if isinstance(module, nn.Linear):
862
+ module.weight.data.normal_(mean=0.0, std=std)
863
+ if module.bias is not None:
864
+ module.bias.data.zero_()
865
+ elif isinstance(module, nn.Embedding):
866
+ module.weight.data.normal_(mean=0.0, std=std)
867
+ if module.padding_idx is not None:
868
+ module.weight.data[module.padding_idx].zero_()
869
+
870
+
871
+ PHI_INPUTS_DOCSTRING = r"""
872
+ Args:
873
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
874
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
875
+ it.
876
+
877
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
878
+ [`PreTrainedTokenizer.__call__`] for details.
879
+
880
+ [What are input IDs?](../glossary#input-ids)
881
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
882
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
883
+
884
+ - 1 for tokens that are **not masked**,
885
+ - 0 for tokens that are **masked**.
886
+
887
+ [What are attention masks?](../glossary#attention-mask)
888
+
889
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
890
+ [`PreTrainedTokenizer.__call__`] for details.
891
+
892
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
893
+ `past_key_values`).
894
+
895
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
896
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
897
+ information on the default strategy.
898
+
899
+ - 1 indicates the head is **not masked**,
900
+ - 0 indicates the head is **masked**.
901
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
902
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
903
+ config.n_positions - 1]`.
904
+
905
+ [What are position IDs?](../glossary#position-ids)
906
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
907
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
908
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
909
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
910
+
911
+ Two formats are allowed:
912
+ - a [`~cache_utils.Cache`] instance;
913
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
914
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
915
+ cache format.
916
+
917
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
918
+ legacy cache format will be returned.
919
+
920
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
921
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
922
+ of shape `(batch_size, sequence_length)`.
923
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
924
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
925
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
926
+ model's internal embedding lookup matrix.
927
+ use_cache (`bool`, *optional*):
928
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
929
+ `past_key_values`).
930
+ output_attentions (`bool`, *optional*):
931
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
932
+ tensors for more detail.
933
+ output_hidden_states (`bool`, *optional*):
934
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
935
+ more detail.
936
+ return_dict (`bool`, *optional*):
937
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
938
+ """
939
+
940
+
941
+ @add_start_docstrings(
942
+ "The bare Phi Model outputting raw hidden-states without any specific head on top.",
943
+ PHI_START_DOCSTRING,
944
+ )
945
+ class PhiModel(PhiPreTrainedModel):
946
+ """
947
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
948
+
949
+ Args:
950
+ config: PhiConfig
951
+ """
952
+
953
+ def __init__(self, config: PhiConfig):
954
+ super().__init__(config)
955
+ self.padding_idx = config.pad_token_id
956
+ self.vocab_size = config.vocab_size
957
+
958
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
959
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
960
+ self.layers = nn.ModuleList(
961
+ [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
962
+ )
963
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
964
+
965
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
966
+ self._use_sdpa = config._attn_implementation == "sdpa"
967
+
968
+ self.gradient_checkpointing = False
969
+ # Initialize weights and apply final processing
970
+ self.post_init()
971
+
972
+ def get_input_embeddings(self):
973
+ return self.embed_tokens
974
+
975
+ def set_input_embeddings(self, value):
976
+ self.embed_tokens = value
977
+
978
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
979
+ def forward(
980
+ self,
981
+ input_ids: torch.LongTensor = None,
982
+ attention_mask: Optional[torch.Tensor] = None,
983
+ position_ids: Optional[torch.LongTensor] = None,
984
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
985
+ inputs_embeds: Optional[torch.FloatTensor] = None,
986
+ use_cache: Optional[bool] = None,
987
+ output_attentions: Optional[bool] = None,
988
+ output_hidden_states: Optional[bool] = None,
989
+ return_dict: Optional[bool] = None,
990
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
991
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
992
+ output_hidden_states = (
993
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
994
+ )
995
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
996
+
997
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
998
+
999
+ # retrieve input_ids and inputs_embeds
1000
+ if input_ids is not None and inputs_embeds is not None:
1001
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1002
+ elif input_ids is not None:
1003
+ batch_size, seq_length = input_ids.shape[:2]
1004
+ elif inputs_embeds is not None:
1005
+ batch_size, seq_length = inputs_embeds.shape[:2]
1006
+ else:
1007
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1008
+
1009
+ past_key_values_length = 0
1010
+
1011
+ if self.gradient_checkpointing and self.training:
1012
+ if use_cache:
1013
+ logger.warning_once(
1014
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1015
+ )
1016
+ use_cache = False
1017
+
1018
+ if use_cache:
1019
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1020
+ if use_legacy_cache:
1021
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1022
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1023
+
1024
+ if position_ids is None:
1025
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1026
+ position_ids = torch.arange(
1027
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1028
+ )
1029
+ position_ids = position_ids.unsqueeze(0)
1030
+
1031
+ if inputs_embeds is None:
1032
+ inputs_embeds = self.embed_tokens(input_ids)
1033
+
1034
+ inputs_embeds = self.embed_dropout(inputs_embeds)
1035
+
1036
+ # Attention mask.
1037
+ if self._use_flash_attention_2:
1038
+ # 2d mask is passed through the layers
1039
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1040
+ elif self._use_sdpa and not output_attentions:
1041
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1042
+ attention_mask,
1043
+ (batch_size, seq_length),
1044
+ inputs_embeds,
1045
+ past_key_values_length,
1046
+ )
1047
+ else:
1048
+ # 4d mask is passed through the layers
1049
+ attention_mask = _prepare_4d_causal_attention_mask(
1050
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1051
+ )
1052
+
1053
+ hidden_states = inputs_embeds
1054
+
1055
+ # decoder layers
1056
+ all_hidden_states = () if output_hidden_states else None
1057
+ all_self_attns = () if output_attentions else None
1058
+ next_decoder_cache = None
1059
+
1060
+ for decoder_layer in self.layers:
1061
+ if output_hidden_states:
1062
+ all_hidden_states += (hidden_states,)
1063
+
1064
+ if self.gradient_checkpointing and self.training:
1065
+ layer_outputs = self._gradient_checkpointing_func(
1066
+ decoder_layer.__call__,
1067
+ hidden_states,
1068
+ attention_mask,
1069
+ position_ids,
1070
+ past_key_values,
1071
+ output_attentions,
1072
+ )
1073
+ else:
1074
+ layer_outputs = decoder_layer(
1075
+ hidden_states,
1076
+ attention_mask=attention_mask,
1077
+ position_ids=position_ids,
1078
+ past_key_value=past_key_values,
1079
+ output_attentions=output_attentions,
1080
+ use_cache=use_cache,
1081
+ )
1082
+
1083
+ hidden_states = layer_outputs[0]
1084
+
1085
+ if use_cache:
1086
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1087
+
1088
+ if output_attentions:
1089
+ all_self_attns += (layer_outputs[1],)
1090
+
1091
+ hidden_states = self.final_layernorm(hidden_states)
1092
+
1093
+ # add hidden states from the last decoder layer
1094
+ if output_hidden_states:
1095
+ all_hidden_states += (hidden_states,)
1096
+
1097
+ next_cache = None
1098
+ if use_cache:
1099
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1100
+ if not return_dict:
1101
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1102
+ return BaseModelOutputWithPast(
1103
+ last_hidden_state=hidden_states,
1104
+ past_key_values=next_cache,
1105
+ hidden_states=all_hidden_states,
1106
+ attentions=all_self_attns,
1107
+ )
1108
+
1109
+
1110
+ class PhiForCausalLM(PhiPreTrainedModel):
1111
+ _tied_weights_keys = ["lm_head.weight"]
1112
+
1113
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
1114
+ def __init__(self, config):
1115
+ super().__init__(config)
1116
+ self.model = PhiModel(config)
1117
+ self.vocab_size = config.vocab_size
1118
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
1119
+
1120
+ # Initialize weights and apply final processing
1121
+ self.post_init()
1122
+
1123
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1124
+ def get_input_embeddings(self):
1125
+ return self.model.embed_tokens
1126
+
1127
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1128
+ def set_input_embeddings(self, value):
1129
+ self.model.embed_tokens = value
1130
+
1131
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1132
+ def get_output_embeddings(self):
1133
+ return self.lm_head
1134
+
1135
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1136
+ def set_output_embeddings(self, new_embeddings):
1137
+ self.lm_head = new_embeddings
1138
+
1139
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1140
+ def set_decoder(self, decoder):
1141
+ self.model = decoder
1142
+
1143
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1144
+ def get_decoder(self):
1145
+ return self.model
1146
+
1147
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1148
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1149
+ def forward(
1150
+ self,
1151
+ input_ids: torch.LongTensor = None,
1152
+ attention_mask: Optional[torch.Tensor] = None,
1153
+ position_ids: Optional[torch.LongTensor] = None,
1154
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1155
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1156
+ labels: Optional[torch.LongTensor] = None,
1157
+ use_cache: Optional[bool] = None,
1158
+ output_attentions: Optional[bool] = None,
1159
+ output_hidden_states: Optional[bool] = None,
1160
+ return_dict: Optional[bool] = None,
1161
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1162
+ r"""
1163
+ Args:
1164
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1165
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1166
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1167
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1168
+
1169
+ Returns:
1170
+
1171
+ Example:
1172
+
1173
+ ```python
1174
+ >>> from transformers import AutoTokenizer, PhiForCausalLM
1175
+
1176
+ >>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
1177
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
1178
+
1179
+ >>> prompt = "This is an example script ."
1180
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1181
+
1182
+ >>> # Generate
1183
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1184
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1185
+ 'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
1186
+ ```"""
1187
+
1188
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1189
+ output_hidden_states = (
1190
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1191
+ )
1192
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1193
+
1194
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1195
+ outputs = self.model(
1196
+ input_ids=input_ids,
1197
+ attention_mask=attention_mask,
1198
+ position_ids=position_ids,
1199
+ past_key_values=past_key_values,
1200
+ inputs_embeds=inputs_embeds,
1201
+ use_cache=use_cache,
1202
+ output_attentions=output_attentions,
1203
+ output_hidden_states=output_hidden_states,
1204
+ return_dict=return_dict,
1205
+ )
1206
+
1207
+ hidden_states = outputs[0]
1208
+ logits = self.lm_head(hidden_states)
1209
+ logits = logits.float()
1210
+
1211
+ loss = None
1212
+ if labels is not None:
1213
+ # Shift so that tokens < n predict n
1214
+ shift_logits = logits[..., :-1, :].contiguous()
1215
+ shift_labels = labels[..., 1:].contiguous()
1216
+ # Flatten the tokens
1217
+ loss_fct = CrossEntropyLoss()
1218
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1219
+ shift_labels = shift_labels.view(-1)
1220
+ # Enable model parallelism
1221
+ shift_labels = shift_labels.to(shift_logits.device)
1222
+ loss = loss_fct(shift_logits, shift_labels)
1223
+
1224
+ if not return_dict:
1225
+ output = (logits,) + outputs[1:]
1226
+ return (loss,) + output if loss is not None else output
1227
+
1228
+ return CausalLMOutputWithPast(
1229
+ loss=loss,
1230
+ logits=logits,
1231
+ past_key_values=outputs.past_key_values,
1232
+ hidden_states=outputs.hidden_states,
1233
+ attentions=outputs.attentions,
1234
+ )
1235
+
1236
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1237
+ def prepare_inputs_for_generation(
1238
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1239
+ ):
1240
+ if past_key_values is not None:
1241
+ if isinstance(past_key_values, Cache):
1242
+ cache_length = past_key_values.get_seq_length()
1243
+ past_length = past_key_values.seen_tokens
1244
+ max_cache_length = past_key_values.get_max_length()
1245
+ else:
1246
+ cache_length = past_length = past_key_values[0][0].shape[2]
1247
+ max_cache_length = None
1248
+
1249
+ # Keep only the unprocessed tokens:
1250
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1251
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1252
+ # input)
1253
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1254
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1255
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1256
+ # input_ids based on the past_length.
1257
+ elif past_length < input_ids.shape[1]:
1258
+ input_ids = input_ids[:, past_length:]
1259
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1260
+
1261
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1262
+ if (
1263
+ max_cache_length is not None
1264
+ and attention_mask is not None
1265
+ and cache_length + input_ids.shape[1] > max_cache_length
1266
+ ):
1267
+ attention_mask = attention_mask[:, -max_cache_length:]
1268
+
1269
+ position_ids = kwargs.get("position_ids", None)
1270
+ if attention_mask is not None and position_ids is None:
1271
+ # create position_ids on the fly for batch generation
1272
+ position_ids = attention_mask.long().cumsum(-1) - 1
1273
+ position_ids.masked_fill_(attention_mask == 0, 1)
1274
+ if past_key_values:
1275
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1276
+
1277
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1278
+ if inputs_embeds is not None and past_key_values is None:
1279
+ model_inputs = {"inputs_embeds": inputs_embeds}
1280
+ else:
1281
+ model_inputs = {"input_ids": input_ids}
1282
+
1283
+ model_inputs.update(
1284
+ {
1285
+ "position_ids": position_ids,
1286
+ "past_key_values": past_key_values,
1287
+ "use_cache": kwargs.get("use_cache"),
1288
+ "attention_mask": attention_mask,
1289
+ }
1290
+ )
1291
+ return model_inputs
1292
+
1293
+ @staticmethod
1294
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1295
+ def _reorder_cache(past_key_values, beam_idx):
1296
+ reordered_past = ()
1297
+ for layer_past in past_key_values:
1298
+ reordered_past += (
1299
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1300
+ )
1301
+ return reordered_past
1302
+
1303
+
1304
+ @add_start_docstrings(
1305
+ """
1306
+ The PhiModel with a sequence classification head on top (linear layer).
1307
+
1308
+ [`PhiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1309
+ (e.g. GPT-2) do.
1310
+
1311
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1312
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1313
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1314
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1315
+ each row of the batch).
1316
+ """,
1317
+ PHI_START_DOCSTRING,
1318
+ )
1319
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->PHI,Llama->Phi with self.transformer->self.model, transformer_outputs->model_outputs
1320
+ class PhiForSequenceClassification(PhiPreTrainedModel):
1321
+ def __init__(self, config):
1322
+ super().__init__(config)
1323
+ self.num_labels = config.num_labels
1324
+ self.model = PhiModel(config)
1325
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1326
+
1327
+ # Initialize weights and apply final processing
1328
+ self.post_init()
1329
+
1330
+ def get_input_embeddings(self):
1331
+ return self.model.embed_tokens
1332
+
1333
+ def set_input_embeddings(self, value):
1334
+ self.model.embed_tokens = value
1335
+
1336
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1337
+ def forward(
1338
+ self,
1339
+ input_ids: torch.LongTensor = None,
1340
+ attention_mask: Optional[torch.Tensor] = None,
1341
+ position_ids: Optional[torch.LongTensor] = None,
1342
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1343
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1344
+ labels: Optional[torch.LongTensor] = None,
1345
+ use_cache: Optional[bool] = None,
1346
+ output_attentions: Optional[bool] = None,
1347
+ output_hidden_states: Optional[bool] = None,
1348
+ return_dict: Optional[bool] = None,
1349
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1350
+ r"""
1351
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1352
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1353
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1354
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1355
+ """
1356
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1357
+
1358
+ model_outputs = self.model(
1359
+ input_ids,
1360
+ attention_mask=attention_mask,
1361
+ position_ids=position_ids,
1362
+ past_key_values=past_key_values,
1363
+ inputs_embeds=inputs_embeds,
1364
+ use_cache=use_cache,
1365
+ output_attentions=output_attentions,
1366
+ output_hidden_states=output_hidden_states,
1367
+ return_dict=return_dict,
1368
+ )
1369
+ hidden_states = model_outputs[0]
1370
+ logits = self.score(hidden_states)
1371
+
1372
+ if input_ids is not None:
1373
+ batch_size = input_ids.shape[0]
1374
+ else:
1375
+ batch_size = inputs_embeds.shape[0]
1376
+
1377
+ if self.config.pad_token_id is None and batch_size != 1:
1378
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1379
+ if self.config.pad_token_id is None:
1380
+ sequence_lengths = -1
1381
+ else:
1382
+ if input_ids is not None:
1383
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1384
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1385
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1386
+ sequence_lengths = sequence_lengths.to(logits.device)
1387
+ else:
1388
+ sequence_lengths = -1
1389
+
1390
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1391
+
1392
+ loss = None
1393
+ if labels is not None:
1394
+ labels = labels.to(logits.device)
1395
+ if self.config.problem_type is None:
1396
+ if self.num_labels == 1:
1397
+ self.config.problem_type = "regression"
1398
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1399
+ self.config.problem_type = "single_label_classification"
1400
+ else:
1401
+ self.config.problem_type = "multi_label_classification"
1402
+
1403
+ if self.config.problem_type == "regression":
1404
+ loss_fct = MSELoss()
1405
+ if self.num_labels == 1:
1406
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1407
+ else:
1408
+ loss = loss_fct(pooled_logits, labels)
1409
+ elif self.config.problem_type == "single_label_classification":
1410
+ loss_fct = CrossEntropyLoss()
1411
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1412
+ elif self.config.problem_type == "multi_label_classification":
1413
+ loss_fct = BCEWithLogitsLoss()
1414
+ loss = loss_fct(pooled_logits, labels)
1415
+ if not return_dict:
1416
+ output = (pooled_logits,) + model_outputs[1:]
1417
+ return ((loss,) + output) if loss is not None else output
1418
+
1419
+ return SequenceClassifierOutputWithPast(
1420
+ loss=loss,
1421
+ logits=pooled_logits,
1422
+ past_key_values=model_outputs.past_key_values,
1423
+ hidden_states=model_outputs.hidden_states,
1424
+ attentions=model_outputs.attentions,
1425
+ )
1426
+
1427
+
1428
+ @add_start_docstrings(
1429
+ """
1430
+ PhiModel with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1431
+ Named-Entity-Recognition (NER) tasks.
1432
+ """,
1433
+ PHI_START_DOCSTRING,
1434
+ )
1435
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with MPT->PHI,Mpt->Phi,self.transformer->self.model,transformer_outputs->model_outputs
1436
+ class PhiForTokenClassification(PhiPreTrainedModel):
1437
+ def __init__(self, config: PhiConfig):
1438
+ super().__init__(config)
1439
+ self.num_labels = config.num_labels
1440
+
1441
+ self.model = PhiModel(config)
1442
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1443
+ classifier_dropout = config.classifier_dropout
1444
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1445
+ classifier_dropout = config.hidden_dropout
1446
+ else:
1447
+ classifier_dropout = 0.1
1448
+ self.dropout = nn.Dropout(classifier_dropout)
1449
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1450
+
1451
+ # Initialize weights and apply final processing
1452
+ self.post_init()
1453
+
1454
+ @add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
1455
+ @add_code_sample_docstrings(
1456
+ checkpoint=_CHECKPOINT_FOR_DOC,
1457
+ output_type=TokenClassifierOutput,
1458
+ config_class=_CONFIG_FOR_DOC,
1459
+ )
1460
+ def forward(
1461
+ self,
1462
+ input_ids: Optional[torch.LongTensor] = None,
1463
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1464
+ attention_mask: Optional[torch.Tensor] = None,
1465
+ inputs_embeds: Optional[torch.Tensor] = None,
1466
+ labels: Optional[torch.Tensor] = None,
1467
+ use_cache: Optional[bool] = None,
1468
+ output_attentions: Optional[bool] = None,
1469
+ output_hidden_states: Optional[bool] = None,
1470
+ return_dict: Optional[bool] = None,
1471
+ **deprecated_arguments,
1472
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1473
+ r"""
1474
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1475
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1476
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1477
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1478
+ """
1479
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1480
+
1481
+ model_outputs = self.model(
1482
+ input_ids,
1483
+ past_key_values=past_key_values,
1484
+ attention_mask=attention_mask,
1485
+ inputs_embeds=inputs_embeds,
1486
+ use_cache=use_cache,
1487
+ output_attentions=output_attentions,
1488
+ output_hidden_states=output_hidden_states,
1489
+ return_dict=return_dict,
1490
+ )
1491
+
1492
+ hidden_states = model_outputs[0]
1493
+ hidden_states = self.dropout(hidden_states)
1494
+ logits = self.classifier(hidden_states)
1495
+
1496
+ loss = None
1497
+ if labels is not None:
1498
+ # move labels to correct device to enable model parallelism
1499
+ labels = labels.to(logits.device)
1500
+ batch_size, seq_length = labels.shape
1501
+ loss_fct = CrossEntropyLoss()
1502
+ loss = loss_fct(
1503
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1504
+ )
1505
+
1506
+ if not return_dict:
1507
+ output = (logits,) + model_outputs[2:]
1508
+ return ((loss,) + output) if loss is not None else output
1509
+
1510
+ return TokenClassifierOutput(
1511
+ loss=loss,
1512
+ logits=logits,
1513
+ hidden_states=model_outputs.hidden_states,
1514
+ attentions=model_outputs.attentions,
1515
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "<|endoftext|>",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "50256": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "50257": {
13
+ "content": " ",
14
+ "lstrip": false,
15
+ "normalized": true,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": false
19
+ },
20
+ "50258": {
21
+ "content": " ",
22
+ "lstrip": false,
23
+ "normalized": true,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": false
27
+ },
28
+ "50259": {
29
+ "content": " ",
30
+ "lstrip": false,
31
+ "normalized": true,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": false
35
+ },
36
+ "50260": {
37
+ "content": " ",
38
+ "lstrip": false,
39
+ "normalized": true,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": false
43
+ },
44
+ "50261": {
45
+ "content": " ",
46
+ "lstrip": false,
47
+ "normalized": true,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": false
51
+ },
52
+ "50262": {
53
+ "content": " ",
54
+ "lstrip": false,
55
+ "normalized": true,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": false
59
+ },
60
+ "50263": {
61
+ "content": " ",
62
+ "lstrip": false,
63
+ "normalized": true,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": false
67
+ },
68
+ "50264": {
69
+ "content": " ",
70
+ "lstrip": false,
71
+ "normalized": true,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": false
75
+ },
76
+ "50265": {
77
+ "content": " ",
78
+ "lstrip": false,
79
+ "normalized": true,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": false
83
+ },
84
+ "50266": {
85
+ "content": " ",
86
+ "lstrip": false,
87
+ "normalized": true,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": false
91
+ },
92
+ "50267": {
93
+ "content": " ",
94
+ "lstrip": false,
95
+ "normalized": true,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": false
99
+ },
100
+ "50268": {
101
+ "content": " ",
102
+ "lstrip": false,
103
+ "normalized": true,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": false
107
+ },
108
+ "50269": {
109
+ "content": " ",
110
+ "lstrip": false,
111
+ "normalized": true,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": false
115
+ },
116
+ "50270": {
117
+ "content": " ",
118
+ "lstrip": false,
119
+ "normalized": true,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": false
123
+ },
124
+ "50271": {
125
+ "content": " ",
126
+ "lstrip": false,
127
+ "normalized": true,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": false
131
+ },
132
+ "50272": {
133
+ "content": " ",
134
+ "lstrip": false,
135
+ "normalized": true,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": false
139
+ },
140
+ "50273": {
141
+ "content": " ",
142
+ "lstrip": false,
143
+ "normalized": true,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": false
147
+ },
148
+ "50274": {
149
+ "content": " ",
150
+ "lstrip": false,
151
+ "normalized": true,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": false
155
+ },
156
+ "50275": {
157
+ "content": " ",
158
+ "lstrip": false,
159
+ "normalized": true,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": false
163
+ },
164
+ "50276": {
165
+ "content": " ",
166
+ "lstrip": false,
167
+ "normalized": true,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": false
171
+ },
172
+ "50277": {
173
+ "content": " ",
174
+ "lstrip": false,
175
+ "normalized": true,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": false
179
+ },
180
+ "50278": {
181
+ "content": " ",
182
+ "lstrip": false,
183
+ "normalized": true,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": false
187
+ },
188
+ "50279": {
189
+ "content": " ",
190
+ "lstrip": false,
191
+ "normalized": true,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": false
195
+ },
196
+ "50280": {
197
+ "content": " ",
198
+ "lstrip": false,
199
+ "normalized": true,
200
+ "rstrip": false,
201
+ "single_word": false,
202
+ "special": false
203
+ },
204
+ "50281": {
205
+ "content": " ",
206
+ "lstrip": false,
207
+ "normalized": true,
208
+ "rstrip": false,
209
+ "single_word": false,
210
+ "special": false
211
+ },
212
+ "50282": {
213
+ "content": " ",
214
+ "lstrip": false,
215
+ "normalized": true,
216
+ "rstrip": false,
217
+ "single_word": false,
218
+ "special": false
219
+ },
220
+ "50283": {
221
+ "content": " ",
222
+ "lstrip": false,
223
+ "normalized": true,
224
+ "rstrip": false,
225
+ "single_word": false,
226
+ "special": false
227
+ },
228
+ "50284": {
229
+ "content": " ",
230
+ "lstrip": false,
231
+ "normalized": true,
232
+ "rstrip": false,
233
+ "single_word": false,
234
+ "special": false
235
+ },
236
+ "50285": {
237
+ "content": " ",
238
+ "lstrip": false,
239
+ "normalized": true,
240
+ "rstrip": false,
241
+ "single_word": false,
242
+ "special": false
243
+ },
244
+ "50286": {
245
+ "content": " ",
246
+ "lstrip": false,
247
+ "normalized": true,
248
+ "rstrip": false,
249
+ "single_word": false,
250
+ "special": false
251
+ },
252
+ "50287": {
253
+ "content": "\t\t\t\t\t\t\t\t\t",
254
+ "lstrip": false,
255
+ "normalized": true,
256
+ "rstrip": false,
257
+ "single_word": false,
258
+ "special": false
259
+ },
260
+ "50288": {
261
+ "content": "\t\t\t\t\t\t\t\t",
262
+ "lstrip": false,
263
+ "normalized": true,
264
+ "rstrip": false,
265
+ "single_word": false,
266
+ "special": false
267
+ },
268
+ "50289": {
269
+ "content": "\t\t\t\t\t\t\t",
270
+ "lstrip": false,
271
+ "normalized": true,
272
+ "rstrip": false,
273
+ "single_word": false,
274
+ "special": false
275
+ },
276
+ "50290": {
277
+ "content": "\t\t\t\t\t\t",
278
+ "lstrip": false,
279
+ "normalized": true,
280
+ "rstrip": false,
281
+ "single_word": false,
282
+ "special": false
283
+ },
284
+ "50291": {
285
+ "content": "\t\t\t\t\t",
286
+ "lstrip": false,
287
+ "normalized": true,
288
+ "rstrip": false,
289
+ "single_word": false,
290
+ "special": false
291
+ },
292
+ "50292": {
293
+ "content": "\t\t\t\t",
294
+ "lstrip": false,
295
+ "normalized": true,
296
+ "rstrip": false,
297
+ "single_word": false,
298
+ "special": false
299
+ },
300
+ "50293": {
301
+ "content": "\t\t\t",
302
+ "lstrip": false,
303
+ "normalized": true,
304
+ "rstrip": false,
305
+ "single_word": false,
306
+ "special": false
307
+ },
308
+ "50294": {
309
+ "content": "\t\t",
310
+ "lstrip": false,
311
+ "normalized": true,
312
+ "rstrip": false,
313
+ "single_word": false,
314
+ "special": false
315
+ }
316
+ },
317
+ "bos_token": "<|endoftext|>",
318
+ "clean_up_tokenization_spaces": true,
319
+ "eos_token": "<|endoftext|>",
320
+ "model_max_length": 2048,
321
+ "pad_token": "<|endoftext|>",
322
+ "return_token_type_ids": false,
323
+ "tokenizer_class": "CodeGenTokenizer",
324
+ "unk_token": "<|endoftext|>"
325
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff