Upload 8 files
Browse files- README.md +6 -25
- config.json +18 -16
- configuration_phi.py +181 -50
- generation_config.json +1 -1
- model-00001-of-00002.safetensors +2 -2
- model-00002-of-00002.safetensors +2 -2
- model.safetensors.index.json +453 -325
- modeling_phi.py +1174 -770
README.md
CHANGED
@@ -33,6 +33,7 @@ To encourage the model to write more concise answers, you can also try the follo
|
|
33 |
Instruct: Write a detailed analogy between mathematics and a lighthouse.
|
34 |
Output: Mathematics is like a lighthouse. Just as a lighthouse guides ships safely to shore, mathematics provides a guiding light in the world of numbers and logic. It helps us navigate through complex problems and find solutions. Just as a lighthouse emits a steady beam of light, mathematics provides a consistent framework for reasoning and problem-solving. It illuminates the path to understanding and helps us make sense of the world around us.
|
35 |
```
|
|
|
36 |
where the model generates the text after "Output:".
|
37 |
|
38 |
### Chat Format:
|
@@ -65,35 +66,18 @@ def print_prime(n):
|
|
65 |
primes.append(num)
|
66 |
print(primes)
|
67 |
```
|
|
|
68 |
where the model generates the text after the comments.
|
69 |
|
70 |
**Notes:**
|
|
|
71 |
* Phi-2 is intended for QA, chat, and code purposes. The model-generated text/code should be treated as a starting point rather than a definitive solution for potential use cases. Users should be cautious when employing these models in their applications.
|
|
|
72 |
* Direct adoption for production tasks without evaluation is out of scope of this project. As a result, the Phi-2 model has not been tested to ensure that it performs adequately for any production-level application. Please refer to the limitation sections of this document for more details.
|
73 |
-
* If you are using `transformers>=4.36.0`, always load the model with `trust_remote_code=True` to prevent side-effects.
|
74 |
|
75 |
-
|
76 |
|
77 |
-
|
78 |
-
|
79 |
-
1. FP16 / Flash-Attention / CUDA:
|
80 |
-
```python
|
81 |
-
model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype="auto", flash_attn=True, flash_rotary=True, fused_dense=True, device_map="cuda", trust_remote_code=True)
|
82 |
-
```
|
83 |
-
2. FP16 / CUDA:
|
84 |
-
```python
|
85 |
-
model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype="auto", device_map="cuda", trust_remote_code=True)
|
86 |
-
```
|
87 |
-
3. FP32 / CUDA:
|
88 |
-
```python
|
89 |
-
model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype=torch.float32, device_map="cuda", trust_remote_code=True)
|
90 |
-
```
|
91 |
-
4. FP32 / CPU:
|
92 |
-
```python
|
93 |
-
model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype=torch.float32, device_map="cpu", trust_remote_code=True)
|
94 |
-
```
|
95 |
-
|
96 |
-
To ensure the maximum compatibility, we recommend using the second execution mode (FP16 / CUDA), as follows:
|
97 |
|
98 |
```python
|
99 |
import torch
|
@@ -114,9 +98,6 @@ text = tokenizer.batch_decode(outputs)[0]
|
|
114 |
print(text)
|
115 |
```
|
116 |
|
117 |
-
**Remark:** In the generation function, our model currently does not support beam search (`num_beams > 1`).
|
118 |
-
Furthermore, in the forward pass of the model, we currently do not support outputting hidden states or attention values, or using custom input embeddings.
|
119 |
-
|
120 |
## Limitations of Phi-2
|
121 |
|
122 |
* Generate Inaccurate Code and Facts: The model may produce incorrect code snippets and statements. Users should treat these outputs as suggestions or starting points, not as definitive or accurate solutions.
|
|
|
33 |
Instruct: Write a detailed analogy between mathematics and a lighthouse.
|
34 |
Output: Mathematics is like a lighthouse. Just as a lighthouse guides ships safely to shore, mathematics provides a guiding light in the world of numbers and logic. It helps us navigate through complex problems and find solutions. Just as a lighthouse emits a steady beam of light, mathematics provides a consistent framework for reasoning and problem-solving. It illuminates the path to understanding and helps us make sense of the world around us.
|
35 |
```
|
36 |
+
|
37 |
where the model generates the text after "Output:".
|
38 |
|
39 |
### Chat Format:
|
|
|
66 |
primes.append(num)
|
67 |
print(primes)
|
68 |
```
|
69 |
+
|
70 |
where the model generates the text after the comments.
|
71 |
|
72 |
**Notes:**
|
73 |
+
|
74 |
* Phi-2 is intended for QA, chat, and code purposes. The model-generated text/code should be treated as a starting point rather than a definitive solution for potential use cases. Users should be cautious when employing these models in their applications.
|
75 |
+
|
76 |
* Direct adoption for production tasks without evaluation is out of scope of this project. As a result, the Phi-2 model has not been tested to ensure that it performs adequately for any production-level application. Please refer to the limitation sections of this document for more details.
|
|
|
77 |
|
78 |
+
* If you are using `transformers<4.37.0`, always load the model with `trust_remote_code=True` to prevent side-effects.
|
79 |
|
80 |
+
## Sample Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
|
82 |
```python
|
83 |
import torch
|
|
|
98 |
print(text)
|
99 |
```
|
100 |
|
|
|
|
|
|
|
101 |
## Limitations of Phi-2
|
102 |
|
103 |
* Generate Inaccurate Code and Facts: The model may produce incorrect code snippets and statements. Users should treat these outputs as suggestions or starting points, not as definitive or accurate solutions.
|
config.json
CHANGED
@@ -1,32 +1,34 @@
|
|
1 |
{
|
2 |
"_name_or_path": "microsoft/phi-2",
|
3 |
-
"activation_function": "gelu_new",
|
4 |
"architectures": [
|
5 |
"PhiForCausalLM"
|
6 |
],
|
7 |
-
"attn_pdrop": 0.0,
|
8 |
"auto_map": {
|
9 |
"AutoConfig": "configuration_phi.PhiConfig",
|
10 |
"AutoModelForCausalLM": "modeling_phi.PhiForCausalLM"
|
11 |
},
|
|
|
|
|
12 |
"embd_pdrop": 0.0,
|
13 |
-
"
|
14 |
-
"
|
15 |
-
"
|
16 |
-
"img_processor": null,
|
17 |
"initializer_range": 0.02,
|
18 |
-
"
|
19 |
-
"
|
20 |
-
"
|
21 |
-
"
|
22 |
-
"
|
23 |
-
"
|
24 |
-
"
|
25 |
-
"
|
|
|
26 |
"resid_pdrop": 0.1,
|
27 |
-
"
|
|
|
28 |
"tie_word_embeddings": false,
|
29 |
"torch_dtype": "float16",
|
30 |
-
"transformers_version": "4.
|
|
|
31 |
"vocab_size": 51200
|
32 |
}
|
|
|
1 |
{
|
2 |
"_name_or_path": "microsoft/phi-2",
|
|
|
3 |
"architectures": [
|
4 |
"PhiForCausalLM"
|
5 |
],
|
|
|
6 |
"auto_map": {
|
7 |
"AutoConfig": "configuration_phi.PhiConfig",
|
8 |
"AutoModelForCausalLM": "modeling_phi.PhiForCausalLM"
|
9 |
},
|
10 |
+
"attention_dropout": 0.0,
|
11 |
+
"bos_token_id": null,
|
12 |
"embd_pdrop": 0.0,
|
13 |
+
"eos_token_id": null,
|
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_hidden_layers": 32,
|
23 |
+
"num_key_value_heads": 32,
|
24 |
+
"partial_rotary_factor": 0.4,
|
25 |
+
"qk_layernorm": false,
|
26 |
"resid_pdrop": 0.1,
|
27 |
+
"rope_scaling": null,
|
28 |
+
"rope_theta": 10000.0,
|
29 |
"tie_word_embeddings": false,
|
30 |
"torch_dtype": "float16",
|
31 |
+
"transformers_version": "4.37.0.dev0",
|
32 |
+
"use_cache": true,
|
33 |
"vocab_size": 51200
|
34 |
}
|
configuration_phi.py
CHANGED
@@ -1,62 +1,193 @@
|
|
1 |
-
#
|
2 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
from typing import Optional
|
6 |
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
|
10 |
class PhiConfig(PretrainedConfig):
|
11 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
|
|
|
|
20 |
|
21 |
def __init__(
|
22 |
self,
|
23 |
-
vocab_size
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
self.
|
47 |
-
self.
|
48 |
-
self.
|
49 |
-
self.
|
50 |
-
self.
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
self.
|
56 |
-
self.attn_pdrop = attn_pdrop
|
57 |
-
self.embd_pdrop = embd_pdrop
|
58 |
self.resid_pdrop = resid_pdrop
|
59 |
-
self.
|
|
|
|
|
|
|
60 |
self.initializer_range = initializer_range
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
PHI_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
26 |
+
"microsoft/phi-2": "https://huggingface.co/microsoft/phi-2/resolve/main/config.json",
|
27 |
+
}
|
28 |
|
29 |
|
30 |
class PhiConfig(PretrainedConfig):
|
31 |
+
r"""
|
32 |
+
This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
|
33 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
34 |
+
defaults will yield a similar configuration to that of the Phi
|
35 |
+
[microsoft/phi-1](https://huggingface.co/microsoft/phi-1).
|
36 |
+
|
37 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
38 |
+
documentation from [`PretrainedConfig`] for more information.
|
39 |
+
|
40 |
+
Args:
|
41 |
+
vocab_size (`int`, *optional*, defaults to 51200):
|
42 |
+
Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
|
43 |
+
`inputs_ids` passed when calling [`PhiModel`].
|
44 |
+
hidden_size (`int`, *optional*, defaults to 2048):
|
45 |
+
Dimension of the hidden representations.
|
46 |
+
intermediate_size (`int`, *optional*, defaults to 8192):
|
47 |
+
Dimension of the MLP representations.
|
48 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
49 |
+
Number of hidden layers in the Transformer decoder.
|
50 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
51 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
52 |
+
num_key_value_heads (`int`, *optional*):
|
53 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
54 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
55 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
56 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
57 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
58 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
59 |
+
`num_attention_heads`.
|
60 |
+
resid_pdrop (`float`, *optional*, defaults to 0.0):
|
61 |
+
Dropout probability for mlp outputs.
|
62 |
+
embd_pdrop (`int`, *optional*, defaults to 0.0):
|
63 |
+
The dropout ratio for the embeddings.
|
64 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
65 |
+
The dropout ratio after computing the attention scores.
|
66 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
|
67 |
+
The non-linear activation function (function or string) in the decoder.
|
68 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
69 |
+
The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
|
70 |
+
tokens.
|
71 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
72 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
73 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
74 |
+
The epsilon used by the rms normalization layers.
|
75 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
76 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
77 |
+
relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
|
78 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
79 |
+
Whether to tie weight embeddings
|
80 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
81 |
+
The base period of the RoPE embeddings.
|
82 |
+
rope_scaling (`Dict`, *optional*):
|
83 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
84 |
+
strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
|
85 |
+
is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
86 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
87 |
+
these scaling strategies behave:
|
88 |
+
https://www.reddit.com/r/LocalPersimmon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This
|
89 |
+
is an experimental feature, subject to breaking API changes in future versions.
|
90 |
+
partial_rotary_factor (`float`, *optional*, defaults to 0.5):
|
91 |
+
Percentage of the query and keys which will have rotary embedding.
|
92 |
+
qk_layernorm (`bool`, *optional*, defaults to `False`):
|
93 |
+
Whether or not to normalize the Queries and Keys after projecting the hidden states.
|
94 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
95 |
+
Denotes beginning of sequences token id.
|
96 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
97 |
+
Denotes end of sequences token id.
|
98 |
+
|
99 |
+
Example:
|
100 |
+
|
101 |
+
```python
|
102 |
+
>>> from transformers import PhiModel, PhiConfig
|
103 |
+
|
104 |
+
>>> # Initializing a Phi-1 style configuration
|
105 |
+
>>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
|
106 |
|
107 |
+
>>> # Initializing a model from the configuration
|
108 |
+
>>> model = PhiModel(configuration)
|
109 |
+
|
110 |
+
>>> # Accessing the model configuration
|
111 |
+
>>> configuration = model.config
|
112 |
+
```"""
|
113 |
+
|
114 |
+
model_type = "phi"
|
115 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
116 |
|
117 |
def __init__(
|
118 |
self,
|
119 |
+
vocab_size=51200,
|
120 |
+
hidden_size=2048,
|
121 |
+
intermediate_size=8192,
|
122 |
+
num_hidden_layers=24,
|
123 |
+
num_attention_heads=32,
|
124 |
+
num_key_value_heads=None,
|
125 |
+
resid_pdrop=0.0,
|
126 |
+
embd_pdrop=0.0,
|
127 |
+
attention_dropout=0.0,
|
128 |
+
hidden_act="gelu_new",
|
129 |
+
max_position_embeddings=2048,
|
130 |
+
initializer_range=0.02,
|
131 |
+
layer_norm_eps=1e-5,
|
132 |
+
use_cache=True,
|
133 |
+
tie_word_embeddings=False,
|
134 |
+
rope_theta=10000.0,
|
135 |
+
rope_scaling=None,
|
136 |
+
partial_rotary_factor=0.5,
|
137 |
+
qk_layernorm=False,
|
138 |
+
bos_token_id=1,
|
139 |
+
eos_token_id=2,
|
140 |
+
**kwargs,
|
141 |
+
):
|
142 |
+
self.vocab_size = vocab_size
|
143 |
+
self.hidden_size = hidden_size
|
144 |
+
self.intermediate_size = intermediate_size
|
145 |
+
self.num_hidden_layers = num_hidden_layers
|
146 |
+
self.num_attention_heads = num_attention_heads
|
147 |
+
|
148 |
+
if num_key_value_heads is None:
|
149 |
+
num_key_value_heads = num_attention_heads
|
150 |
+
|
151 |
+
self.num_key_value_heads = num_key_value_heads
|
|
|
|
|
152 |
self.resid_pdrop = resid_pdrop
|
153 |
+
self.embd_pdrop = embd_pdrop
|
154 |
+
self.attention_dropout = attention_dropout
|
155 |
+
self.hidden_act = hidden_act
|
156 |
+
self.max_position_embeddings = max_position_embeddings
|
157 |
self.initializer_range = initializer_range
|
158 |
+
self.layer_norm_eps = layer_norm_eps
|
159 |
+
self.use_cache = use_cache
|
160 |
+
self.rope_theta = rope_theta
|
161 |
+
self.rope_scaling = rope_scaling
|
162 |
+
self.partial_rotary_factor = partial_rotary_factor
|
163 |
+
self.qk_layernorm = qk_layernorm
|
164 |
+
self._rope_scaling_validation()
|
165 |
+
|
166 |
+
super().__init__(
|
167 |
+
bos_token_id=bos_token_id,
|
168 |
+
eos_token_id=eos_token_id,
|
169 |
+
tie_word_embeddings=tie_word_embeddings,
|
170 |
+
**kwargs,
|
171 |
+
)
|
172 |
+
|
173 |
+
# Copied from transformers.models.llama.configuration_llama.LlamaConfig._rope_scaling_validation
|
174 |
+
def _rope_scaling_validation(self):
|
175 |
+
"""
|
176 |
+
Validate the `rope_scaling` configuration.
|
177 |
+
"""
|
178 |
+
if self.rope_scaling is None:
|
179 |
+
return
|
180 |
|
181 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
182 |
+
raise ValueError(
|
183 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
184 |
+
f"got {self.rope_scaling}"
|
185 |
+
)
|
186 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
187 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
188 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
189 |
+
raise ValueError(
|
190 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
191 |
+
)
|
192 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
193 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
generation_config.json
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
{
|
2 |
"_from_model_config": true,
|
3 |
-
"transformers_version": "4.
|
4 |
}
|
|
|
1 |
{
|
2 |
"_from_model_config": true,
|
3 |
+
"transformers_version": "4.37.0.dev0"
|
4 |
}
|
model-00001-of-00002.safetensors
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7fbcdefa72edf7527bf5da40535b57d9f5bd3d16829b94a9d25d2b457df62e84
|
3 |
+
size 4995584424
|
model-00002-of-00002.safetensors
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:17b98759e4b7953cbcf63ec49be7edbc9b863b57c207d84a52f5d2f5bcfcf6b4
|
3 |
+
size 563832976
|
model.safetensors.index.json
CHANGED
@@ -3,330 +3,458 @@
|
|
3 |
"total_size": 5559367680
|
4 |
},
|
5 |
"weight_map": {
|
6 |
-
"lm_head.
|
7 |
-
"lm_head.
|
8 |
-
"
|
9 |
-
"
|
10 |
-
"
|
11 |
-
"
|
12 |
-
"
|
13 |
-
"
|
14 |
-
"
|
15 |
-
"
|
16 |
-
"
|
17 |
-
"
|
18 |
-
"
|
19 |
-
"
|
20 |
-
"
|
21 |
-
"
|
22 |
-
"
|
23 |
-
"
|
24 |
-
"
|
25 |
-
"
|
26 |
-
"
|
27 |
-
"
|
28 |
-
"
|
29 |
-
"
|
30 |
-
"
|
31 |
-
"
|
32 |
-
"
|
33 |
-
"
|
34 |
-
"
|
35 |
-
"
|
36 |
-
"
|
37 |
-
"
|
38 |
-
"
|
39 |
-
"
|
40 |
-
"
|
41 |
-
"
|
42 |
-
"
|
43 |
-
"
|
44 |
-
"
|
45 |
-
"
|
46 |
-
"
|
47 |
-
"
|
48 |
-
"
|
49 |
-
"
|
50 |
-
"
|
51 |
-
"
|
52 |
-
"
|
53 |
-
"
|
54 |
-
"
|
55 |
-
"
|
56 |
-
"
|
57 |
-
"
|
58 |
-
"
|
59 |
-
"
|
60 |
-
"
|
61 |
-
"
|
62 |
-
"
|
63 |
-
"
|
64 |
-
"
|
65 |
-
"
|
66 |
-
"
|
67 |
-
"
|
68 |
-
"
|
69 |
-
"
|
70 |
-
"
|
71 |
-
"
|
72 |
-
"
|
73 |
-
"
|
74 |
-
"
|
75 |
-
"
|
76 |
-
"
|
77 |
-
"
|
78 |
-
"
|
79 |
-
"
|
80 |
-
"
|
81 |
-
"
|
82 |
-
"
|
83 |
-
"
|
84 |
-
"
|
85 |
-
"
|
86 |
-
"
|
87 |
-
"
|
88 |
-
"
|
89 |
-
"
|
90 |
-
"
|
91 |
-
"
|
92 |
-
"
|
93 |
-
"
|
94 |
-
"
|
95 |
-
"
|
96 |
-
"
|
97 |
-
"
|
98 |
-
"
|
99 |
-
"
|
100 |
-
"
|
101 |
-
"
|
102 |
-
"
|
103 |
-
"
|
104 |
-
"
|
105 |
-
"
|
106 |
-
"
|
107 |
-
"
|
108 |
-
"
|
109 |
-
"
|
110 |
-
"
|
111 |
-
"
|
112 |
-
"
|
113 |
-
"
|
114 |
-
"
|
115 |
-
"
|
116 |
-
"
|
117 |
-
"
|
118 |
-
"
|
119 |
-
"
|
120 |
-
"
|
121 |
-
"
|
122 |
-
"
|
123 |
-
"
|
124 |
-
"
|
125 |
-
"
|
126 |
-
"
|
127 |
-
"
|
128 |
-
"
|
129 |
-
"
|
130 |
-
"
|
131 |
-
"
|
132 |
-
"
|
133 |
-
"
|
134 |
-
"
|
135 |
-
"
|
136 |
-
"
|
137 |
-
"
|
138 |
-
"
|
139 |
-
"
|
140 |
-
"
|
141 |
-
"
|
142 |
-
"
|
143 |
-
"
|
144 |
-
"
|
145 |
-
"
|
146 |
-
"
|
147 |
-
"
|
148 |
-
"
|
149 |
-
"
|
150 |
-
"
|
151 |
-
"
|
152 |
-
"
|
153 |
-
"
|
154 |
-
"
|
155 |
-
"
|
156 |
-
"
|
157 |
-
"
|
158 |
-
"
|
159 |
-
"
|
160 |
-
"
|
161 |
-
"
|
162 |
-
"
|
163 |
-
"
|
164 |
-
"
|
165 |
-
"
|
166 |
-
"
|
167 |
-
"
|
168 |
-
"
|
169 |
-
"
|
170 |
-
"
|
171 |
-
"
|
172 |
-
"
|
173 |
-
"
|
174 |
-
"
|
175 |
-
"
|
176 |
-
"
|
177 |
-
"
|
178 |
-
"
|
179 |
-
"
|
180 |
-
"
|
181 |
-
"
|
182 |
-
"
|
183 |
-
"
|
184 |
-
"
|
185 |
-
"
|
186 |
-
"
|
187 |
-
"
|
188 |
-
"
|
189 |
-
"
|
190 |
-
"
|
191 |
-
"
|
192 |
-
"
|
193 |
-
"
|
194 |
-
"
|
195 |
-
"
|
196 |
-
"
|
197 |
-
"
|
198 |
-
"
|
199 |
-
"
|
200 |
-
"
|
201 |
-
"
|
202 |
-
"
|
203 |
-
"
|
204 |
-
"
|
205 |
-
"
|
206 |
-
"
|
207 |
-
"
|
208 |
-
"
|
209 |
-
"
|
210 |
-
"
|
211 |
-
"
|
212 |
-
"
|
213 |
-
"
|
214 |
-
"
|
215 |
-
"
|
216 |
-
"
|
217 |
-
"
|
218 |
-
"
|
219 |
-
"
|
220 |
-
"
|
221 |
-
"
|
222 |
-
"
|
223 |
-
"
|
224 |
-
"
|
225 |
-
"
|
226 |
-
"
|
227 |
-
"
|
228 |
-
"
|
229 |
-
"
|
230 |
-
"
|
231 |
-
"
|
232 |
-
"
|
233 |
-
"
|
234 |
-
"
|
235 |
-
"
|
236 |
-
"
|
237 |
-
"
|
238 |
-
"
|
239 |
-
"
|
240 |
-
"
|
241 |
-
"
|
242 |
-
"
|
243 |
-
"
|
244 |
-
"
|
245 |
-
"
|
246 |
-
"
|
247 |
-
"
|
248 |
-
"
|
249 |
-
"
|
250 |
-
"
|
251 |
-
"
|
252 |
-
"
|
253 |
-
"
|
254 |
-
"
|
255 |
-
"
|
256 |
-
"
|
257 |
-
"
|
258 |
-
"
|
259 |
-
"
|
260 |
-
"
|
261 |
-
"
|
262 |
-
"
|
263 |
-
"
|
264 |
-
"
|
265 |
-
"
|
266 |
-
"
|
267 |
-
"
|
268 |
-
"
|
269 |
-
"
|
270 |
-
"
|
271 |
-
"
|
272 |
-
"
|
273 |
-
"
|
274 |
-
"
|
275 |
-
"
|
276 |
-
"
|
277 |
-
"
|
278 |
-
"
|
279 |
-
"
|
280 |
-
"
|
281 |
-
"
|
282 |
-
"
|
283 |
-
"
|
284 |
-
"
|
285 |
-
"
|
286 |
-
"
|
287 |
-
"
|
288 |
-
"
|
289 |
-
"
|
290 |
-
"
|
291 |
-
"
|
292 |
-
"
|
293 |
-
"
|
294 |
-
"
|
295 |
-
"
|
296 |
-
"
|
297 |
-
"
|
298 |
-
"
|
299 |
-
"
|
300 |
-
"
|
301 |
-
"
|
302 |
-
"
|
303 |
-
"
|
304 |
-
"
|
305 |
-
"
|
306 |
-
"
|
307 |
-
"
|
308 |
-
"
|
309 |
-
"
|
310 |
-
"
|
311 |
-
"
|
312 |
-
"
|
313 |
-
"
|
314 |
-
"
|
315 |
-
"
|
316 |
-
"
|
317 |
-
"
|
318 |
-
"
|
319 |
-
"
|
320 |
-
"
|
321 |
-
"
|
322 |
-
"
|
323 |
-
"
|
324 |
-
"
|
325 |
-
"
|
326 |
-
"
|
327 |
-
"
|
328 |
-
"
|
329 |
-
"
|
330 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
331 |
}
|
332 |
}
|
|
|
3 |
"total_size": 5559367680
|
4 |
},
|
5 |
"weight_map": {
|
6 |
+
"lm_head.bias": "model-00002-of-00002.safetensors",
|
7 |
+
"lm_head.weight": "model-00002-of-00002.safetensors",
|
8 |
+
"model.embed_tokens.weight": "model-00001-of-00002.safetensors",
|
9 |
+
"model.final_layernorm.bias": "model-00002-of-00002.safetensors",
|
10 |
+
"model.final_layernorm.weight": "model-00002-of-00002.safetensors",
|
11 |
+
"model.layers.0.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
12 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
13 |
+
"model.layers.0.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
14 |
+
"model.layers.0.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
15 |
+
"model.layers.0.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
16 |
+
"model.layers.0.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
17 |
+
"model.layers.0.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
18 |
+
"model.layers.0.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
19 |
+
"model.layers.0.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
20 |
+
"model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
21 |
+
"model.layers.0.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
22 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
23 |
+
"model.layers.0.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
24 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
25 |
+
"model.layers.1.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
26 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
27 |
+
"model.layers.1.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
28 |
+
"model.layers.1.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
29 |
+
"model.layers.1.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
30 |
+
"model.layers.1.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
31 |
+
"model.layers.1.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
32 |
+
"model.layers.1.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
33 |
+
"model.layers.1.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
34 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
35 |
+
"model.layers.1.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
36 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
37 |
+
"model.layers.1.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
38 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
39 |
+
"model.layers.10.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
40 |
+
"model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
41 |
+
"model.layers.10.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
42 |
+
"model.layers.10.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
43 |
+
"model.layers.10.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
44 |
+
"model.layers.10.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
45 |
+
"model.layers.10.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
46 |
+
"model.layers.10.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
47 |
+
"model.layers.10.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
48 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
49 |
+
"model.layers.10.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
50 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
51 |
+
"model.layers.10.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
52 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
53 |
+
"model.layers.11.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
54 |
+
"model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
55 |
+
"model.layers.11.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
56 |
+
"model.layers.11.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
57 |
+
"model.layers.11.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
58 |
+
"model.layers.11.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
59 |
+
"model.layers.11.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
60 |
+
"model.layers.11.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
61 |
+
"model.layers.11.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
62 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
63 |
+
"model.layers.11.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
64 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
65 |
+
"model.layers.11.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
66 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
67 |
+
"model.layers.12.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
68 |
+
"model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
69 |
+
"model.layers.12.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
70 |
+
"model.layers.12.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
71 |
+
"model.layers.12.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
72 |
+
"model.layers.12.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
73 |
+
"model.layers.12.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
74 |
+
"model.layers.12.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
75 |
+
"model.layers.12.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
76 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
77 |
+
"model.layers.12.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
78 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
79 |
+
"model.layers.12.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
80 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
81 |
+
"model.layers.13.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
82 |
+
"model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
83 |
+
"model.layers.13.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
84 |
+
"model.layers.13.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
85 |
+
"model.layers.13.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
86 |
+
"model.layers.13.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
87 |
+
"model.layers.13.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
88 |
+
"model.layers.13.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
89 |
+
"model.layers.13.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
90 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
91 |
+
"model.layers.13.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
92 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
93 |
+
"model.layers.13.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
94 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
95 |
+
"model.layers.14.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
96 |
+
"model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
97 |
+
"model.layers.14.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
98 |
+
"model.layers.14.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
99 |
+
"model.layers.14.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
100 |
+
"model.layers.14.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
101 |
+
"model.layers.14.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
102 |
+
"model.layers.14.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
103 |
+
"model.layers.14.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
104 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
105 |
+
"model.layers.14.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
106 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
107 |
+
"model.layers.14.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
108 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
109 |
+
"model.layers.15.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
110 |
+
"model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
111 |
+
"model.layers.15.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
112 |
+
"model.layers.15.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
113 |
+
"model.layers.15.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
114 |
+
"model.layers.15.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
115 |
+
"model.layers.15.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
116 |
+
"model.layers.15.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
117 |
+
"model.layers.15.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
118 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
119 |
+
"model.layers.15.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
120 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
121 |
+
"model.layers.15.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
122 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
123 |
+
"model.layers.16.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
124 |
+
"model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
125 |
+
"model.layers.16.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
126 |
+
"model.layers.16.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
127 |
+
"model.layers.16.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
128 |
+
"model.layers.16.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
129 |
+
"model.layers.16.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
130 |
+
"model.layers.16.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
131 |
+
"model.layers.16.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
132 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
133 |
+
"model.layers.16.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
134 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
135 |
+
"model.layers.16.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
136 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
137 |
+
"model.layers.17.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
138 |
+
"model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
139 |
+
"model.layers.17.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
140 |
+
"model.layers.17.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
141 |
+
"model.layers.17.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
142 |
+
"model.layers.17.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
143 |
+
"model.layers.17.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
144 |
+
"model.layers.17.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
145 |
+
"model.layers.17.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
146 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
147 |
+
"model.layers.17.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
148 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
149 |
+
"model.layers.17.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
150 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
151 |
+
"model.layers.18.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
152 |
+
"model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
153 |
+
"model.layers.18.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
154 |
+
"model.layers.18.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
155 |
+
"model.layers.18.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
156 |
+
"model.layers.18.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
157 |
+
"model.layers.18.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
158 |
+
"model.layers.18.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
159 |
+
"model.layers.18.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
160 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
161 |
+
"model.layers.18.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
162 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
163 |
+
"model.layers.18.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
164 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
165 |
+
"model.layers.19.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
166 |
+
"model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
167 |
+
"model.layers.19.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
168 |
+
"model.layers.19.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
169 |
+
"model.layers.19.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
170 |
+
"model.layers.19.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
171 |
+
"model.layers.19.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
172 |
+
"model.layers.19.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
173 |
+
"model.layers.19.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
174 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
175 |
+
"model.layers.19.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
176 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
177 |
+
"model.layers.19.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
178 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
179 |
+
"model.layers.2.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
180 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
181 |
+
"model.layers.2.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
182 |
+
"model.layers.2.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
183 |
+
"model.layers.2.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
184 |
+
"model.layers.2.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
185 |
+
"model.layers.2.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
186 |
+
"model.layers.2.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
187 |
+
"model.layers.2.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
188 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
189 |
+
"model.layers.2.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
190 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
191 |
+
"model.layers.2.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
192 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
193 |
+
"model.layers.20.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
194 |
+
"model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
195 |
+
"model.layers.20.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
196 |
+
"model.layers.20.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
197 |
+
"model.layers.20.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
198 |
+
"model.layers.20.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
199 |
+
"model.layers.20.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
200 |
+
"model.layers.20.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
201 |
+
"model.layers.20.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
202 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
203 |
+
"model.layers.20.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
204 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
205 |
+
"model.layers.20.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
206 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
207 |
+
"model.layers.21.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
208 |
+
"model.layers.21.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
209 |
+
"model.layers.21.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
210 |
+
"model.layers.21.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
211 |
+
"model.layers.21.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
212 |
+
"model.layers.21.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
213 |
+
"model.layers.21.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
214 |
+
"model.layers.21.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
215 |
+
"model.layers.21.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
216 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
217 |
+
"model.layers.21.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
218 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
219 |
+
"model.layers.21.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
220 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
221 |
+
"model.layers.22.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
222 |
+
"model.layers.22.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
223 |
+
"model.layers.22.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
224 |
+
"model.layers.22.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
225 |
+
"model.layers.22.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
226 |
+
"model.layers.22.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
227 |
+
"model.layers.22.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
228 |
+
"model.layers.22.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
229 |
+
"model.layers.22.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
230 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
231 |
+
"model.layers.22.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
232 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
233 |
+
"model.layers.22.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
234 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
235 |
+
"model.layers.23.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
236 |
+
"model.layers.23.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
237 |
+
"model.layers.23.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
238 |
+
"model.layers.23.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
239 |
+
"model.layers.23.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
240 |
+
"model.layers.23.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
241 |
+
"model.layers.23.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
242 |
+
"model.layers.23.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
243 |
+
"model.layers.23.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
244 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
245 |
+
"model.layers.23.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
246 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
247 |
+
"model.layers.23.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
248 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
249 |
+
"model.layers.24.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
250 |
+
"model.layers.24.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
251 |
+
"model.layers.24.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
252 |
+
"model.layers.24.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
253 |
+
"model.layers.24.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
254 |
+
"model.layers.24.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
255 |
+
"model.layers.24.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
256 |
+
"model.layers.24.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
257 |
+
"model.layers.24.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
258 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
259 |
+
"model.layers.24.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
260 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
261 |
+
"model.layers.24.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
262 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
263 |
+
"model.layers.25.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
264 |
+
"model.layers.25.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
265 |
+
"model.layers.25.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
266 |
+
"model.layers.25.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
267 |
+
"model.layers.25.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
268 |
+
"model.layers.25.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
269 |
+
"model.layers.25.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
270 |
+
"model.layers.25.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
271 |
+
"model.layers.25.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
272 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
273 |
+
"model.layers.25.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
274 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
275 |
+
"model.layers.25.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
276 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
277 |
+
"model.layers.26.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
278 |
+
"model.layers.26.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
279 |
+
"model.layers.26.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
280 |
+
"model.layers.26.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
281 |
+
"model.layers.26.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
282 |
+
"model.layers.26.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
283 |
+
"model.layers.26.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
284 |
+
"model.layers.26.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
285 |
+
"model.layers.26.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
286 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
287 |
+
"model.layers.26.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
288 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
289 |
+
"model.layers.26.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
290 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
291 |
+
"model.layers.27.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
292 |
+
"model.layers.27.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
293 |
+
"model.layers.27.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
294 |
+
"model.layers.27.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
295 |
+
"model.layers.27.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
296 |
+
"model.layers.27.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
297 |
+
"model.layers.27.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
298 |
+
"model.layers.27.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
299 |
+
"model.layers.27.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
300 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
301 |
+
"model.layers.27.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
302 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
303 |
+
"model.layers.27.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
304 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
305 |
+
"model.layers.28.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
306 |
+
"model.layers.28.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
307 |
+
"model.layers.28.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
308 |
+
"model.layers.28.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
309 |
+
"model.layers.28.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
310 |
+
"model.layers.28.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
311 |
+
"model.layers.28.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
312 |
+
"model.layers.28.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
313 |
+
"model.layers.28.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
314 |
+
"model.layers.28.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
315 |
+
"model.layers.28.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
316 |
+
"model.layers.28.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
317 |
+
"model.layers.28.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
318 |
+
"model.layers.28.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
319 |
+
"model.layers.29.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
320 |
+
"model.layers.29.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
321 |
+
"model.layers.29.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
322 |
+
"model.layers.29.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
323 |
+
"model.layers.29.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
324 |
+
"model.layers.29.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
325 |
+
"model.layers.29.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
326 |
+
"model.layers.29.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
327 |
+
"model.layers.29.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
328 |
+
"model.layers.29.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
329 |
+
"model.layers.29.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
330 |
+
"model.layers.29.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
331 |
+
"model.layers.29.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
332 |
+
"model.layers.29.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
333 |
+
"model.layers.3.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
334 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
335 |
+
"model.layers.3.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
336 |
+
"model.layers.3.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
337 |
+
"model.layers.3.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
338 |
+
"model.layers.3.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
339 |
+
"model.layers.3.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
340 |
+
"model.layers.3.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
341 |
+
"model.layers.3.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
342 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
343 |
+
"model.layers.3.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
344 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
345 |
+
"model.layers.3.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
346 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
347 |
+
"model.layers.30.input_layernorm.bias": "model-00002-of-00002.safetensors",
|
348 |
+
"model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
349 |
+
"model.layers.30.mlp.fc1.bias": "model-00002-of-00002.safetensors",
|
350 |
+
"model.layers.30.mlp.fc1.weight": "model-00002-of-00002.safetensors",
|
351 |
+
"model.layers.30.mlp.fc2.bias": "model-00002-of-00002.safetensors",
|
352 |
+
"model.layers.30.mlp.fc2.weight": "model-00002-of-00002.safetensors",
|
353 |
+
"model.layers.30.self_attn.dense.bias": "model-00002-of-00002.safetensors",
|
354 |
+
"model.layers.30.self_attn.dense.weight": "model-00002-of-00002.safetensors",
|
355 |
+
"model.layers.30.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
|
356 |
+
"model.layers.30.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
357 |
+
"model.layers.30.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
358 |
+
"model.layers.30.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
359 |
+
"model.layers.30.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
|
360 |
+
"model.layers.30.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
361 |
+
"model.layers.31.input_layernorm.bias": "model-00002-of-00002.safetensors",
|
362 |
+
"model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
|
363 |
+
"model.layers.31.mlp.fc1.bias": "model-00002-of-00002.safetensors",
|
364 |
+
"model.layers.31.mlp.fc1.weight": "model-00002-of-00002.safetensors",
|
365 |
+
"model.layers.31.mlp.fc2.bias": "model-00002-of-00002.safetensors",
|
366 |
+
"model.layers.31.mlp.fc2.weight": "model-00002-of-00002.safetensors",
|
367 |
+
"model.layers.31.self_attn.dense.bias": "model-00002-of-00002.safetensors",
|
368 |
+
"model.layers.31.self_attn.dense.weight": "model-00002-of-00002.safetensors",
|
369 |
+
"model.layers.31.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
|
370 |
+
"model.layers.31.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
|
371 |
+
"model.layers.31.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
|
372 |
+
"model.layers.31.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
|
373 |
+
"model.layers.31.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
|
374 |
+
"model.layers.31.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
|
375 |
+
"model.layers.4.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
376 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
377 |
+
"model.layers.4.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
378 |
+
"model.layers.4.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
379 |
+
"model.layers.4.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
380 |
+
"model.layers.4.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
381 |
+
"model.layers.4.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
382 |
+
"model.layers.4.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
383 |
+
"model.layers.4.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
384 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
385 |
+
"model.layers.4.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
386 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
387 |
+
"model.layers.4.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
388 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
389 |
+
"model.layers.5.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
390 |
+
"model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
391 |
+
"model.layers.5.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
392 |
+
"model.layers.5.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
393 |
+
"model.layers.5.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
394 |
+
"model.layers.5.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
395 |
+
"model.layers.5.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
396 |
+
"model.layers.5.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
397 |
+
"model.layers.5.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
398 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
399 |
+
"model.layers.5.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
400 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
401 |
+
"model.layers.5.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
402 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
403 |
+
"model.layers.6.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
404 |
+
"model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
405 |
+
"model.layers.6.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
406 |
+
"model.layers.6.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
407 |
+
"model.layers.6.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
408 |
+
"model.layers.6.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
409 |
+
"model.layers.6.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
410 |
+
"model.layers.6.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
411 |
+
"model.layers.6.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
412 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
413 |
+
"model.layers.6.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
414 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
415 |
+
"model.layers.6.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
416 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
417 |
+
"model.layers.7.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
418 |
+
"model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
419 |
+
"model.layers.7.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
420 |
+
"model.layers.7.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
421 |
+
"model.layers.7.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
422 |
+
"model.layers.7.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
423 |
+
"model.layers.7.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
424 |
+
"model.layers.7.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
425 |
+
"model.layers.7.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
426 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
427 |
+
"model.layers.7.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
428 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
429 |
+
"model.layers.7.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
430 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
431 |
+
"model.layers.8.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
432 |
+
"model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
433 |
+
"model.layers.8.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
434 |
+
"model.layers.8.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
435 |
+
"model.layers.8.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
436 |
+
"model.layers.8.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
437 |
+
"model.layers.8.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
438 |
+
"model.layers.8.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
439 |
+
"model.layers.8.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
440 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
441 |
+
"model.layers.8.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
442 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
443 |
+
"model.layers.8.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
444 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
|
445 |
+
"model.layers.9.input_layernorm.bias": "model-00001-of-00002.safetensors",
|
446 |
+
"model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
|
447 |
+
"model.layers.9.mlp.fc1.bias": "model-00001-of-00002.safetensors",
|
448 |
+
"model.layers.9.mlp.fc1.weight": "model-00001-of-00002.safetensors",
|
449 |
+
"model.layers.9.mlp.fc2.bias": "model-00001-of-00002.safetensors",
|
450 |
+
"model.layers.9.mlp.fc2.weight": "model-00001-of-00002.safetensors",
|
451 |
+
"model.layers.9.self_attn.dense.bias": "model-00001-of-00002.safetensors",
|
452 |
+
"model.layers.9.self_attn.dense.weight": "model-00001-of-00002.safetensors",
|
453 |
+
"model.layers.9.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
|
454 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
|
455 |
+
"model.layers.9.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
|
456 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
|
457 |
+
"model.layers.9.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
|
458 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors"
|
459 |
}
|
460 |
}
|
modeling_phi.py
CHANGED
@@ -1,960 +1,1364 @@
|
|
1 |
-
#
|
2 |
-
#
|
3 |
#
|
4 |
-
#
|
5 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
-
from __future__ import annotations
|
8 |
|
9 |
import math
|
10 |
-
from
|
11 |
-
from typing import Any, Dict, Optional, Tuple, Union
|
12 |
|
13 |
import torch
|
14 |
-
import torch.nn as
|
15 |
-
|
16 |
-
from
|
17 |
-
from
|
18 |
-
from transformers.modeling_outputs import CausalLMOutputWithPast
|
19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
from .configuration_phi import PhiConfig
|
21 |
|
22 |
-
try:
|
23 |
-
from flash_attn.bert_padding import pad_input, unpad_input
|
24 |
-
from flash_attn.layers.rotary import RotaryEmbedding as FlashRotaryEmbedding
|
25 |
-
from flash_attn.modules.mha import FlashCrossAttention, FlashSelfAttention
|
26 |
-
from flash_attn.ops.fused_dense import FusedDense
|
27 |
-
except:
|
28 |
-
pad_input, unpad_input = None, None
|
29 |
-
FlashRotaryEmbedding = None
|
30 |
-
FlashSelfAttention, FlashCrossAttention = None, None
|
31 |
-
FusedDense = None
|
32 |
-
|
33 |
-
|
34 |
-
@dataclass
|
35 |
-
class InferenceParams:
|
36 |
-
"""Inference parameters passed to model to efficiently calculate
|
37 |
-
and store context during inference.
|
38 |
-
|
39 |
-
Reference:
|
40 |
-
https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/utils/generation.py.
|
41 |
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
seqlen_offset: Sequence length offset.
|
46 |
-
batch_size_offset: Batch size offset.
|
47 |
-
key_value_memory_dict: Key value memory dictionary.
|
48 |
-
lengths_per_sample: Lengths per sample.
|
49 |
|
50 |
-
"""
|
51 |
|
52 |
-
|
53 |
|
54 |
-
|
|
|
55 |
|
56 |
-
|
|
|
|
|
|
|
57 |
|
58 |
-
batch_size_offset: int = field(default=0, metadata={"help": "Batch size offset."})
|
59 |
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
)
|
63 |
|
64 |
-
lengths_per_sample: torch.Tensor = field(default=None, metadata={"help": "Lengths per sample."})
|
65 |
-
|
66 |
-
|
67 |
-
class Embedding(nn.Module):
|
68 |
-
"""Token embedding with dropout."""
|
69 |
|
70 |
-
|
|
|
|
|
71 |
super().__init__()
|
72 |
|
73 |
-
self.
|
74 |
-
self.
|
|
|
|
|
|
|
75 |
|
76 |
-
|
77 |
-
|
78 |
-
|
|
|
79 |
|
80 |
-
|
81 |
-
|
|
|
82 |
|
83 |
-
|
|
|
|
|
|
|
|
|
84 |
|
|
|
|
|
|
|
|
|
85 |
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
) -> torch.FloatTensor:
|
91 |
-
_, seqlen, _, _ = x.shape
|
92 |
-
_, rotary_dim = cos.shape
|
93 |
-
rotary_dim *= 2
|
94 |
|
95 |
-
x_rot = x[:, :, :, :rotary_dim]
|
96 |
-
x_pass = x[:, :, :, rotary_dim:]
|
97 |
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
|
102 |
-
|
|
|
|
|
103 |
|
104 |
-
|
|
|
|
|
|
|
105 |
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
-
def _apply_rotary_emb_kv(
|
108 |
-
kv: torch.FloatTensor,
|
109 |
-
cos: torch.FloatTensor,
|
110 |
-
sin: torch.FloatTensor,
|
111 |
-
cos_k: Optional[torch.FloatTensor] = None,
|
112 |
-
sin_k: Optional[torch.FloatTensor] = None,
|
113 |
-
) -> torch.FloatTensor:
|
114 |
-
_, seqlen, _, _, _ = kv.shape
|
115 |
-
_, rotary_dim = cos.shape
|
116 |
-
rotary_dim *= 2
|
117 |
|
118 |
-
|
119 |
-
|
|
|
120 |
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
|
125 |
-
|
|
|
126 |
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
)
|
134 |
|
|
|
135 |
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
sin_k: Optional[torch.FloatTensor] = None,
|
142 |
-
) -> torch.FloatTensor:
|
143 |
-
_, seqlen, _, _, _ = qkv.shape
|
144 |
-
_, rotary_dim = cos.shape
|
145 |
-
rotary_dim *= 2
|
146 |
-
|
147 |
-
q_rot = qkv[:, :, 0, :, :rotary_dim]
|
148 |
-
q_pass = qkv[:, :, 0, :, rotary_dim:]
|
149 |
-
|
150 |
-
k_rot = qkv[:, :, 1, :, :rotary_dim]
|
151 |
-
k_pass = qkv[:, :, 1, :, rotary_dim:]
|
152 |
-
|
153 |
-
q1, q2 = q_rot.chunk(2, dim=-1)
|
154 |
-
k1, k2 = k_rot.chunk(2, dim=-1)
|
155 |
-
c, s = rearrange(cos[:seqlen], "s d -> s 1 d"), rearrange(sin[:seqlen], "s d -> s 1 d")
|
156 |
-
q1, q2, k1, k2, c, s = [t.to(dtype=torch.float32) for t in [q1, q2, k1, k2, c, s]]
|
157 |
-
|
158 |
-
q_rot = torch.cat([q1 * c - q2 * s, q1 * s + q2 * c], axis=-1).to(qkv.dtype)
|
159 |
-
k_rot = torch.cat([k1 * c - k2 * s, k1 * s + k2 * c], axis=-1).to(qkv.dtype)
|
160 |
-
|
161 |
-
return torch.cat(
|
162 |
-
[
|
163 |
-
torch.cat([q_rot, q_pass], axis=-1).unsqueeze(2),
|
164 |
-
torch.cat([k_rot, k_pass], axis=-1).unsqueeze(2),
|
165 |
-
qkv[:, :, 2:3, :, :],
|
166 |
-
],
|
167 |
-
axis=2,
|
168 |
-
)
|
169 |
|
170 |
|
171 |
-
|
172 |
-
|
|
|
|
|
|
|
|
|
173 |
|
174 |
-
Reference:
|
175 |
-
RoFormer: Enhanced Transformer with Rotary Position Embedding.
|
176 |
-
https://arxiv.org/pdf/2104.09864.pdf.
|
177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
"""
|
|
|
|
|
|
|
|
|
|
|
179 |
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
scale_base: Optional[float] = None,
|
185 |
-
pos_idx_in_fp32: bool = True,
|
186 |
-
max_position_embeddings: int = 2048,
|
187 |
-
device: Optional[str] = None,
|
188 |
-
**kwargs,
|
189 |
-
) -> None:
|
190 |
super().__init__()
|
|
|
|
|
|
|
|
|
191 |
|
192 |
-
|
193 |
-
|
|
|
|
|
|
|
194 |
|
195 |
-
self.dim = dim
|
196 |
-
self.base = float(base)
|
197 |
-
self.scale_base = scale_base
|
198 |
-
self.pos_idx_in_fp32 = pos_idx_in_fp32
|
199 |
-
self.max_position_embeddings = max_position_embeddings
|
200 |
-
self.device = device
|
201 |
|
202 |
-
|
203 |
-
|
204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
|
206 |
-
# Generate and save the scale buffer (non-trainable)
|
207 |
-
scale = (
|
208 |
-
(torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
|
209 |
-
if scale_base is not None
|
210 |
-
else None
|
211 |
-
)
|
212 |
-
self.register_buffer("scale", scale, persistent=False)
|
213 |
|
214 |
-
|
215 |
-
|
216 |
|
217 |
-
def
|
218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
219 |
|
220 |
-
|
221 |
-
self
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
self.
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
else:
|
237 |
-
t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
|
238 |
-
inv_freq = self.inv_freq
|
239 |
-
|
240 |
-
# `torch.outer` is preferred since `torch.einsum` converts from fp32 to fp16 if used with AMP
|
241 |
-
freqs = torch.outer(t, inv_freq)
|
242 |
-
if self.scale is None:
|
243 |
-
self._cos_cached = torch.cos(freqs).to(dtype)
|
244 |
-
self._sin_cached = torch.sin(freqs).to(dtype)
|
245 |
-
else:
|
246 |
-
power = (
|
247 |
-
torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) - seqlen // 2
|
248 |
-
) / self.scale_base
|
249 |
-
scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
|
250 |
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
|
256 |
|
257 |
-
|
258 |
-
self
|
259 |
-
|
260 |
-
|
261 |
-
seqlen_offset: int = 0,
|
262 |
-
**kwargs,
|
263 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
264 |
-
if (
|
265 |
-
self._seq_len_cached < qkv.shape[1] + seqlen_offset
|
266 |
-
or self._cos_cached.device != qkv.device
|
267 |
-
or self._cos_cached.dtype != qkv.dtype
|
268 |
-
or (self.training and self._cos_cached.is_inference())
|
269 |
-
):
|
270 |
-
self._update_cos_sin_cache(qkv.shape[1] + seqlen_offset, device=qkv.device, dtype=qkv.dtype)
|
271 |
-
|
272 |
-
if kv is None:
|
273 |
-
return _apply_rotary_emb_qkv(
|
274 |
-
qkv,
|
275 |
-
self._cos_cached[seqlen_offset:],
|
276 |
-
self._sin_cached[seqlen_offset:],
|
277 |
)
|
278 |
-
|
279 |
-
|
280 |
-
qkv,
|
281 |
-
self._cos_cached[seqlen_offset:],
|
282 |
-
self._sin_cached[seqlen_offset:],
|
283 |
)
|
284 |
-
kv = _apply_rotary_emb_kv(
|
285 |
-
kv,
|
286 |
-
self._cos_cached[seqlen_offset:],
|
287 |
-
self._sin_cached[seqlen_offset:],
|
288 |
-
)
|
289 |
-
|
290 |
-
return q, kv
|
291 |
-
|
292 |
-
|
293 |
-
class MLP(nn.Module):
|
294 |
-
"""Multi-Layer Perceptron.
|
295 |
|
296 |
-
|
297 |
-
Attention Is All You Need.
|
298 |
-
https://arxiv.org/pdf/1706.03762.pdf.
|
299 |
|
300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
301 |
|
302 |
-
def
|
303 |
self,
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
self.
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
329 |
|
330 |
-
|
331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
332 |
|
333 |
-
|
|
|
|
|
334 |
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
softmax_scale: Optional[float] = None,
|
339 |
-
attention_dropout: float = 0.0,
|
340 |
-
) -> None:
|
341 |
-
super().__init__()
|
342 |
|
343 |
-
|
344 |
-
|
345 |
-
self.drop = nn.Dropout(attention_dropout)
|
346 |
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
self
|
351 |
-
qkv: torch.FloatTensor,
|
352 |
-
causal: bool = None,
|
353 |
-
key_padding_mask: Optional[torch.BoolTensor] = None,
|
354 |
-
**kwargs,
|
355 |
-
) -> torch.FloatTensor:
|
356 |
-
batch_size, seqlen = qkv.shape[0], qkv.shape[1]
|
357 |
-
q, k, v = qkv.unbind(dim=2)
|
358 |
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
# Autocast is manually disabled to avoid `torch.einsum` performing the operation
|
366 |
-
# using float16, which might lead to overflow
|
367 |
-
scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale)
|
368 |
|
369 |
-
if
|
370 |
-
|
371 |
-
|
|
|
|
|
|
|
372 |
|
373 |
-
|
|
|
|
|
374 |
|
375 |
-
|
376 |
-
causal_mask = torch.triu(torch.full((seqlen, seqlen), -10000.0, device=scores.device), 1)
|
377 |
-
scores = scores + causal_mask.to(dtype=scores.dtype)
|
378 |
|
379 |
-
|
380 |
-
|
|
|
|
|
|
|
381 |
|
382 |
-
|
|
|
383 |
|
384 |
-
|
385 |
|
|
|
|
|
386 |
|
387 |
-
|
388 |
-
"""Cross-attention layer (compatible with PyTorch).
|
389 |
|
390 |
-
Reference:
|
391 |
-
https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/modules/mha.py.
|
392 |
|
|
|
|
|
|
|
|
|
|
|
393 |
"""
|
394 |
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
softmax_scale: Optional[float] = None,
|
399 |
-
attention_dropout: float = 0.0,
|
400 |
-
) -> None:
|
401 |
-
super().__init__()
|
402 |
|
403 |
-
|
404 |
-
|
405 |
-
|
|
|
406 |
|
407 |
-
@torch.autocast("cpu", enabled=False)
|
408 |
-
@torch.autocast("cuda", enabled=False)
|
409 |
def forward(
|
410 |
self,
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
|
|
|
|
415 |
**kwargs,
|
416 |
-
) -> torch.
|
417 |
-
|
418 |
-
seqlen_k = kv.shape[1]
|
419 |
-
|
420 |
-
if kv.shape[3] != q.shape[2]:
|
421 |
-
kv = repeat(kv, "... hkv d -> ... (hkv g) d", g=q.shape[2] // kv.shape[3])
|
422 |
-
k, v = kv.unbind(dim=2)
|
423 |
-
|
424 |
-
q = q.to(torch.float32)
|
425 |
-
k = k.to(torch.float32)
|
426 |
-
|
427 |
-
causal = self.causal if causal is None else causal
|
428 |
-
softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1])
|
429 |
-
|
430 |
-
# Autocast is manually disabled to avoid `torch.einsum` performing the operation
|
431 |
-
# using float16, which might lead to overflow
|
432 |
-
scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale)
|
433 |
-
|
434 |
-
if key_padding_mask is not None:
|
435 |
-
padding_mask = torch.full(
|
436 |
-
(batch_size, seqlen_k),
|
437 |
-
-10000.0,
|
438 |
-
dtype=scores.dtype,
|
439 |
-
device=scores.device,
|
440 |
-
)
|
441 |
-
padding_mask.masked_fill_(key_padding_mask, 0.0)
|
442 |
-
|
443 |
-
scores = scores + rearrange(padding_mask, "b s -> b 1 1 s")
|
444 |
-
|
445 |
-
if causal:
|
446 |
-
rows = rearrange(torch.arange(seqlen_q, device=q.device, dtype=torch.long), "s -> s 1")
|
447 |
-
cols = torch.arange(seqlen_k, device=k.device, dtype=torch.long)
|
448 |
-
causal_mask = cols > rows + seqlen_k - seqlen_q
|
449 |
-
|
450 |
-
scores = scores.masked_fill(causal_mask, -10000.0)
|
451 |
-
|
452 |
-
attention = torch.softmax(scores, dim=-1).to(v.dtype)
|
453 |
-
attention = self.drop(attention)
|
454 |
-
|
455 |
-
output = torch.einsum("bhts,bshd->bthd", attention, v)
|
456 |
|
457 |
-
|
458 |
|
|
|
459 |
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
n_head_kv: Optional[int] = None,
|
464 |
-
head_dim: Optional[int] = None,
|
465 |
-
) -> Tuple[int, int]:
|
466 |
-
if n_head is None and head_dim is None:
|
467 |
-
head_dim = config.n_embd // config.n_head
|
468 |
-
n_head = config.n_head
|
469 |
-
elif n_head is None or head_dim is None:
|
470 |
-
raise ValueError("`n_head` and `head_dim` must be both specified or `None`.")
|
471 |
|
472 |
-
|
473 |
-
|
|
|
474 |
|
475 |
-
|
|
|
|
|
|
|
|
|
|
|
476 |
|
|
|
|
|
|
|
|
|
477 |
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
inference_params.key_value_memory_dict[layer_idx] = torch.empty(
|
483 |
-
inference_params.max_batch_size,
|
484 |
-
inference_params.max_seqlen,
|
485 |
-
2,
|
486 |
-
num_heads,
|
487 |
-
head_dim,
|
488 |
-
dtype=kv.dtype,
|
489 |
-
device=kv.device,
|
490 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
491 |
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
# When the current sequence length is equal to or larger than the maximum sequence length,
|
499 |
-
# we need to concatenate the current `kv` with the cached `kv` to expand its length
|
500 |
-
if sequence_end >= inference_params.max_seqlen:
|
501 |
-
inference_params.key_value_memory_dict[layer_idx] = torch.concatenate((inference_params.key_value_memory_dict[layer_idx], kv), dim=1)
|
502 |
-
|
503 |
-
inference_params.key_value_memory_dict[layer_idx][batch_start:batch_end, sequence_start:sequence_end, ...] = kv
|
504 |
-
kv = inference_params.key_value_memory_dict[layer_idx][batch_start:batch_end, :sequence_end, ...]
|
505 |
-
|
506 |
-
return kv
|
507 |
|
|
|
|
|
|
|
508 |
|
509 |
-
|
510 |
-
|
|
|
511 |
|
512 |
-
|
513 |
-
self
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
531 |
|
532 |
-
#
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
rotary_cls = RotaryEmbedding
|
538 |
-
|
539 |
-
rotary_kwargs = {}
|
540 |
-
if rotary_cls is RotaryEmbedding:
|
541 |
-
rotary_kwargs["max_position_embeddings"] = config.n_positions
|
542 |
-
|
543 |
-
self.rotary_emb = rotary_cls(
|
544 |
-
self.rotary_dim,
|
545 |
-
base=rotary_base,
|
546 |
-
scale_base=rotary_scale_base,
|
547 |
-
device=device,
|
548 |
-
**rotary_kwargs,
|
549 |
)
|
550 |
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
|
|
|
|
|
|
|
|
|
|
561 |
|
562 |
-
|
563 |
-
|
|
|
|
|
|
|
564 |
|
565 |
-
|
566 |
-
attn_cls = FlashSelfAttention if config.flash_attn else SelfAttention
|
567 |
-
if attn_cls is None:
|
568 |
-
attn_cls = SelfAttention
|
569 |
|
570 |
-
|
571 |
-
|
572 |
-
|
|
|
573 |
|
574 |
-
|
575 |
-
|
576 |
-
softmax_scale=softmax_scale,
|
577 |
-
attention_dropout=config.attn_pdrop,
|
578 |
)
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
583 |
)
|
584 |
|
585 |
-
self.flash_attn = config.flash_attn and attn_cls is FlashSelfAttention
|
586 |
-
self.layer_idx = layer_idx
|
587 |
-
self.return_residual = return_residual
|
588 |
-
self.checkpointing = checkpointing
|
589 |
-
|
590 |
-
def _forward_self_attn(
|
591 |
-
self, x: torch.FloatTensor, key_padding_mask: Optional[torch.BoolTensor]
|
592 |
-
) -> torch.FloatTensor:
|
593 |
-
qkv = self.Wqkv(x)
|
594 |
-
qkv = rearrange(qkv, "... (three h d) -> ... three h d", three=3, d=self.head_dim)
|
595 |
-
|
596 |
-
if self.rotary_dim > 0:
|
597 |
-
qkv = self.rotary_emb(qkv)
|
598 |
-
|
599 |
-
if self.flash_attn:
|
600 |
-
batch_size, seqlen = qkv.shape[0], qkv.shape[1]
|
601 |
-
|
602 |
-
cu_seqlens, max_seqlen = None, None
|
603 |
-
if key_padding_mask is not None:
|
604 |
-
# If `key_padding_mask` is supplied, we need to unpad the input and retrieve
|
605 |
-
# the `cu_seqlens` and `max_seqlen` to be used by `flash-attn`
|
606 |
-
qkv, indices, cu_seqlens, max_seqlen = unpad_input(qkv, key_padding_mask)
|
607 |
-
|
608 |
-
if self.checkpointing:
|
609 |
-
attn_output = torch.utils.checkpoint.checkpoint(
|
610 |
-
self.inner_attn, qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen
|
611 |
-
)
|
612 |
-
else:
|
613 |
-
attn_output = self.inner_attn(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen).to(qkv.device)
|
614 |
|
615 |
-
|
616 |
-
|
|
|
|
|
617 |
|
618 |
-
if self.checkpointing:
|
619 |
-
return torch.utils.checkpoint.checkpoint(self.inner_attn, qkv, key_padding_mask=key_padding_mask)
|
620 |
|
621 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
622 |
|
623 |
-
def
|
624 |
self,
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
630 |
|
631 |
-
|
632 |
|
633 |
-
|
634 |
-
q = rearrange(q, "... (h d) -> ... h d", d=self.head_dim)
|
635 |
|
636 |
-
|
637 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
638 |
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
q, kv = self.rotary_emb(q, kv=kv, seqlen_offset=seqlen_offset)
|
643 |
|
644 |
-
if
|
645 |
-
|
646 |
|
647 |
-
if
|
648 |
-
|
649 |
-
seqlen_k = kv.shape[1]
|
650 |
|
651 |
-
|
652 |
-
None,
|
653 |
-
None,
|
654 |
-
None,
|
655 |
-
None,
|
656 |
-
)
|
657 |
-
if key_padding_mask is not None:
|
658 |
-
kv, _, cu_seqlens_k, max_seqlen_k = unpad_input(kv, key_padding_mask)
|
659 |
-
|
660 |
-
if seqlen_q == 1:
|
661 |
-
key_padding_mask = torch.ones(batch_size, 1, device=q.device)
|
662 |
-
elif seqlen_q != seqlen_k:
|
663 |
-
key_padding_mask = key_padding_mask[:, -seqlen_q:]
|
664 |
-
|
665 |
-
q, indices_q, cu_seqlens_q, max_seqlen_q = unpad_input(q, key_padding_mask)
|
666 |
-
|
667 |
-
if self.checkpointing:
|
668 |
-
attn_output = torch.utils.checkpoint.checkpoint(
|
669 |
-
self.inner_cross_attn,
|
670 |
-
q,
|
671 |
-
kv,
|
672 |
-
causal=causal,
|
673 |
-
cu_seqlens=cu_seqlens_q,
|
674 |
-
max_seqlen=max_seqlen_q,
|
675 |
-
cu_seqlens_k=cu_seqlens_k,
|
676 |
-
max_seqlen_k=max_seqlen_k,
|
677 |
-
)
|
678 |
-
else:
|
679 |
-
attn_output = self.inner_cross_attn(
|
680 |
-
q,
|
681 |
-
kv,
|
682 |
-
causal=causal,
|
683 |
-
cu_seqlens=cu_seqlens_q,
|
684 |
-
max_seqlen=max_seqlen_q,
|
685 |
-
cu_seqlens_k=cu_seqlens_k,
|
686 |
-
max_seqlen_k=max_seqlen_k,
|
687 |
-
)
|
688 |
|
689 |
-
return (
|
690 |
-
pad_input(attn_output, indices_q, batch_size, max_seqlen_q)
|
691 |
-
if key_padding_mask is not None
|
692 |
-
else attn_output
|
693 |
-
)
|
694 |
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
kv,
|
700 |
-
key_padding_mask=key_padding_mask,
|
701 |
-
causal=causal,
|
702 |
-
)
|
703 |
|
704 |
-
|
|
|
|
|
705 |
|
706 |
-
|
707 |
-
|
708 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
|
713 |
-
if attention_mask is not None:
|
714 |
-
attention_mask = attention_mask.bool()
|
715 |
-
else:
|
716 |
-
attention_mask = None
|
717 |
|
718 |
-
# MHA
|
719 |
-
if self.n_head == self.n_head_kv:
|
720 |
-
if past_key_values is None:
|
721 |
-
# If `past_key_values` are not supplied, we run self-attention
|
722 |
-
attn_output = self._forward_self_attn(x, attention_mask)
|
723 |
-
else:
|
724 |
-
# If `past_key_values` are supplied, it means that we might have cached values and
|
725 |
-
# could take advantage of cross-attention
|
726 |
-
attn_output = self._forward_cross_attn(x, past_key_values, attention_mask)
|
727 |
-
# MQA / GQA
|
728 |
-
else:
|
729 |
-
# Regardless of `past_key_values` being supplied or not, it always use cross-attention
|
730 |
-
# because `q` and `kv` lengths might be different
|
731 |
-
attn_output = self._forward_cross_attn(x, past_key_values, attention_mask)
|
732 |
|
733 |
-
|
734 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
735 |
|
736 |
-
return output if not self.return_residual else (output, x)
|
737 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
738 |
|
739 |
-
|
740 |
-
|
|
|
741 |
|
742 |
-
|
|
|
|
|
|
|
743 |
|
744 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
745 |
|
746 |
-
|
747 |
-
|
748 |
-
|
749 |
-
block_idx: Optional[int] = None,
|
750 |
-
) -> None:
|
751 |
-
super().__init__()
|
752 |
|
753 |
-
|
754 |
-
self.
|
755 |
-
self.block_idx = block_idx
|
756 |
|
757 |
-
|
758 |
-
self.
|
759 |
|
|
|
760 |
def forward(
|
761 |
self,
|
762 |
-
|
763 |
-
|
764 |
-
|
765 |
-
|
766 |
-
|
767 |
-
|
768 |
-
|
769 |
-
|
770 |
-
|
771 |
-
|
772 |
-
|
773 |
-
|
|
|
774 |
)
|
775 |
-
if
|
776 |
-
attn_outputs = attn_outputs[0]
|
777 |
-
|
778 |
-
attn_outputs = self.resid_dropout(attn_outputs)
|
779 |
-
feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
|
780 |
|
781 |
-
|
782 |
|
783 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
784 |
|
|
|
785 |
|
786 |
-
|
787 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
788 |
|
789 |
-
|
790 |
-
|
791 |
-
https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf.
|
792 |
|
793 |
-
|
794 |
|
795 |
-
|
796 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
797 |
|
798 |
-
|
799 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
800 |
|
801 |
-
|
802 |
-
hidden_states = self.ln(hidden_states)
|
803 |
-
logits = self.linear(hidden_states).to(torch.float32)
|
804 |
|
805 |
-
|
|
|
806 |
|
|
|
|
|
807 |
|
808 |
-
|
809 |
-
"""Causal Language Modeling loss.
|
810 |
|
811 |
-
|
812 |
-
|
813 |
-
|
814 |
|
815 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
816 |
|
817 |
-
def __init__(self, shift_labels: bool = True) -> None:
|
818 |
-
super().__init__()
|
819 |
|
820 |
-
|
821 |
-
|
822 |
|
823 |
-
|
824 |
-
|
825 |
-
|
826 |
-
|
|
|
|
|
827 |
|
828 |
-
|
|
|
829 |
|
830 |
-
|
|
|
|
|
831 |
|
|
|
|
|
|
|
832 |
|
833 |
-
|
834 |
-
|
|
|
835 |
|
836 |
-
|
837 |
-
|
838 |
-
|
839 |
-
_no_split_modules = ["ParallelBlock"]
|
840 |
|
841 |
-
|
842 |
-
|
|
|
843 |
|
844 |
-
|
845 |
-
|
846 |
-
|
847 |
-
if module.bias is not None:
|
848 |
-
module.bias.data.zero_()
|
849 |
-
elif isinstance(module, nn.Embedding):
|
850 |
-
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
851 |
-
if module.padding_idx is not None:
|
852 |
-
module.weight.data[module.padding_idx].zero_()
|
853 |
-
elif isinstance(module, nn.LayerNorm):
|
854 |
-
if module.bias is not None:
|
855 |
-
module.bias.data.zero_()
|
856 |
-
module.weight.data.fill_(1.0)
|
857 |
|
858 |
-
|
|
|
|
|
859 |
self,
|
860 |
-
input_ids: torch.LongTensor,
|
861 |
-
|
862 |
-
|
863 |
-
|
864 |
-
|
865 |
-
|
866 |
-
|
867 |
-
|
868 |
-
|
869 |
-
|
870 |
-
|
871 |
-
|
872 |
-
|
873 |
-
)
|
874 |
-
|
875 |
-
|
876 |
-
|
877 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
878 |
|
879 |
-
|
880 |
-
|
881 |
-
|
882 |
-
|
883 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
884 |
|
|
|
|
|
|
|
885 |
|
886 |
-
|
887 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
888 |
|
889 |
-
_keys_to_ignore_on_load_missing = [""]
|
890 |
-
_keys_to_ignore_on_load_unexpected = [r"h\.\d+\.mlp.(fc_in|fc_out)\.(weight|bias)"]
|
891 |
|
892 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
893 |
super().__init__(config)
|
|
|
|
|
|
|
894 |
|
895 |
-
|
896 |
-
self.h = nn.ModuleList([ParallelBlock(config, block_idx=i) for i in range(config.n_layer)])
|
897 |
-
self.gradient_checkpointing = False
|
898 |
self.post_init()
|
899 |
|
900 |
-
def get_input_embeddings(self)
|
901 |
-
return self.
|
902 |
|
903 |
-
def set_input_embeddings(self,
|
904 |
-
self.
|
905 |
|
|
|
906 |
def forward(
|
907 |
self,
|
908 |
-
input_ids: torch.LongTensor,
|
909 |
-
|
910 |
-
|
911 |
-
|
912 |
-
|
913 |
-
|
914 |
-
|
915 |
-
|
916 |
-
|
917 |
-
|
918 |
-
|
919 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
920 |
|
921 |
-
|
|
|
|
|
|
|
922 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
923 |
|
924 |
-
|
925 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
926 |
|
927 |
-
_keys_to_ignore_on_load_missing = [""]
|
928 |
-
_keys_to_ignore_on_load_unexpected = [r"transformer\.h\.\d+\.mlp.(fc_in|fc_out)\.(weight|bias)"]
|
929 |
|
930 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
931 |
super().__init__(config)
|
|
|
932 |
|
933 |
-
self.
|
934 |
-
|
935 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
936 |
|
|
|
937 |
self.post_init()
|
938 |
|
939 |
-
|
940 |
-
|
941 |
-
|
942 |
-
|
943 |
-
|
944 |
-
|
945 |
def forward(
|
946 |
self,
|
947 |
-
input_ids: torch.LongTensor,
|
948 |
-
past_key_values: Optional[
|
949 |
-
attention_mask: Optional[torch.
|
950 |
-
|
951 |
-
|
952 |
-
|
953 |
-
|
954 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
955 |
|
956 |
loss = None
|
957 |
if labels is not None:
|
958 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
959 |
|
960 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
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 torch import nn
|
26 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
|
|
27 |
|
28 |
+
from transformers.activations import ACT2FN
|
29 |
+
from transformers.cache_utils import Cache, DynamicCache
|
30 |
+
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
|
31 |
+
from transformers.modeling_outputs import (
|
32 |
+
BaseModelOutputWithPast,
|
33 |
+
CausalLMOutputWithPast,
|
34 |
+
SequenceClassifierOutputWithPast,
|
35 |
+
TokenClassifierOutput,
|
36 |
+
)
|
37 |
+
from transformers.modeling_utils import PreTrainedModel
|
38 |
+
from transformers.utils import (
|
39 |
+
add_code_sample_docstrings,
|
40 |
+
add_start_docstrings,
|
41 |
+
add_start_docstrings_to_model_forward,
|
42 |
+
is_flash_attn_2_available,
|
43 |
+
is_flash_attn_greater_or_equal_2_10,
|
44 |
+
logging,
|
45 |
+
replace_return_docstrings,
|
46 |
+
)
|
47 |
from .configuration_phi import PhiConfig
|
48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
+
if is_flash_attn_2_available():
|
51 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
52 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
|
|
|
|
|
|
|
|
53 |
|
|
|
54 |
|
55 |
+
logger = logging.get_logger(__name__)
|
56 |
|
57 |
+
_CHECKPOINT_FOR_DOC = "microsoft/phi-2"
|
58 |
+
_CONFIG_FOR_DOC = "PhiConfig"
|
59 |
|
60 |
+
PHI_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
61 |
+
"microsoft/phi-2",
|
62 |
+
# See all Phi models at https://huggingface.co/models?filter=phi
|
63 |
+
]
|
64 |
|
|
|
65 |
|
66 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
67 |
+
def _get_unpad_data(attention_mask):
|
68 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
69 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
70 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
71 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
72 |
+
return (
|
73 |
+
indices,
|
74 |
+
cu_seqlens,
|
75 |
+
max_seqlen_in_batch,
|
76 |
)
|
77 |
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Phi
|
80 |
+
class PhiRotaryEmbedding(nn.Module):
|
81 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
82 |
super().__init__()
|
83 |
|
84 |
+
self.dim = dim
|
85 |
+
self.max_position_embeddings = max_position_embeddings
|
86 |
+
self.base = base
|
87 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
88 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
89 |
|
90 |
+
# Build here to make `torch.jit.trace` work.
|
91 |
+
self._set_cos_sin_cache(
|
92 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
93 |
+
)
|
94 |
|
95 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
96 |
+
self.max_seq_len_cached = seq_len
|
97 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
98 |
|
99 |
+
freqs = torch.outer(t, self.inv_freq)
|
100 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
101 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
102 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
103 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
104 |
|
105 |
+
def forward(self, x, seq_len=None):
|
106 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
107 |
+
if seq_len > self.max_seq_len_cached:
|
108 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
109 |
|
110 |
+
return (
|
111 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
112 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
113 |
+
)
|
|
|
|
|
|
|
|
|
114 |
|
|
|
|
|
115 |
|
116 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Phi
|
117 |
+
class PhiLinearScalingRotaryEmbedding(PhiRotaryEmbedding):
|
118 |
+
"""PhiRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
119 |
|
120 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
121 |
+
self.scaling_factor = scaling_factor
|
122 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
123 |
|
124 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
125 |
+
self.max_seq_len_cached = seq_len
|
126 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
127 |
+
t = t / self.scaling_factor
|
128 |
|
129 |
+
freqs = torch.outer(t, self.inv_freq)
|
130 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
131 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
132 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
133 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
|
136 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Phi
|
137 |
+
class PhiDynamicNTKScalingRotaryEmbedding(PhiRotaryEmbedding):
|
138 |
+
"""PhiRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
139 |
|
140 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
141 |
+
self.scaling_factor = scaling_factor
|
142 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
143 |
|
144 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
145 |
+
self.max_seq_len_cached = seq_len
|
146 |
|
147 |
+
if seq_len > self.max_position_embeddings:
|
148 |
+
base = self.base * (
|
149 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
150 |
+
) ** (self.dim / (self.dim - 2))
|
151 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
152 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
|
|
153 |
|
154 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
155 |
|
156 |
+
freqs = torch.outer(t, self.inv_freq)
|
157 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
158 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
159 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
160 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
161 |
|
162 |
|
163 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
164 |
+
def rotate_half(x):
|
165 |
+
"""Rotates half the hidden dims of the input."""
|
166 |
+
x1 = x[..., : x.shape[-1] // 2]
|
167 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
168 |
+
return torch.cat((-x2, x1), dim=-1)
|
169 |
|
|
|
|
|
|
|
170 |
|
171 |
+
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
|
172 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
173 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
174 |
+
|
175 |
+
Args:
|
176 |
+
q (`torch.Tensor`): The query tensor.
|
177 |
+
k (`torch.Tensor`): The key tensor.
|
178 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
179 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
180 |
+
position_ids (`torch.Tensor`):
|
181 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
182 |
+
used to pass offsetted position ids when working with a KV-cache.
|
183 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
184 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
185 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
186 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
187 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
188 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
189 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
190 |
+
Returns:
|
191 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
192 |
"""
|
193 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
194 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
195 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
196 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
197 |
+
return q_embed, k_embed
|
198 |
|
199 |
+
|
200 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Phi
|
201 |
+
class PhiMLP(nn.Module):
|
202 |
+
def __init__(self, config):
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
super().__init__()
|
204 |
+
self.config = config
|
205 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
206 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
207 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
208 |
|
209 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
210 |
+
hidden_states = self.fc1(hidden_states)
|
211 |
+
hidden_states = self.activation_fn(hidden_states)
|
212 |
+
hidden_states = self.fc2(hidden_states)
|
213 |
+
return hidden_states
|
214 |
|
|
|
|
|
|
|
|
|
|
|
|
|
215 |
|
216 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
|
217 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
218 |
+
"""
|
219 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
220 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
221 |
+
"""
|
222 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
223 |
+
if n_rep == 1:
|
224 |
+
return hidden_states
|
225 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
226 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
227 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
228 |
|
229 |
+
class PhiAttention(nn.Module):
|
230 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
231 |
|
232 |
+
def __init__(self, config: PhiConfig, layer_idx: Optional[int] = None):
|
233 |
+
super().__init__()
|
234 |
+
self.config = config
|
235 |
+
self.layer_idx = layer_idx
|
236 |
+
if layer_idx is None:
|
237 |
+
logger.warning_once(
|
238 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
239 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
240 |
+
"when creating this class."
|
241 |
+
)
|
242 |
|
243 |
+
self.attention_dropout = config.attention_dropout
|
244 |
+
self.hidden_size = config.hidden_size
|
245 |
+
self.num_heads = config.num_attention_heads
|
246 |
+
self.head_dim = self.hidden_size // self.num_heads
|
247 |
+
self.num_key_value_heads = config.num_key_value_heads
|
248 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
249 |
+
self.max_position_embeddings = config.max_position_embeddings
|
250 |
+
self.rope_theta = config.rope_theta
|
251 |
+
self.partial_rotary_factor = config.partial_rotary_factor
|
252 |
+
self.is_causal = True
|
253 |
+
|
254 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
255 |
+
raise ValueError(
|
256 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
257 |
+
f" and `num_heads`: {self.num_heads})."
|
258 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
259 |
|
260 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
261 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
262 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
263 |
+
self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=True)
|
|
|
264 |
|
265 |
+
self.qk_layernorm = config.qk_layernorm
|
266 |
+
if self.qk_layernorm:
|
267 |
+
self.q_layernorm = nn.LayerNorm(
|
268 |
+
config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
269 |
)
|
270 |
+
self.k_layernorm = nn.LayerNorm(
|
271 |
+
config.hidden_size // self.num_heads, eps=config.layer_norm_eps, elementwise_affine=True
|
|
|
|
|
|
|
272 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
273 |
|
274 |
+
self._init_rope()
|
|
|
|
|
275 |
|
276 |
+
def _init_rope(self):
|
277 |
+
if self.config.rope_scaling is None:
|
278 |
+
self.rotary_emb = PhiRotaryEmbedding(
|
279 |
+
int(self.partial_rotary_factor * self.head_dim),
|
280 |
+
max_position_embeddings=self.max_position_embeddings,
|
281 |
+
base=self.rope_theta,
|
282 |
+
)
|
283 |
+
else:
|
284 |
+
scaling_type = self.config.rope_scaling["type"]
|
285 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
286 |
+
if scaling_type == "linear":
|
287 |
+
self.rotary_emb = PhiLinearScalingRotaryEmbedding(
|
288 |
+
int(self.partial_rotary_factor * self.head_dim),
|
289 |
+
max_position_embeddings=self.max_position_embeddings,
|
290 |
+
scaling_factor=scaling_factor,
|
291 |
+
base=self.rope_theta,
|
292 |
+
)
|
293 |
+
elif scaling_type == "dynamic":
|
294 |
+
self.rotary_emb = PhiDynamicNTKScalingRotaryEmbedding(
|
295 |
+
int(self.partial_rotary_factor * self.head_dim),
|
296 |
+
max_position_embeddings=self.max_position_embeddings,
|
297 |
+
scaling_factor=scaling_factor,
|
298 |
+
base=self.rope_theta,
|
299 |
+
)
|
300 |
+
else:
|
301 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
302 |
|
303 |
+
def forward(
|
304 |
self,
|
305 |
+
hidden_states: torch.Tensor,
|
306 |
+
attention_mask: Optional[torch.Tensor] = None,
|
307 |
+
position_ids: Optional[torch.LongTensor] = None,
|
308 |
+
past_key_value: Optional[Cache] = None,
|
309 |
+
output_attentions: bool = False,
|
310 |
+
use_cache: bool = False,
|
311 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
312 |
+
bsz, q_len, _ = hidden_states.size()
|
313 |
+
|
314 |
+
query_states = self.q_proj(hidden_states)
|
315 |
+
key_states = self.k_proj(hidden_states)
|
316 |
+
value_states = self.v_proj(hidden_states)
|
317 |
+
|
318 |
+
if self.qk_layernorm:
|
319 |
+
query_states = self.q_layernorm(query_states)
|
320 |
+
key_states = self.k_layernorm(key_states)
|
321 |
+
|
322 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
323 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
324 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
325 |
+
|
326 |
+
kv_seq_len = key_states.shape[-2]
|
327 |
+
if past_key_value is not None:
|
328 |
+
if self.layer_idx is None:
|
329 |
+
raise ValueError(
|
330 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
331 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
332 |
+
"with a layer index."
|
333 |
+
)
|
334 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
335 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
336 |
|
337 |
+
# Partial rotary embedding
|
338 |
+
query_rot, query_pass = (
|
339 |
+
query_states[..., : self.rotary_emb.dim],
|
340 |
+
query_states[..., self.rotary_emb.dim :],
|
341 |
+
)
|
342 |
+
key_rot, key_pass = (
|
343 |
+
key_states[..., : self.rotary_emb.dim],
|
344 |
+
key_states[..., self.rotary_emb.dim :],
|
345 |
+
)
|
346 |
+
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
|
347 |
+
query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
|
348 |
|
349 |
+
# [batch_size, seq_length, num_heads, head_dim]
|
350 |
+
query_states = torch.cat((query_rot, query_pass), dim=-1)
|
351 |
+
key_states = torch.cat((key_rot, key_pass), dim=-1)
|
352 |
|
353 |
+
if past_key_value is not None:
|
354 |
+
cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
|
355 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
|
|
|
|
|
|
|
|
356 |
|
357 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
358 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
|
|
359 |
|
360 |
+
# Queries and keys upcast to fp32 is required by Phi-2 to avoid overflow
|
361 |
+
attn_weights = torch.matmul(
|
362 |
+
query_states.to(torch.float32), key_states.to(torch.float32).transpose(2, 3)
|
363 |
+
) / math.sqrt(self.head_dim)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
364 |
|
365 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
366 |
+
raise ValueError(
|
367 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
368 |
+
f" {attn_weights.size()}"
|
369 |
+
)
|
|
|
|
|
|
|
|
|
370 |
|
371 |
+
if attention_mask is not None:
|
372 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
373 |
+
raise ValueError(
|
374 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
375 |
+
)
|
376 |
+
attn_weights = attn_weights + attention_mask
|
377 |
|
378 |
+
# upcast attention to fp32
|
379 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
|
380 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
381 |
|
382 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
|
|
|
|
383 |
|
384 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
385 |
+
raise ValueError(
|
386 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
387 |
+
f" {attn_output.size()}"
|
388 |
+
)
|
389 |
|
390 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
391 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
392 |
|
393 |
+
attn_output = self.dense(attn_output)
|
394 |
|
395 |
+
if not output_attentions:
|
396 |
+
attn_weights = None
|
397 |
|
398 |
+
return attn_output, attn_weights, past_key_value
|
|
|
399 |
|
|
|
|
|
400 |
|
401 |
+
class PhiFlashAttention2(PhiAttention):
|
402 |
+
"""
|
403 |
+
Phi flash attention module. This module inherits from `PhiAttention` as the weights of the module stays
|
404 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
405 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
406 |
"""
|
407 |
|
408 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
409 |
+
def __init__(self, *args, **kwargs):
|
410 |
+
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
|
411 |
|
412 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
413 |
+
# 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.
|
414 |
+
# 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).
|
415 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
416 |
|
|
|
|
|
417 |
def forward(
|
418 |
self,
|
419 |
+
hidden_states: torch.Tensor,
|
420 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
421 |
+
position_ids: Optional[torch.LongTensor] = None,
|
422 |
+
past_key_value: Optional[Cache] = None,
|
423 |
+
output_attentions: bool = False,
|
424 |
+
use_cache: bool = False,
|
425 |
**kwargs,
|
426 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
427 |
+
# PhiFlashAttention2 attention does not support output_attentions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
428 |
|
429 |
+
output_attentions = False
|
430 |
|
431 |
+
bsz, q_len, _ = hidden_states.size()
|
432 |
|
433 |
+
query_states = self.q_proj(hidden_states)
|
434 |
+
key_states = self.k_proj(hidden_states)
|
435 |
+
value_states = self.v_proj(hidden_states)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
436 |
|
437 |
+
if self.qk_layernorm:
|
438 |
+
query_states = self.q_layernorm(query_states)
|
439 |
+
key_states = self.k_layernorm(key_states)
|
440 |
|
441 |
+
# Flash attention requires the input to have the shape
|
442 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
443 |
+
# therefore we just need to keep the original shape
|
444 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
445 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
446 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
447 |
|
448 |
+
kv_seq_len = key_states.shape[-2]
|
449 |
+
if past_key_value is not None:
|
450 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
451 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
452 |
|
453 |
+
# Partial rotary embedding
|
454 |
+
query_rot, query_pass = (
|
455 |
+
query_states[..., : self.rotary_emb.dim],
|
456 |
+
query_states[..., self.rotary_emb.dim :],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
457 |
)
|
458 |
+
key_rot, key_pass = (
|
459 |
+
key_states[..., : self.rotary_emb.dim],
|
460 |
+
key_states[..., self.rotary_emb.dim :],
|
461 |
+
)
|
462 |
+
# [batch_size, seq_length, num_heads, head_dim // config.partial_rotary_factor]
|
463 |
+
query_rot, key_rot = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
|
464 |
+
|
465 |
+
# [batch_size, seq_length, num_heads, head_dim]
|
466 |
+
query_states = torch.cat((query_rot, query_pass), dim=-1)
|
467 |
+
key_states = torch.cat((key_rot, key_pass), dim=-1)
|
468 |
+
|
469 |
+
if past_key_value is not None:
|
470 |
+
cache_kwargs = {"sin": sin, "cos": cos, "partial_rotation_size": self.rotary_emb.dim}
|
471 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
472 |
+
|
473 |
+
# 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
|
474 |
+
# to be able to avoid many of these transpose/reshape/view.
|
475 |
+
query_states = query_states.transpose(1, 2)
|
476 |
+
key_states = key_states.transpose(1, 2)
|
477 |
+
value_states = value_states.transpose(1, 2)
|
478 |
+
|
479 |
+
attn_dropout = self.attention_dropout if self.training else 0.0
|
480 |
+
|
481 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
482 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
483 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
484 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
485 |
+
# in fp32.
|
486 |
+
|
487 |
+
if query_states.dtype == torch.float32:
|
488 |
+
if torch.is_autocast_enabled():
|
489 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
490 |
+
# Handle the case where the model is quantized
|
491 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
492 |
+
target_dtype = self.config._pre_quantization_dtype
|
493 |
+
else:
|
494 |
+
target_dtype = self.q_proj.weight.dtype
|
495 |
|
496 |
+
logger.warning_once(
|
497 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
498 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
499 |
+
f" {target_dtype}."
|
500 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
501 |
|
502 |
+
query_states = query_states.to(target_dtype)
|
503 |
+
key_states = key_states.to(target_dtype)
|
504 |
+
value_states = value_states.to(target_dtype)
|
505 |
|
506 |
+
attn_output = self._flash_attention_forward(
|
507 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=attn_dropout, softmax_scale=1.0
|
508 |
+
)
|
509 |
|
510 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
511 |
+
attn_output = self.dense(attn_output)
|
512 |
+
|
513 |
+
if not output_attentions:
|
514 |
+
attn_weights = None
|
515 |
+
|
516 |
+
return attn_output, attn_weights, past_key_value
|
517 |
+
|
518 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
|
519 |
+
def _flash_attention_forward(
|
520 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
521 |
+
):
|
522 |
+
"""
|
523 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
524 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
525 |
+
|
526 |
+
Args:
|
527 |
+
query_states (`torch.Tensor`):
|
528 |
+
Input query states to be passed to Flash Attention API
|
529 |
+
key_states (`torch.Tensor`):
|
530 |
+
Input key states to be passed to Flash Attention API
|
531 |
+
value_states (`torch.Tensor`):
|
532 |
+
Input value states to be passed to Flash Attention API
|
533 |
+
attention_mask (`torch.Tensor`):
|
534 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
535 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
536 |
+
dropout (`int`, *optional*):
|
537 |
+
Attention dropout
|
538 |
+
softmax_scale (`float`, *optional*):
|
539 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
540 |
+
"""
|
541 |
+
if not self._flash_attn_uses_top_left_mask:
|
542 |
+
causal = self.is_causal
|
543 |
+
else:
|
544 |
+
# 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__.
|
545 |
+
causal = self.is_causal and query_length != 1
|
546 |
|
547 |
+
# Contains at least one padding token in the sequence
|
548 |
+
if attention_mask is not None:
|
549 |
+
batch_size = query_states.shape[0]
|
550 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
551 |
+
query_states, key_states, value_states, attention_mask, query_length
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
552 |
)
|
553 |
|
554 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
555 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
556 |
+
|
557 |
+
attn_output_unpad = flash_attn_varlen_func(
|
558 |
+
query_states,
|
559 |
+
key_states,
|
560 |
+
value_states,
|
561 |
+
cu_seqlens_q=cu_seqlens_q,
|
562 |
+
cu_seqlens_k=cu_seqlens_k,
|
563 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
564 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
565 |
+
dropout_p=dropout,
|
566 |
+
softmax_scale=softmax_scale,
|
567 |
+
causal=causal,
|
568 |
+
)
|
569 |
|
570 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
571 |
+
else:
|
572 |
+
attn_output = flash_attn_func(
|
573 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
574 |
+
)
|
575 |
|
576 |
+
return attn_output
|
|
|
|
|
|
|
577 |
|
578 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
|
579 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
580 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
581 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
582 |
|
583 |
+
key_layer = index_first_axis(
|
584 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
|
|
|
|
585 |
)
|
586 |
+
value_layer = index_first_axis(
|
587 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
588 |
+
)
|
589 |
+
if query_length == kv_seq_len:
|
590 |
+
query_layer = index_first_axis(
|
591 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
592 |
+
)
|
593 |
+
cu_seqlens_q = cu_seqlens_k
|
594 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
595 |
+
indices_q = indices_k
|
596 |
+
elif query_length == 1:
|
597 |
+
max_seqlen_in_batch_q = 1
|
598 |
+
cu_seqlens_q = torch.arange(
|
599 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
600 |
+
) # There is a memcpy here, that is very bad.
|
601 |
+
indices_q = cu_seqlens_q[:-1]
|
602 |
+
query_layer = query_layer.squeeze(1)
|
603 |
+
else:
|
604 |
+
# The -q_len: slice assumes left padding.
|
605 |
+
attention_mask = attention_mask[:, -query_length:]
|
606 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
607 |
+
|
608 |
+
return (
|
609 |
+
query_layer,
|
610 |
+
key_layer,
|
611 |
+
value_layer,
|
612 |
+
indices_q,
|
613 |
+
(cu_seqlens_q, cu_seqlens_k),
|
614 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
615 |
)
|
616 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
617 |
|
618 |
+
PHI_ATTENTION_CLASSES = {
|
619 |
+
"eager": PhiAttention,
|
620 |
+
"flash_attention_2": PhiFlashAttention2,
|
621 |
+
}
|
622 |
|
|
|
|
|
623 |
|
624 |
+
class PhiDecoderLayer(nn.Module):
|
625 |
+
def __init__(self, config: PhiConfig, layer_idx: int):
|
626 |
+
super().__init__()
|
627 |
+
self.self_attn = PHI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
|
628 |
+
self.mlp = PhiMLP(config)
|
629 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
630 |
+
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
631 |
|
632 |
+
def forward(
|
633 |
self,
|
634 |
+
hidden_states: torch.Tensor,
|
635 |
+
attention_mask: Optional[torch.Tensor] = None,
|
636 |
+
position_ids: Optional[torch.LongTensor] = None,
|
637 |
+
output_attentions: Optional[bool] = False,
|
638 |
+
use_cache: Optional[bool] = False,
|
639 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
640 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
641 |
+
"""
|
642 |
+
Args:
|
643 |
+
hidden_states (`torch.FloatTensor`):
|
644 |
+
input to the layer of shape `(batch, seq_len, embed_dim)`
|
645 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
646 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
647 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
648 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
|
649 |
+
`[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
650 |
+
output_attentions (`bool`, *optional*):
|
651 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
652 |
+
returned tensors for more detail.
|
653 |
+
use_cache (`bool`, *optional*):
|
654 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
655 |
+
(see `past_key_values`).
|
656 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
657 |
+
"""
|
658 |
|
659 |
+
residual = hidden_states
|
660 |
|
661 |
+
hidden_states = self.input_layernorm(hidden_states)
|
|
|
662 |
|
663 |
+
# Self Attention
|
664 |
+
attn_outputs, self_attn_weights, present_key_value = self.self_attn(
|
665 |
+
hidden_states=hidden_states,
|
666 |
+
attention_mask=attention_mask,
|
667 |
+
position_ids=position_ids,
|
668 |
+
past_key_value=past_key_value,
|
669 |
+
output_attentions=output_attentions,
|
670 |
+
use_cache=use_cache,
|
671 |
+
)
|
672 |
+
attn_outputs = self.resid_dropout(attn_outputs)
|
673 |
|
674 |
+
feed_forward_hidden_states = self.resid_dropout(self.mlp(hidden_states))
|
675 |
+
hidden_states = attn_outputs + feed_forward_hidden_states + residual
|
676 |
+
outputs = (hidden_states,)
|
|
|
677 |
|
678 |
+
if output_attentions:
|
679 |
+
outputs += (self_attn_weights,)
|
680 |
|
681 |
+
if use_cache:
|
682 |
+
outputs += (present_key_value,)
|
|
|
683 |
|
684 |
+
return outputs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
685 |
|
|
|
|
|
|
|
|
|
|
|
686 |
|
687 |
+
PHI_START_DOCSTRING = r"""
|
688 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
689 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
690 |
+
etc.)
|
|
|
|
|
|
|
|
|
691 |
|
692 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
693 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
694 |
+
and behavior.
|
695 |
|
696 |
+
Parameters:
|
697 |
+
config ([`PhiConfig`]):
|
698 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
699 |
+
load the weights associated with the model, only the configuration. Check out the
|
700 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
701 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
702 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
703 |
|
704 |
+
@add_start_docstrings(
|
705 |
+
"The bare Phi Model outputting raw hidden-states without any specific head on top.",
|
706 |
+
PHI_START_DOCSTRING,
|
707 |
+
)
|
708 |
+
class PhiPreTrainedModel(PreTrainedModel):
|
709 |
+
config_class = PhiConfig
|
710 |
+
base_model_prefix = "model"
|
711 |
+
supports_gradient_checkpointing = True
|
712 |
+
_no_split_modules = ["PhiDecoderLayer"]
|
713 |
+
_skip_keys_device_placement = "past_key_values"
|
714 |
+
_supports_flash_attn_2 = True
|
715 |
+
_supports_cache_class = True
|
716 |
+
|
717 |
+
def _init_weights(self, module):
|
718 |
+
std = self.config.initializer_range
|
719 |
+
if isinstance(module, nn.Linear):
|
720 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
721 |
+
if module.bias is not None:
|
722 |
+
module.bias.data.zero_()
|
723 |
+
elif isinstance(module, nn.Embedding):
|
724 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
725 |
+
if module.padding_idx is not None:
|
726 |
+
module.weight.data[module.padding_idx].zero_()
|
727 |
|
|
|
728 |
|
729 |
+
PHI_INPUTS_DOCSTRING = r"""
|
730 |
+
Args:
|
731 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
732 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
733 |
+
it.
|
734 |
+
|
735 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
736 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
737 |
+
|
738 |
+
[What are input IDs?](../glossary#input-ids)
|
739 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
740 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
741 |
+
|
742 |
+
- 1 for tokens that are **not masked**,
|
743 |
+
- 0 for tokens that are **masked**.
|
744 |
+
|
745 |
+
[What are attention masks?](../glossary#attention-mask)
|
746 |
+
|
747 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
748 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
749 |
+
|
750 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
751 |
+
`past_key_values`).
|
752 |
+
|
753 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
754 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
755 |
+
information on the default strategy.
|
756 |
+
|
757 |
+
- 1 indicates the head is **not masked**,
|
758 |
+
- 0 indicates the head is **masked**.
|
759 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
760 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
761 |
+
config.n_positions - 1]`.
|
762 |
+
|
763 |
+
[What are position IDs?](../glossary#position-ids)
|
764 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
765 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
766 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
767 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
768 |
+
|
769 |
+
Two formats are allowed:
|
770 |
+
- a [`~cache_utils.Cache`] instance;
|
771 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
772 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
773 |
+
cache format.
|
774 |
+
|
775 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
776 |
+
legacy cache format will be returned.
|
777 |
+
|
778 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
779 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
780 |
+
of shape `(batch_size, sequence_length)`.
|
781 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
782 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
783 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
784 |
+
model's internal embedding lookup matrix.
|
785 |
+
use_cache (`bool`, *optional*):
|
786 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
787 |
+
`past_key_values`).
|
788 |
+
output_attentions (`bool`, *optional*):
|
789 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
790 |
+
tensors for more detail.
|
791 |
+
output_hidden_states (`bool`, *optional*):
|
792 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
793 |
+
more detail.
|
794 |
+
return_dict (`bool`, *optional*):
|
795 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
796 |
+
"""
|
797 |
+
|
798 |
+
|
799 |
+
@add_start_docstrings(
|
800 |
+
"The bare Phi Model outputting raw hidden-states without any specific head on top.",
|
801 |
+
PHI_START_DOCSTRING,
|
802 |
+
)
|
803 |
+
class PhiModel(PhiPreTrainedModel):
|
804 |
+
"""
|
805 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhiDecoderLayer`]
|
806 |
|
807 |
+
Args:
|
808 |
+
config: PhiConfig
|
809 |
+
"""
|
810 |
|
811 |
+
def __init__(self, config: PhiConfig):
|
812 |
+
super().__init__(config)
|
813 |
+
self.padding_idx = config.pad_token_id
|
814 |
+
self.vocab_size = config.vocab_size
|
815 |
|
816 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
817 |
+
self.embed_dropout = nn.Dropout(config.embd_pdrop)
|
818 |
+
self.layers = nn.ModuleList(
|
819 |
+
[PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
820 |
+
)
|
821 |
+
self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
822 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
823 |
|
824 |
+
self.gradient_checkpointing = False
|
825 |
+
# Initialize weights and apply final processing
|
826 |
+
self.post_init()
|
|
|
|
|
|
|
827 |
|
828 |
+
def get_input_embeddings(self):
|
829 |
+
return self.embed_tokens
|
|
|
830 |
|
831 |
+
def set_input_embeddings(self, value):
|
832 |
+
self.embed_tokens = value
|
833 |
|
834 |
+
@add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
|
835 |
def forward(
|
836 |
self,
|
837 |
+
input_ids: torch.LongTensor = None,
|
838 |
+
attention_mask: Optional[torch.Tensor] = None,
|
839 |
+
position_ids: Optional[torch.LongTensor] = None,
|
840 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
841 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
842 |
+
use_cache: Optional[bool] = None,
|
843 |
+
output_attentions: Optional[bool] = None,
|
844 |
+
output_hidden_states: Optional[bool] = None,
|
845 |
+
return_dict: Optional[bool] = None,
|
846 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
847 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
848 |
+
output_hidden_states = (
|
849 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
850 |
)
|
851 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
|
|
|
|
|
|
|
|
852 |
|
853 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
854 |
|
855 |
+
# retrieve input_ids and inputs_embeds
|
856 |
+
if input_ids is not None and inputs_embeds is not None:
|
857 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
858 |
+
elif input_ids is not None:
|
859 |
+
batch_size, seq_length = input_ids.shape[:2]
|
860 |
+
elif inputs_embeds is not None:
|
861 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
862 |
+
else:
|
863 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
864 |
|
865 |
+
past_key_values_length = 0
|
866 |
|
867 |
+
if self.gradient_checkpointing and self.training:
|
868 |
+
if use_cache:
|
869 |
+
logger.warning_once(
|
870 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
871 |
+
)
|
872 |
+
use_cache = False
|
873 |
+
|
874 |
+
if use_cache:
|
875 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
876 |
+
if use_legacy_cache:
|
877 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
878 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
879 |
+
|
880 |
+
if position_ids is None:
|
881 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
882 |
+
position_ids = torch.arange(
|
883 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
884 |
+
)
|
885 |
+
position_ids = position_ids.unsqueeze(0)
|
886 |
|
887 |
+
if inputs_embeds is None:
|
888 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
|
|
889 |
|
890 |
+
inputs_embeds = self.embed_dropout(inputs_embeds)
|
891 |
|
892 |
+
# Attention mask.
|
893 |
+
if self._use_flash_attention_2:
|
894 |
+
# 2d mask is passed through the layers
|
895 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
896 |
+
else:
|
897 |
+
# 4d mask is passed through the layers
|
898 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
899 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
900 |
+
)
|
901 |
|
902 |
+
hidden_states = inputs_embeds
|
903 |
+
|
904 |
+
# decoder layers
|
905 |
+
all_hidden_states = () if output_hidden_states else None
|
906 |
+
all_self_attns = () if output_attentions else None
|
907 |
+
next_decoder_cache = None
|
908 |
+
|
909 |
+
for decoder_layer in self.layers:
|
910 |
+
if output_hidden_states:
|
911 |
+
all_hidden_states += (hidden_states,)
|
912 |
+
|
913 |
+
if self.gradient_checkpointing and self.training:
|
914 |
+
layer_outputs = self._gradient_checkpointing_func(
|
915 |
+
decoder_layer.__call__,
|
916 |
+
hidden_states,
|
917 |
+
attention_mask,
|
918 |
+
position_ids,
|
919 |
+
past_key_values,
|
920 |
+
output_attentions,
|
921 |
+
)
|
922 |
+
else:
|
923 |
+
layer_outputs = decoder_layer(
|
924 |
+
hidden_states,
|
925 |
+
attention_mask=attention_mask,
|
926 |
+
position_ids=position_ids,
|
927 |
+
past_key_value=past_key_values,
|
928 |
+
output_attentions=output_attentions,
|
929 |
+
use_cache=use_cache,
|
930 |
+
)
|
931 |
|
932 |
+
hidden_states = layer_outputs[0]
|
|
|
|
|
933 |
|
934 |
+
if use_cache:
|
935 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
936 |
|
937 |
+
if output_attentions:
|
938 |
+
all_self_attns += (layer_outputs[1],)
|
939 |
|
940 |
+
hidden_states = self.final_layernorm(hidden_states)
|
|
|
941 |
|
942 |
+
# add hidden states from the last decoder layer
|
943 |
+
if output_hidden_states:
|
944 |
+
all_hidden_states += (hidden_states,)
|
945 |
|
946 |
+
next_cache = None
|
947 |
+
if use_cache:
|
948 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
949 |
+
if not return_dict:
|
950 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
951 |
+
return BaseModelOutputWithPast(
|
952 |
+
last_hidden_state=hidden_states,
|
953 |
+
past_key_values=next_cache,
|
954 |
+
hidden_states=all_hidden_states,
|
955 |
+
attentions=all_self_attns,
|
956 |
+
)
|
957 |
|
|
|
|
|
958 |
|
959 |
+
class PhiForCausalLM(PhiPreTrainedModel):
|
960 |
+
_tied_weights_keys = ["lm_head.weight"]
|
961 |
|
962 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi,bias=False->bias=True
|
963 |
+
def __init__(self, config):
|
964 |
+
super().__init__(config)
|
965 |
+
self.model = PhiModel(config)
|
966 |
+
self.vocab_size = config.vocab_size
|
967 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
|
968 |
|
969 |
+
# Initialize weights and apply final processing
|
970 |
+
self.post_init()
|
971 |
|
972 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
|
973 |
+
def get_input_embeddings(self):
|
974 |
+
return self.model.embed_tokens
|
975 |
|
976 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
|
977 |
+
def set_input_embeddings(self, value):
|
978 |
+
self.model.embed_tokens = value
|
979 |
|
980 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
|
981 |
+
def get_output_embeddings(self):
|
982 |
+
return self.lm_head
|
983 |
|
984 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
|
985 |
+
def set_output_embeddings(self, new_embeddings):
|
986 |
+
self.lm_head = new_embeddings
|
|
|
987 |
|
988 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
|
989 |
+
def set_decoder(self, decoder):
|
990 |
+
self.model = decoder
|
991 |
|
992 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
|
993 |
+
def get_decoder(self):
|
994 |
+
return self.model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
995 |
|
996 |
+
@add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
|
997 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
998 |
+
def forward(
|
999 |
self,
|
1000 |
+
input_ids: torch.LongTensor = None,
|
1001 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1002 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1003 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1004 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1005 |
+
labels: Optional[torch.LongTensor] = None,
|
1006 |
+
use_cache: Optional[bool] = None,
|
1007 |
+
output_attentions: Optional[bool] = None,
|
1008 |
+
output_hidden_states: Optional[bool] = None,
|
1009 |
+
return_dict: Optional[bool] = None,
|
1010 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1011 |
+
r"""
|
1012 |
+
Args:
|
1013 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1014 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1015 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1016 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1017 |
+
|
1018 |
+
Returns:
|
1019 |
+
|
1020 |
+
Example:
|
1021 |
+
|
1022 |
+
```python
|
1023 |
+
>>> from transformers import AutoTokenizer, PhiForCausalLM
|
1024 |
+
|
1025 |
+
>>> model = PhiForCausalLM.from_pretrained("microsoft/phi-1")
|
1026 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")
|
1027 |
+
|
1028 |
+
>>> prompt = "This is an example script ."
|
1029 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1030 |
+
|
1031 |
+
>>> # Generate
|
1032 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1033 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1034 |
+
'This is an example script .\n\n\n\nfrom typing import List\n\ndef find_most_common_letter(words: List[str'
|
1035 |
+
```"""
|
1036 |
+
|
1037 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1038 |
+
output_hidden_states = (
|
1039 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1040 |
+
)
|
1041 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1042 |
|
1043 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1044 |
+
outputs = self.model(
|
1045 |
+
input_ids=input_ids,
|
1046 |
+
attention_mask=attention_mask,
|
1047 |
+
position_ids=position_ids,
|
1048 |
+
past_key_values=past_key_values,
|
1049 |
+
inputs_embeds=inputs_embeds,
|
1050 |
+
use_cache=use_cache,
|
1051 |
+
output_attentions=output_attentions,
|
1052 |
+
output_hidden_states=output_hidden_states,
|
1053 |
+
return_dict=return_dict,
|
1054 |
+
)
|
1055 |
|
1056 |
+
hidden_states = outputs[0]
|
1057 |
+
logits = self.lm_head(hidden_states)
|
1058 |
+
logits = logits.float()
|
1059 |
|
1060 |
+
loss = None
|
1061 |
+
if labels is not None:
|
1062 |
+
# Shift so that tokens < n predict n
|
1063 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1064 |
+
shift_labels = labels[..., 1:].contiguous()
|
1065 |
+
# Flatten the tokens
|
1066 |
+
loss_fct = CrossEntropyLoss()
|
1067 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1068 |
+
shift_labels = shift_labels.view(-1)
|
1069 |
+
# Enable model parallelism
|
1070 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1071 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1072 |
+
|
1073 |
+
if not return_dict:
|
1074 |
+
output = (logits,) + outputs[1:]
|
1075 |
+
return (loss,) + output if loss is not None else output
|
1076 |
+
|
1077 |
+
return CausalLMOutputWithPast(
|
1078 |
+
loss=loss,
|
1079 |
+
logits=logits,
|
1080 |
+
past_key_values=outputs.past_key_values,
|
1081 |
+
hidden_states=outputs.hidden_states,
|
1082 |
+
attentions=outputs.attentions,
|
1083 |
+
)
|
1084 |
+
|
1085 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
|
1086 |
+
def prepare_inputs_for_generation(
|
1087 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
1088 |
+
):
|
1089 |
+
if past_key_values is not None:
|
1090 |
+
if isinstance(past_key_values, Cache):
|
1091 |
+
cache_length = past_key_values.get_seq_length()
|
1092 |
+
past_length = past_key_values.seen_tokens
|
1093 |
+
max_cache_length = past_key_values.get_max_length()
|
1094 |
+
else:
|
1095 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1096 |
+
max_cache_length = None
|
1097 |
+
|
1098 |
+
# Keep only the unprocessed tokens:
|
1099 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1100 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1101 |
+
# input)
|
1102 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1103 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1104 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1105 |
+
# input_ids based on the past_length.
|
1106 |
+
elif past_length < input_ids.shape[1]:
|
1107 |
+
input_ids = input_ids[:, past_length:]
|
1108 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1109 |
+
|
1110 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1111 |
+
if (
|
1112 |
+
max_cache_length is not None
|
1113 |
+
and attention_mask is not None
|
1114 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1115 |
+
):
|
1116 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1117 |
+
|
1118 |
+
position_ids = kwargs.get("position_ids", None)
|
1119 |
+
if attention_mask is not None and position_ids is None:
|
1120 |
+
# create position_ids on the fly for batch generation
|
1121 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1122 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1123 |
+
if past_key_values:
|
1124 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1125 |
+
|
1126 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1127 |
+
if inputs_embeds is not None and past_key_values is None:
|
1128 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1129 |
+
else:
|
1130 |
+
model_inputs = {"input_ids": input_ids}
|
1131 |
+
|
1132 |
+
model_inputs.update(
|
1133 |
+
{
|
1134 |
+
"position_ids": position_ids,
|
1135 |
+
"past_key_values": past_key_values,
|
1136 |
+
"use_cache": kwargs.get("use_cache"),
|
1137 |
+
"attention_mask": attention_mask,
|
1138 |
+
}
|
1139 |
+
)
|
1140 |
+
return model_inputs
|
1141 |
+
|
1142 |
+
@staticmethod
|
1143 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
|
1144 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1145 |
+
reordered_past = ()
|
1146 |
+
for layer_past in past_key_values:
|
1147 |
+
reordered_past += (
|
1148 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1149 |
+
)
|
1150 |
+
return reordered_past
|
1151 |
|
|
|
|
|
1152 |
|
1153 |
+
@add_start_docstrings(
|
1154 |
+
"""
|
1155 |
+
The PhiModel with a sequence classification head on top (linear layer).
|
1156 |
+
|
1157 |
+
[`PhiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1158 |
+
(e.g. GPT-2) do.
|
1159 |
+
|
1160 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1161 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1162 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1163 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1164 |
+
each row of the batch).
|
1165 |
+
""",
|
1166 |
+
PHI_START_DOCSTRING,
|
1167 |
+
)
|
1168 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->PHI,Llama->Phi with self.transformer->self.model, transformer_outputs->model_outputs
|
1169 |
+
class PhiForSequenceClassification(PhiPreTrainedModel):
|
1170 |
+
def __init__(self, config):
|
1171 |
super().__init__(config)
|
1172 |
+
self.num_labels = config.num_labels
|
1173 |
+
self.model = PhiModel(config)
|
1174 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1175 |
|
1176 |
+
# Initialize weights and apply final processing
|
|
|
|
|
1177 |
self.post_init()
|
1178 |
|
1179 |
+
def get_input_embeddings(self):
|
1180 |
+
return self.model.embed_tokens
|
1181 |
|
1182 |
+
def set_input_embeddings(self, value):
|
1183 |
+
self.model.embed_tokens = value
|
1184 |
|
1185 |
+
@add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
|
1186 |
def forward(
|
1187 |
self,
|
1188 |
+
input_ids: torch.LongTensor = None,
|
1189 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1190 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1191 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1192 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1193 |
+
labels: Optional[torch.LongTensor] = None,
|
1194 |
+
use_cache: Optional[bool] = None,
|
1195 |
+
output_attentions: Optional[bool] = None,
|
1196 |
+
output_hidden_states: Optional[bool] = None,
|
1197 |
+
return_dict: Optional[bool] = None,
|
1198 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1199 |
+
r"""
|
1200 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1201 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1202 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1203 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1204 |
+
"""
|
1205 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1206 |
+
|
1207 |
+
model_outputs = self.model(
|
1208 |
+
input_ids,
|
1209 |
+
attention_mask=attention_mask,
|
1210 |
+
position_ids=position_ids,
|
1211 |
+
past_key_values=past_key_values,
|
1212 |
+
inputs_embeds=inputs_embeds,
|
1213 |
+
use_cache=use_cache,
|
1214 |
+
output_attentions=output_attentions,
|
1215 |
+
output_hidden_states=output_hidden_states,
|
1216 |
+
return_dict=return_dict,
|
1217 |
+
)
|
1218 |
+
hidden_states = model_outputs[0]
|
1219 |
+
logits = self.score(hidden_states)
|
1220 |
|
1221 |
+
if input_ids is not None:
|
1222 |
+
batch_size = input_ids.shape[0]
|
1223 |
+
else:
|
1224 |
+
batch_size = inputs_embeds.shape[0]
|
1225 |
|
1226 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1227 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1228 |
+
if self.config.pad_token_id is None:
|
1229 |
+
sequence_lengths = -1
|
1230 |
+
else:
|
1231 |
+
if input_ids is not None:
|
1232 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1233 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1234 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1235 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1236 |
+
else:
|
1237 |
+
sequence_lengths = -1
|
1238 |
|
1239 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1240 |
+
|
1241 |
+
loss = None
|
1242 |
+
if labels is not None:
|
1243 |
+
labels = labels.to(logits.device)
|
1244 |
+
if self.config.problem_type is None:
|
1245 |
+
if self.num_labels == 1:
|
1246 |
+
self.config.problem_type = "regression"
|
1247 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1248 |
+
self.config.problem_type = "single_label_classification"
|
1249 |
+
else:
|
1250 |
+
self.config.problem_type = "multi_label_classification"
|
1251 |
+
|
1252 |
+
if self.config.problem_type == "regression":
|
1253 |
+
loss_fct = MSELoss()
|
1254 |
+
if self.num_labels == 1:
|
1255 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1256 |
+
else:
|
1257 |
+
loss = loss_fct(pooled_logits, labels)
|
1258 |
+
elif self.config.problem_type == "single_label_classification":
|
1259 |
+
loss_fct = CrossEntropyLoss()
|
1260 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1261 |
+
elif self.config.problem_type == "multi_label_classification":
|
1262 |
+
loss_fct = BCEWithLogitsLoss()
|
1263 |
+
loss = loss_fct(pooled_logits, labels)
|
1264 |
+
if not return_dict:
|
1265 |
+
output = (pooled_logits,) + model_outputs[1:]
|
1266 |
+
return ((loss,) + output) if loss is not None else output
|
1267 |
+
|
1268 |
+
return SequenceClassifierOutputWithPast(
|
1269 |
+
loss=loss,
|
1270 |
+
logits=pooled_logits,
|
1271 |
+
past_key_values=model_outputs.past_key_values,
|
1272 |
+
hidden_states=model_outputs.hidden_states,
|
1273 |
+
attentions=model_outputs.attentions,
|
1274 |
+
)
|
1275 |
|
|
|
|
|
1276 |
|
1277 |
+
@add_start_docstrings(
|
1278 |
+
"""
|
1279 |
+
PhiModel with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
1280 |
+
Named-Entity-Recognition (NER) tasks.
|
1281 |
+
""",
|
1282 |
+
PHI_START_DOCSTRING,
|
1283 |
+
)
|
1284 |
+
# Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with MPT->PHI,Mpt->Phi,self.transformer->self.model,transformer_outputs->model_outputs
|
1285 |
+
class PhiForTokenClassification(PhiPreTrainedModel):
|
1286 |
+
def __init__(self, config: PhiConfig):
|
1287 |
super().__init__(config)
|
1288 |
+
self.num_labels = config.num_labels
|
1289 |
|
1290 |
+
self.model = PhiModel(config)
|
1291 |
+
if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
|
1292 |
+
classifier_dropout = config.classifier_dropout
|
1293 |
+
elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
|
1294 |
+
classifier_dropout = config.hidden_dropout
|
1295 |
+
else:
|
1296 |
+
classifier_dropout = 0.1
|
1297 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1298 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1299 |
|
1300 |
+
# Initialize weights and apply final processing
|
1301 |
self.post_init()
|
1302 |
|
1303 |
+
@add_start_docstrings_to_model_forward(PHI_INPUTS_DOCSTRING)
|
1304 |
+
@add_code_sample_docstrings(
|
1305 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1306 |
+
output_type=TokenClassifierOutput,
|
1307 |
+
config_class=_CONFIG_FOR_DOC,
|
1308 |
+
)
|
1309 |
def forward(
|
1310 |
self,
|
1311 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1312 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
|
1313 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1314 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1315 |
+
labels: Optional[torch.Tensor] = None,
|
1316 |
+
use_cache: Optional[bool] = None,
|
1317 |
+
output_attentions: Optional[bool] = None,
|
1318 |
+
output_hidden_states: Optional[bool] = None,
|
1319 |
+
return_dict: Optional[bool] = None,
|
1320 |
+
**deprecated_arguments,
|
1321 |
+
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
1322 |
+
r"""
|
1323 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1324 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1325 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1326 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1327 |
+
"""
|
1328 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1329 |
+
|
1330 |
+
model_outputs = self.model(
|
1331 |
+
input_ids,
|
1332 |
+
past_key_values=past_key_values,
|
1333 |
+
attention_mask=attention_mask,
|
1334 |
+
inputs_embeds=inputs_embeds,
|
1335 |
+
use_cache=use_cache,
|
1336 |
+
output_attentions=output_attentions,
|
1337 |
+
output_hidden_states=output_hidden_states,
|
1338 |
+
return_dict=return_dict,
|
1339 |
+
)
|
1340 |
+
|
1341 |
+
hidden_states = model_outputs[0]
|
1342 |
+
hidden_states = self.dropout(hidden_states)
|
1343 |
+
logits = self.classifier(hidden_states)
|
1344 |
|
1345 |
loss = None
|
1346 |
if labels is not None:
|
1347 |
+
# move labels to correct device to enable model parallelism
|
1348 |
+
labels = labels.to(logits.device)
|
1349 |
+
batch_size, seq_length = labels.shape
|
1350 |
+
loss_fct = CrossEntropyLoss()
|
1351 |
+
loss = loss_fct(
|
1352 |
+
logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
|
1353 |
+
)
|
1354 |
+
|
1355 |
+
if not return_dict:
|
1356 |
+
output = (logits,) + model_outputs[2:]
|
1357 |
+
return ((loss,) + output) if loss is not None else output
|
1358 |
|
1359 |
+
return TokenClassifierOutput(
|
1360 |
+
loss=loss,
|
1361 |
+
logits=logits,
|
1362 |
+
hidden_states=model_outputs.hidden_states,
|
1363 |
+
attentions=model_outputs.attentions,
|
1364 |
+
)
|