Commit
•
7d3f15f
1
Parent(s):
0c87b6a
Upload 18 files
Browse files- config.json +33 -0
- configuration_llama.py +187 -0
- generation_config.json +7 -0
- latest +1 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +394 -0
- modeling_llama.py +1412 -0
- qwen.tiktoken +0 -0
- special_tokens_map.json +12 -0
- tokenization_qwen.py +276 -0
- tokenizer_config.json +19 -0
- trainer_state.json +0 -0
- training_args.bin +3 -0
- zero_to_fp32.py +592 -0
config.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "xxx",
|
3 |
+
"architectures": [
|
4 |
+
"AquilaForCausalLM"
|
5 |
+
],
|
6 |
+
"attention_dropout": 0.0,
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_llama.LlamaConfig",
|
9 |
+
"AutoModel": "modeling_llama.LlamaForCausalLM",
|
10 |
+
"AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM"
|
11 |
+
},
|
12 |
+
"bos_token_id": 151849,
|
13 |
+
"eos_token_id": 151850,
|
14 |
+
"hidden_act": "silu",
|
15 |
+
"hidden_size": 4096,
|
16 |
+
"initializer_range": 0.02,
|
17 |
+
"intermediate_size": 14336,
|
18 |
+
"max_position_embeddings": 4096,
|
19 |
+
"model_type": "aquila3",
|
20 |
+
"num_attention_heads": 32,
|
21 |
+
"num_hidden_layers": 32,
|
22 |
+
"num_key_value_heads": 8,
|
23 |
+
"pad_token_id": 151643,
|
24 |
+
"pretraining_tp": 1,
|
25 |
+
"rms_norm_eps": 1e-05,
|
26 |
+
"rope_scaling": null,
|
27 |
+
"rope_theta": 1000000.0,
|
28 |
+
"tie_word_embeddings": false,
|
29 |
+
"torch_dtype": "bfloat16",
|
30 |
+
"transformers_version": "4.38.2",
|
31 |
+
"use_cache": false,
|
32 |
+
"vocab_size": 151851
|
33 |
+
}
|
configuration_llama.py
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" LLaMA model configuration"""
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.utils import logging
|
24 |
+
|
25 |
+
|
26 |
+
logger = logging.get_logger(__name__)
|
27 |
+
|
28 |
+
LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
29 |
+
|
30 |
+
|
31 |
+
class LlamaConfig(PretrainedConfig):
|
32 |
+
r"""
|
33 |
+
This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
|
34 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
35 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
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 |
+
|
41 |
+
Args:
|
42 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
43 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
44 |
+
`inputs_ids` passed when calling [`LlamaModel`]
|
45 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
46 |
+
Dimension of the hidden representations.
|
47 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
48 |
+
Dimension of the MLP representations.
|
49 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
50 |
+
Number of hidden layers in the Transformer decoder.
|
51 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
52 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
53 |
+
num_key_value_heads (`int`, *optional*):
|
54 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
55 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
56 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
57 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
58 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
59 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
60 |
+
`num_attention_heads`.
|
61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
62 |
+
The non-linear activation function (function or string) in the decoder.
|
63 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
64 |
+
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
65 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
66 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
67 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
68 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
69 |
+
The epsilon used by the rms normalization layers.
|
70 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
71 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
72 |
+
relevant if `config.is_decoder=True`.
|
73 |
+
pad_token_id (`int`, *optional*):
|
74 |
+
Padding token id.
|
75 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
76 |
+
Beginning of stream token id.
|
77 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
78 |
+
End of stream token id.
|
79 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
80 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
81 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
82 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
83 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
84 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
85 |
+
Whether to tie weight embeddings
|
86 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
87 |
+
The base period of the RoPE embeddings.
|
88 |
+
rope_scaling (`Dict`, *optional*):
|
89 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
90 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
91 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
92 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
93 |
+
these scaling strategies behave:
|
94 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
95 |
+
experimental feature, subject to breaking API changes in future versions.
|
96 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
97 |
+
The dropout ratio for the attention probabilities.
|
98 |
+
|
99 |
+
```python
|
100 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
101 |
+
|
102 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
103 |
+
>>> configuration = LlamaConfig()
|
104 |
+
|
105 |
+
>>> # Initializing a model from the llama-7b style configuration
|
106 |
+
>>> model = LlamaModel(configuration)
|
107 |
+
|
108 |
+
>>> # Accessing the model configuration
|
109 |
+
>>> configuration = model.config
|
110 |
+
```"""
|
111 |
+
|
112 |
+
model_type = "aquila3"
|
113 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
114 |
+
|
115 |
+
def __init__(
|
116 |
+
self,
|
117 |
+
vocab_size=32000,
|
118 |
+
hidden_size=4096,
|
119 |
+
intermediate_size=11008,
|
120 |
+
num_hidden_layers=32,
|
121 |
+
num_attention_heads=32,
|
122 |
+
num_key_value_heads=None,
|
123 |
+
hidden_act="silu",
|
124 |
+
max_position_embeddings=2048,
|
125 |
+
initializer_range=0.02,
|
126 |
+
rms_norm_eps=1e-6,
|
127 |
+
use_cache=True,
|
128 |
+
pad_token_id=None,
|
129 |
+
bos_token_id=1,
|
130 |
+
eos_token_id=2,
|
131 |
+
pretraining_tp=1,
|
132 |
+
tie_word_embeddings=False,
|
133 |
+
rope_theta=10000.0,
|
134 |
+
rope_scaling=None,
|
135 |
+
attention_dropout=0.0,
|
136 |
+
**kwargs,
|
137 |
+
):
|
138 |
+
self.vocab_size = vocab_size
|
139 |
+
self.max_position_embeddings = max_position_embeddings
|
140 |
+
self.hidden_size = hidden_size
|
141 |
+
self.intermediate_size = intermediate_size
|
142 |
+
self.num_hidden_layers = num_hidden_layers
|
143 |
+
self.num_attention_heads = num_attention_heads
|
144 |
+
|
145 |
+
# for backward compatibility
|
146 |
+
if num_key_value_heads is None:
|
147 |
+
num_key_value_heads = num_attention_heads
|
148 |
+
|
149 |
+
self.num_key_value_heads = num_key_value_heads
|
150 |
+
self.hidden_act = hidden_act
|
151 |
+
self.initializer_range = initializer_range
|
152 |
+
self.rms_norm_eps = rms_norm_eps
|
153 |
+
self.pretraining_tp = pretraining_tp
|
154 |
+
self.use_cache = use_cache
|
155 |
+
self.rope_theta = rope_theta
|
156 |
+
self.rope_scaling = rope_scaling
|
157 |
+
self._rope_scaling_validation()
|
158 |
+
self.attention_dropout = attention_dropout
|
159 |
+
|
160 |
+
super().__init__(
|
161 |
+
pad_token_id=pad_token_id,
|
162 |
+
bos_token_id=bos_token_id,
|
163 |
+
eos_token_id=eos_token_id,
|
164 |
+
tie_word_embeddings=tie_word_embeddings,
|
165 |
+
**kwargs,
|
166 |
+
)
|
167 |
+
|
168 |
+
def _rope_scaling_validation(self):
|
169 |
+
"""
|
170 |
+
Validate the `rope_scaling` configuration.
|
171 |
+
"""
|
172 |
+
if self.rope_scaling is None:
|
173 |
+
return
|
174 |
+
|
175 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
176 |
+
raise ValueError(
|
177 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
178 |
+
f"got {self.rope_scaling}"
|
179 |
+
)
|
180 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
181 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
182 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
183 |
+
raise ValueError(
|
184 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
185 |
+
)
|
186 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
187 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 151849,
|
4 |
+
"eos_token_id": 151850,
|
5 |
+
"pad_token_id": 151643,
|
6 |
+
"transformers_version": "4.38.2"
|
7 |
+
}
|
latest
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
global_step350
|
model-00001-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:49b47f6f7e15fa83b767fb86c4bacf1f6427b9fac9daf861e280f1255b4cf531
|
3 |
+
size 4935204608
|
model-00002-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:747312bf1c6100f31d24fe53ffb60cb9e9bb4875eff81d8373e157a6abb58f62
|
3 |
+
size 4916054976
|
model-00003-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d7c4c5f6bf6cc6d9891de27920c7b4f6f7eaaa6425601c5db80c5a9a11c94e86
|
3 |
+
size 4999970776
|
model-00004-of-00004.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2753c16a13446e53cc2f92cf5bcdc9cf8f30e05ebbff0a768d19aeaf48cdf100
|
3 |
+
size 1596310304
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 16447496192
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"lm_head.weight": "model-00004-of-00004.safetensors",
|
7 |
+
"model.embed_tokens.weight": "model-00001-of-00004.safetensors",
|
8 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
9 |
+
"model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
10 |
+
"model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
11 |
+
"model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
12 |
+
"model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
13 |
+
"model.layers.0.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
14 |
+
"model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
15 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
16 |
+
"model.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
17 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
18 |
+
"model.layers.0.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
19 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
20 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
21 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
22 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
23 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
24 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
25 |
+
"model.layers.1.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
26 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
27 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
28 |
+
"model.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
29 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
30 |
+
"model.layers.1.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
31 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
32 |
+
"model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
33 |
+
"model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
34 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
35 |
+
"model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
36 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
37 |
+
"model.layers.10.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
38 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
39 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
40 |
+
"model.layers.10.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
41 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
42 |
+
"model.layers.10.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
43 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
44 |
+
"model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
45 |
+
"model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
46 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
47 |
+
"model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
48 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
49 |
+
"model.layers.11.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
50 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
51 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
52 |
+
"model.layers.11.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
53 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
54 |
+
"model.layers.11.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
55 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
56 |
+
"model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
57 |
+
"model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
58 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
59 |
+
"model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
60 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
61 |
+
"model.layers.12.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
62 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
63 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
64 |
+
"model.layers.12.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
65 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
66 |
+
"model.layers.12.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
67 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
68 |
+
"model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
69 |
+
"model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
70 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
71 |
+
"model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
72 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
73 |
+
"model.layers.13.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
74 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
75 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
76 |
+
"model.layers.13.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
77 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
78 |
+
"model.layers.13.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
79 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
80 |
+
"model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
81 |
+
"model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
82 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
83 |
+
"model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
84 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
85 |
+
"model.layers.14.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
86 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
87 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
88 |
+
"model.layers.14.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
89 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
90 |
+
"model.layers.14.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
91 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
92 |
+
"model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
93 |
+
"model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
94 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
95 |
+
"model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
96 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
97 |
+
"model.layers.15.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
98 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
99 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
100 |
+
"model.layers.15.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
101 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
102 |
+
"model.layers.15.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
103 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
104 |
+
"model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
105 |
+
"model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
106 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
107 |
+
"model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
108 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
109 |
+
"model.layers.16.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
110 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
111 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
112 |
+
"model.layers.16.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
113 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
114 |
+
"model.layers.16.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
115 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
116 |
+
"model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
117 |
+
"model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
118 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
119 |
+
"model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
120 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
121 |
+
"model.layers.17.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
122 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
123 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
124 |
+
"model.layers.17.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
125 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
126 |
+
"model.layers.17.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
127 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
128 |
+
"model.layers.18.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
129 |
+
"model.layers.18.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
130 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
131 |
+
"model.layers.18.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
132 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
133 |
+
"model.layers.18.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
134 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
135 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
136 |
+
"model.layers.18.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
137 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
138 |
+
"model.layers.18.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
139 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
140 |
+
"model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
141 |
+
"model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
142 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
143 |
+
"model.layers.19.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
144 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
145 |
+
"model.layers.19.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
146 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
147 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
148 |
+
"model.layers.19.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
149 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
150 |
+
"model.layers.19.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
151 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
152 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
153 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
154 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
155 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
156 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
157 |
+
"model.layers.2.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
158 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
159 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
160 |
+
"model.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
161 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
162 |
+
"model.layers.2.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
163 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
164 |
+
"model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
165 |
+
"model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
166 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
167 |
+
"model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
168 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
169 |
+
"model.layers.20.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
170 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
171 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
172 |
+
"model.layers.20.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
173 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
174 |
+
"model.layers.20.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
175 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
176 |
+
"model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
177 |
+
"model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
178 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
179 |
+
"model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
180 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
181 |
+
"model.layers.21.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
182 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
183 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
184 |
+
"model.layers.21.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
185 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
186 |
+
"model.layers.21.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
187 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
188 |
+
"model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
189 |
+
"model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
190 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
191 |
+
"model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
192 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
193 |
+
"model.layers.22.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
194 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
195 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
196 |
+
"model.layers.22.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
197 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
198 |
+
"model.layers.22.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
199 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
200 |
+
"model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
201 |
+
"model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
202 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
203 |
+
"model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
204 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
205 |
+
"model.layers.23.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
206 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
207 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
208 |
+
"model.layers.23.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
209 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
210 |
+
"model.layers.23.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
211 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
212 |
+
"model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
213 |
+
"model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
214 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
215 |
+
"model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
216 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
217 |
+
"model.layers.24.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
218 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
219 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
220 |
+
"model.layers.24.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
221 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
222 |
+
"model.layers.24.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
223 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
224 |
+
"model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
225 |
+
"model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
226 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
227 |
+
"model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
228 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
229 |
+
"model.layers.25.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
230 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
231 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
232 |
+
"model.layers.25.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
233 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
234 |
+
"model.layers.25.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
235 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
236 |
+
"model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
237 |
+
"model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
238 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
239 |
+
"model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
240 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
241 |
+
"model.layers.26.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
242 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
243 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
244 |
+
"model.layers.26.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
245 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
246 |
+
"model.layers.26.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
247 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
248 |
+
"model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
249 |
+
"model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
250 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
251 |
+
"model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
252 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
253 |
+
"model.layers.27.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
254 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
255 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
256 |
+
"model.layers.27.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
257 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
258 |
+
"model.layers.27.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
259 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
260 |
+
"model.layers.28.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
261 |
+
"model.layers.28.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
262 |
+
"model.layers.28.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
263 |
+
"model.layers.28.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
264 |
+
"model.layers.28.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
265 |
+
"model.layers.28.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
266 |
+
"model.layers.28.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
267 |
+
"model.layers.28.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
268 |
+
"model.layers.28.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
269 |
+
"model.layers.28.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
270 |
+
"model.layers.28.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
271 |
+
"model.layers.28.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
272 |
+
"model.layers.29.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
273 |
+
"model.layers.29.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
274 |
+
"model.layers.29.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
275 |
+
"model.layers.29.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
276 |
+
"model.layers.29.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
277 |
+
"model.layers.29.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
278 |
+
"model.layers.29.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
279 |
+
"model.layers.29.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
280 |
+
"model.layers.29.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
281 |
+
"model.layers.29.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
282 |
+
"model.layers.29.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
283 |
+
"model.layers.29.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
284 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
285 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
286 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
287 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
288 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
289 |
+
"model.layers.3.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
290 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
291 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
292 |
+
"model.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
293 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
294 |
+
"model.layers.3.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
295 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
296 |
+
"model.layers.30.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
297 |
+
"model.layers.30.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
298 |
+
"model.layers.30.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
299 |
+
"model.layers.30.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
300 |
+
"model.layers.30.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
301 |
+
"model.layers.30.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
302 |
+
"model.layers.30.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
303 |
+
"model.layers.30.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
304 |
+
"model.layers.30.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
305 |
+
"model.layers.30.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
306 |
+
"model.layers.30.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
307 |
+
"model.layers.30.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
308 |
+
"model.layers.31.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
309 |
+
"model.layers.31.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
310 |
+
"model.layers.31.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
|
311 |
+
"model.layers.31.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
|
312 |
+
"model.layers.31.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
313 |
+
"model.layers.31.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
314 |
+
"model.layers.31.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
315 |
+
"model.layers.31.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
316 |
+
"model.layers.31.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
317 |
+
"model.layers.31.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
318 |
+
"model.layers.31.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
319 |
+
"model.layers.31.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
320 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
321 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
322 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
323 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
324 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
325 |
+
"model.layers.4.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
326 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
327 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
328 |
+
"model.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
329 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
330 |
+
"model.layers.4.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
331 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
332 |
+
"model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
333 |
+
"model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
334 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
335 |
+
"model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
336 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
337 |
+
"model.layers.5.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
338 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
339 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
340 |
+
"model.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
341 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
342 |
+
"model.layers.5.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
343 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
344 |
+
"model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
345 |
+
"model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
346 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
347 |
+
"model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
348 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
349 |
+
"model.layers.6.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
350 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
351 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
352 |
+
"model.layers.6.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
353 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
354 |
+
"model.layers.6.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
355 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
356 |
+
"model.layers.7.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
357 |
+
"model.layers.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
358 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
359 |
+
"model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
360 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
361 |
+
"model.layers.7.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
362 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
363 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
364 |
+
"model.layers.7.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
365 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
366 |
+
"model.layers.7.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
367 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
368 |
+
"model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
369 |
+
"model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
370 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
371 |
+
"model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
372 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
373 |
+
"model.layers.8.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
374 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
375 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
376 |
+
"model.layers.8.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
377 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
378 |
+
"model.layers.8.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
379 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
380 |
+
"model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
381 |
+
"model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
382 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
383 |
+
"model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
384 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
385 |
+
"model.layers.9.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
386 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
387 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
388 |
+
"model.layers.9.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
389 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
390 |
+
"model.layers.9.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
391 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
392 |
+
"model.norm.weight": "model-00004-of-00004.safetensors"
|
393 |
+
}
|
394 |
+
}
|
modeling_llama.py
ADDED
@@ -0,0 +1,1412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
""" PyTorch LLaMA model."""
|
21 |
+
import math
|
22 |
+
import warnings
|
23 |
+
from typing import List, Optional, Tuple, Union
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.nn.functional as F
|
27 |
+
import torch.utils.checkpoint
|
28 |
+
from torch import nn
|
29 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
30 |
+
|
31 |
+
from transformers.activations import ACT2FN
|
32 |
+
from transformers.cache_utils import Cache, DynamicCache
|
33 |
+
from transformers.modeling_attn_mask_utils import (
|
34 |
+
AttentionMaskConverter,
|
35 |
+
_prepare_4d_attention_mask,
|
36 |
+
_prepare_4d_causal_attention_mask,
|
37 |
+
_prepare_4d_causal_attention_mask_for_sdpa,
|
38 |
+
)
|
39 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
40 |
+
from transformers.modeling_utils import PreTrainedModel
|
41 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
|
42 |
+
from transformers.utils import (
|
43 |
+
add_start_docstrings,
|
44 |
+
add_start_docstrings_to_model_forward,
|
45 |
+
is_flash_attn_2_available,
|
46 |
+
is_flash_attn_greater_or_equal_2_10,
|
47 |
+
logging,
|
48 |
+
replace_return_docstrings,
|
49 |
+
)
|
50 |
+
from transformers.utils.import_utils import is_torch_fx_available
|
51 |
+
from .configuration_llama import LlamaConfig
|
52 |
+
|
53 |
+
|
54 |
+
if is_flash_attn_2_available():
|
55 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
56 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
57 |
+
|
58 |
+
|
59 |
+
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
|
60 |
+
# It means that the function will not be traced through and simply appear as a node in the graph.
|
61 |
+
if is_torch_fx_available():
|
62 |
+
if not is_torch_greater_or_equal_than_1_13:
|
63 |
+
import torch.fx
|
64 |
+
|
65 |
+
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
|
66 |
+
|
67 |
+
|
68 |
+
logger = logging.get_logger(__name__)
|
69 |
+
|
70 |
+
_CONFIG_FOR_DOC = "LlamaConfig"
|
71 |
+
|
72 |
+
|
73 |
+
def _get_unpad_data(attention_mask):
|
74 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
75 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
76 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
77 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
78 |
+
return (
|
79 |
+
indices,
|
80 |
+
cu_seqlens,
|
81 |
+
max_seqlen_in_batch,
|
82 |
+
)
|
83 |
+
|
84 |
+
|
85 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
86 |
+
warnings.warn(
|
87 |
+
"Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
|
88 |
+
)
|
89 |
+
return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
90 |
+
|
91 |
+
|
92 |
+
def _make_causal_mask(
|
93 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
94 |
+
):
|
95 |
+
warnings.warn(
|
96 |
+
"Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
|
97 |
+
)
|
98 |
+
return AttentionMaskConverter._make_causal_mask(
|
99 |
+
input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
|
100 |
+
)
|
101 |
+
|
102 |
+
|
103 |
+
class LlamaRMSNorm(nn.Module):
|
104 |
+
def __init__(self, hidden_size, eps=1e-6):
|
105 |
+
"""
|
106 |
+
LlamaRMSNorm is equivalent to T5LayerNorm
|
107 |
+
"""
|
108 |
+
super().__init__()
|
109 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
110 |
+
self.variance_epsilon = eps
|
111 |
+
|
112 |
+
def forward(self, hidden_states):
|
113 |
+
input_dtype = hidden_states.dtype
|
114 |
+
hidden_states = hidden_states.to(torch.float32)
|
115 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
116 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
117 |
+
return self.weight * hidden_states.to(input_dtype)
|
118 |
+
|
119 |
+
|
120 |
+
ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
|
121 |
+
|
122 |
+
|
123 |
+
class LlamaRotaryEmbedding(nn.Module):
|
124 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
125 |
+
super().__init__()
|
126 |
+
|
127 |
+
self.dim = dim
|
128 |
+
self.max_position_embeddings = max_position_embeddings
|
129 |
+
self.base = base
|
130 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
131 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
132 |
+
|
133 |
+
# Build here to make `torch.jit.trace` work.
|
134 |
+
self._set_cos_sin_cache(
|
135 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
136 |
+
)
|
137 |
+
|
138 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
139 |
+
self.max_seq_len_cached = seq_len
|
140 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
141 |
+
|
142 |
+
freqs = torch.outer(t, self.inv_freq)
|
143 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
144 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
145 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
146 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
147 |
+
|
148 |
+
def forward(self, x, seq_len=None):
|
149 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
150 |
+
if seq_len > self.max_seq_len_cached:
|
151 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
152 |
+
|
153 |
+
return (
|
154 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
155 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
156 |
+
)
|
157 |
+
|
158 |
+
|
159 |
+
class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
|
160 |
+
"""LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
161 |
+
|
162 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
163 |
+
self.scaling_factor = scaling_factor
|
164 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
165 |
+
|
166 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
167 |
+
self.max_seq_len_cached = seq_len
|
168 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
169 |
+
t = t / self.scaling_factor
|
170 |
+
|
171 |
+
freqs = torch.outer(t, self.inv_freq)
|
172 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
173 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
174 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
175 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
176 |
+
|
177 |
+
|
178 |
+
class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
|
179 |
+
"""LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
180 |
+
|
181 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
182 |
+
self.scaling_factor = scaling_factor
|
183 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
184 |
+
|
185 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
186 |
+
self.max_seq_len_cached = seq_len
|
187 |
+
|
188 |
+
if seq_len > self.max_position_embeddings:
|
189 |
+
base = self.base * (
|
190 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
191 |
+
) ** (self.dim / (self.dim - 2))
|
192 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
193 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
194 |
+
|
195 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
196 |
+
|
197 |
+
freqs = torch.outer(t, self.inv_freq)
|
198 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
199 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
200 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
201 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
202 |
+
|
203 |
+
|
204 |
+
def rotate_half(x):
|
205 |
+
"""Rotates half the hidden dims of the input."""
|
206 |
+
x1 = x[..., : x.shape[-1] // 2]
|
207 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
208 |
+
return torch.cat((-x2, x1), dim=-1)
|
209 |
+
|
210 |
+
|
211 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
212 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
213 |
+
|
214 |
+
Args:
|
215 |
+
q (`torch.Tensor`): The query tensor.
|
216 |
+
k (`torch.Tensor`): The key tensor.
|
217 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
218 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
219 |
+
position_ids (`torch.Tensor`):
|
220 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
221 |
+
used to pass offsetted position ids when working with a KV-cache.
|
222 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
223 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
224 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
225 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
226 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
227 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
228 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
229 |
+
Returns:
|
230 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
231 |
+
"""
|
232 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
233 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
234 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
235 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
236 |
+
return q_embed, k_embed
|
237 |
+
|
238 |
+
|
239 |
+
class LlamaMLP(nn.Module):
|
240 |
+
def __init__(self, config):
|
241 |
+
super().__init__()
|
242 |
+
self.config = config
|
243 |
+
self.hidden_size = config.hidden_size
|
244 |
+
self.intermediate_size = config.intermediate_size
|
245 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
246 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
247 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
248 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
249 |
+
|
250 |
+
def forward(self, x):
|
251 |
+
if self.config.pretraining_tp > 1:
|
252 |
+
slice = self.intermediate_size // self.config.pretraining_tp
|
253 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
254 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
255 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
256 |
+
|
257 |
+
gate_proj = torch.cat(
|
258 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
259 |
+
)
|
260 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
261 |
+
|
262 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
263 |
+
down_proj = [
|
264 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
265 |
+
]
|
266 |
+
down_proj = sum(down_proj)
|
267 |
+
else:
|
268 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
269 |
+
|
270 |
+
return down_proj
|
271 |
+
|
272 |
+
|
273 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
274 |
+
"""
|
275 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
276 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
277 |
+
"""
|
278 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
279 |
+
if n_rep == 1:
|
280 |
+
return hidden_states
|
281 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
282 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
283 |
+
|
284 |
+
|
285 |
+
class LlamaAttention(nn.Module):
|
286 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
287 |
+
|
288 |
+
def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
|
289 |
+
super().__init__()
|
290 |
+
self.config = config
|
291 |
+
self.layer_idx = layer_idx
|
292 |
+
if layer_idx is None:
|
293 |
+
logger.warning_once(
|
294 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
295 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
296 |
+
"when creating this class."
|
297 |
+
)
|
298 |
+
|
299 |
+
self.attention_dropout = config.attention_dropout
|
300 |
+
self.hidden_size = config.hidden_size
|
301 |
+
self.num_heads = config.num_attention_heads
|
302 |
+
self.head_dim = self.hidden_size // self.num_heads
|
303 |
+
self.num_key_value_heads = config.num_key_value_heads
|
304 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
305 |
+
self.max_position_embeddings = config.max_position_embeddings
|
306 |
+
self.rope_theta = config.rope_theta
|
307 |
+
self.is_causal = True
|
308 |
+
|
309 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
310 |
+
raise ValueError(
|
311 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
312 |
+
f" and `num_heads`: {self.num_heads})."
|
313 |
+
)
|
314 |
+
|
315 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
316 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
317 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
318 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
319 |
+
self._init_rope()
|
320 |
+
|
321 |
+
def _init_rope(self):
|
322 |
+
if self.config.rope_scaling is None:
|
323 |
+
self.rotary_emb = LlamaRotaryEmbedding(
|
324 |
+
self.head_dim,
|
325 |
+
max_position_embeddings=self.max_position_embeddings,
|
326 |
+
base=self.rope_theta,
|
327 |
+
)
|
328 |
+
else:
|
329 |
+
scaling_type = self.config.rope_scaling["type"]
|
330 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
331 |
+
if scaling_type == "linear":
|
332 |
+
self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
|
333 |
+
self.head_dim,
|
334 |
+
max_position_embeddings=self.max_position_embeddings,
|
335 |
+
scaling_factor=scaling_factor,
|
336 |
+
base=self.rope_theta,
|
337 |
+
)
|
338 |
+
elif scaling_type == "dynamic":
|
339 |
+
self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
|
340 |
+
self.head_dim,
|
341 |
+
max_position_embeddings=self.max_position_embeddings,
|
342 |
+
scaling_factor=scaling_factor,
|
343 |
+
base=self.rope_theta,
|
344 |
+
)
|
345 |
+
else:
|
346 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
347 |
+
|
348 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
349 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
350 |
+
|
351 |
+
def forward(
|
352 |
+
self,
|
353 |
+
hidden_states: torch.Tensor,
|
354 |
+
attention_mask: Optional[torch.Tensor] = None,
|
355 |
+
position_ids: Optional[torch.LongTensor] = None,
|
356 |
+
past_key_value: Optional[Cache] = None,
|
357 |
+
output_attentions: bool = False,
|
358 |
+
use_cache: bool = False,
|
359 |
+
**kwargs,
|
360 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
361 |
+
if "padding_mask" in kwargs:
|
362 |
+
warnings.warn(
|
363 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
364 |
+
)
|
365 |
+
|
366 |
+
bsz, q_len, _ = hidden_states.size()
|
367 |
+
|
368 |
+
if self.config.pretraining_tp > 1:
|
369 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
370 |
+
query_slices = self.q_proj.weight.split(
|
371 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
372 |
+
)
|
373 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
374 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
375 |
+
|
376 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
377 |
+
query_states = torch.cat(query_states, dim=-1)
|
378 |
+
|
379 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
380 |
+
key_states = torch.cat(key_states, dim=-1)
|
381 |
+
|
382 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
383 |
+
value_states = torch.cat(value_states, dim=-1)
|
384 |
+
|
385 |
+
else:
|
386 |
+
query_states = self.q_proj(hidden_states)
|
387 |
+
key_states = self.k_proj(hidden_states)
|
388 |
+
value_states = self.v_proj(hidden_states)
|
389 |
+
|
390 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
391 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
392 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
393 |
+
|
394 |
+
kv_seq_len = key_states.shape[-2]
|
395 |
+
if past_key_value is not None:
|
396 |
+
if self.layer_idx is None:
|
397 |
+
raise ValueError(
|
398 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
399 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
400 |
+
"with a layer index."
|
401 |
+
)
|
402 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
403 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
404 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
405 |
+
|
406 |
+
if past_key_value is not None:
|
407 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
408 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
409 |
+
|
410 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
411 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
412 |
+
|
413 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
414 |
+
|
415 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
416 |
+
raise ValueError(
|
417 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
418 |
+
f" {attn_weights.size()}"
|
419 |
+
)
|
420 |
+
|
421 |
+
if attention_mask is not None:
|
422 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
423 |
+
raise ValueError(
|
424 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
425 |
+
)
|
426 |
+
attn_weights = attn_weights + attention_mask
|
427 |
+
|
428 |
+
# upcast attention to fp32
|
429 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
430 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
431 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
432 |
+
|
433 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
434 |
+
raise ValueError(
|
435 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
436 |
+
f" {attn_output.size()}"
|
437 |
+
)
|
438 |
+
|
439 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
440 |
+
|
441 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
442 |
+
|
443 |
+
if self.config.pretraining_tp > 1:
|
444 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
445 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
446 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
447 |
+
else:
|
448 |
+
attn_output = self.o_proj(attn_output)
|
449 |
+
|
450 |
+
if not output_attentions:
|
451 |
+
attn_weights = None
|
452 |
+
|
453 |
+
return attn_output, attn_weights, past_key_value
|
454 |
+
|
455 |
+
|
456 |
+
class LlamaFlashAttention2(LlamaAttention):
|
457 |
+
"""
|
458 |
+
Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
|
459 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
460 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
461 |
+
"""
|
462 |
+
|
463 |
+
def __init__(self, *args, **kwargs):
|
464 |
+
super().__init__(*args, **kwargs)
|
465 |
+
|
466 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
467 |
+
# 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.
|
468 |
+
# 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).
|
469 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
470 |
+
|
471 |
+
def forward(
|
472 |
+
self,
|
473 |
+
hidden_states: torch.Tensor,
|
474 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
475 |
+
position_ids: Optional[torch.LongTensor] = None,
|
476 |
+
past_key_value: Optional[Cache] = None,
|
477 |
+
output_attentions: bool = False,
|
478 |
+
use_cache: bool = False,
|
479 |
+
**kwargs,
|
480 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
481 |
+
# LlamaFlashAttention2 attention does not support output_attentions
|
482 |
+
if "padding_mask" in kwargs:
|
483 |
+
warnings.warn(
|
484 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
485 |
+
)
|
486 |
+
|
487 |
+
# overwrite attention_mask with padding_mask
|
488 |
+
attention_mask = kwargs.pop("padding_mask")
|
489 |
+
|
490 |
+
output_attentions = False
|
491 |
+
|
492 |
+
bsz, q_len, _ = hidden_states.size()
|
493 |
+
|
494 |
+
query_states = self.q_proj(hidden_states)
|
495 |
+
key_states = self.k_proj(hidden_states)
|
496 |
+
value_states = self.v_proj(hidden_states)
|
497 |
+
|
498 |
+
# Flash attention requires the input to have the shape
|
499 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
500 |
+
# therefore we just need to keep the original shape
|
501 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
502 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
503 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
504 |
+
|
505 |
+
kv_seq_len = key_states.shape[-2]
|
506 |
+
if past_key_value is not None:
|
507 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
508 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
509 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
510 |
+
|
511 |
+
if past_key_value is not None:
|
512 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
513 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
514 |
+
|
515 |
+
# 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
|
516 |
+
# to be able to avoid many of these transpose/reshape/view.
|
517 |
+
query_states = query_states.transpose(1, 2)
|
518 |
+
key_states = key_states.transpose(1, 2)
|
519 |
+
value_states = value_states.transpose(1, 2)
|
520 |
+
|
521 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
522 |
+
|
523 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
524 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
525 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
526 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
527 |
+
# in fp32. (LlamaRMSNorm handles it correctly)
|
528 |
+
|
529 |
+
input_dtype = query_states.dtype
|
530 |
+
if input_dtype == torch.float32:
|
531 |
+
# Handle the case where the model is quantized
|
532 |
+
if hasattr(self.config, "_pre_quantization_dtype"):
|
533 |
+
target_dtype = self.config._pre_quantization_dtype
|
534 |
+
else:
|
535 |
+
target_dtype = self.q_proj.weight.dtype
|
536 |
+
|
537 |
+
logger.warning_once(
|
538 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
539 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
540 |
+
f" {target_dtype}."
|
541 |
+
)
|
542 |
+
|
543 |
+
query_states = query_states.to(target_dtype)
|
544 |
+
key_states = key_states.to(target_dtype)
|
545 |
+
value_states = value_states.to(target_dtype)
|
546 |
+
|
547 |
+
attn_output = self._flash_attention_forward(
|
548 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
549 |
+
)
|
550 |
+
|
551 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
552 |
+
attn_output = self.o_proj(attn_output)
|
553 |
+
|
554 |
+
if not output_attentions:
|
555 |
+
attn_weights = None
|
556 |
+
|
557 |
+
return attn_output, attn_weights, past_key_value
|
558 |
+
|
559 |
+
def _flash_attention_forward(
|
560 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
561 |
+
):
|
562 |
+
"""
|
563 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
564 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
565 |
+
|
566 |
+
Args:
|
567 |
+
query_states (`torch.Tensor`):
|
568 |
+
Input query states to be passed to Flash Attention API
|
569 |
+
key_states (`torch.Tensor`):
|
570 |
+
Input key states to be passed to Flash Attention API
|
571 |
+
value_states (`torch.Tensor`):
|
572 |
+
Input value states to be passed to Flash Attention API
|
573 |
+
attention_mask (`torch.Tensor`):
|
574 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
575 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
576 |
+
dropout (`int`, *optional*):
|
577 |
+
Attention dropout
|
578 |
+
softmax_scale (`float`, *optional*):
|
579 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
580 |
+
"""
|
581 |
+
if not self._flash_attn_uses_top_left_mask:
|
582 |
+
causal = self.is_causal
|
583 |
+
else:
|
584 |
+
# 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__.
|
585 |
+
causal = self.is_causal and query_length != 1
|
586 |
+
|
587 |
+
# Contains at least one padding token in the sequence
|
588 |
+
if attention_mask is not None:
|
589 |
+
batch_size = query_states.shape[0]
|
590 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
591 |
+
query_states, key_states, value_states, attention_mask, query_length
|
592 |
+
)
|
593 |
+
|
594 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
595 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
596 |
+
|
597 |
+
attn_output_unpad = flash_attn_varlen_func(
|
598 |
+
query_states,
|
599 |
+
key_states,
|
600 |
+
value_states,
|
601 |
+
cu_seqlens_q=cu_seqlens_q,
|
602 |
+
cu_seqlens_k=cu_seqlens_k,
|
603 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
604 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
605 |
+
dropout_p=dropout,
|
606 |
+
softmax_scale=softmax_scale,
|
607 |
+
causal=causal,
|
608 |
+
)
|
609 |
+
|
610 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
611 |
+
else:
|
612 |
+
attn_output = flash_attn_func(
|
613 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
614 |
+
)
|
615 |
+
|
616 |
+
return attn_output
|
617 |
+
|
618 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
619 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
620 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
621 |
+
|
622 |
+
key_layer = index_first_axis(
|
623 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
624 |
+
)
|
625 |
+
value_layer = index_first_axis(
|
626 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
627 |
+
)
|
628 |
+
if query_length == kv_seq_len:
|
629 |
+
query_layer = index_first_axis(
|
630 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
631 |
+
)
|
632 |
+
cu_seqlens_q = cu_seqlens_k
|
633 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
634 |
+
indices_q = indices_k
|
635 |
+
elif query_length == 1:
|
636 |
+
max_seqlen_in_batch_q = 1
|
637 |
+
cu_seqlens_q = torch.arange(
|
638 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
639 |
+
) # There is a memcpy here, that is very bad.
|
640 |
+
indices_q = cu_seqlens_q[:-1]
|
641 |
+
query_layer = query_layer.squeeze(1)
|
642 |
+
else:
|
643 |
+
# The -q_len: slice assumes left padding.
|
644 |
+
attention_mask = attention_mask[:, -query_length:]
|
645 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
646 |
+
|
647 |
+
return (
|
648 |
+
query_layer,
|
649 |
+
key_layer,
|
650 |
+
value_layer,
|
651 |
+
indices_q,
|
652 |
+
(cu_seqlens_q, cu_seqlens_k),
|
653 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
654 |
+
)
|
655 |
+
|
656 |
+
|
657 |
+
class LlamaSdpaAttention(LlamaAttention):
|
658 |
+
"""
|
659 |
+
Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
660 |
+
`LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
661 |
+
SDPA API.
|
662 |
+
"""
|
663 |
+
|
664 |
+
# Adapted from LlamaAttention.forward
|
665 |
+
def forward(
|
666 |
+
self,
|
667 |
+
hidden_states: torch.Tensor,
|
668 |
+
attention_mask: Optional[torch.Tensor] = None,
|
669 |
+
position_ids: Optional[torch.LongTensor] = None,
|
670 |
+
past_key_value: Optional[Cache] = None,
|
671 |
+
output_attentions: bool = False,
|
672 |
+
use_cache: bool = False,
|
673 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
674 |
+
if output_attentions:
|
675 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
676 |
+
logger.warning_once(
|
677 |
+
"LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
678 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
679 |
+
)
|
680 |
+
return super().forward(
|
681 |
+
hidden_states=hidden_states,
|
682 |
+
attention_mask=attention_mask,
|
683 |
+
position_ids=position_ids,
|
684 |
+
past_key_value=past_key_value,
|
685 |
+
output_attentions=output_attentions,
|
686 |
+
use_cache=use_cache,
|
687 |
+
)
|
688 |
+
|
689 |
+
bsz, q_len, _ = hidden_states.size()
|
690 |
+
|
691 |
+
query_states = self.q_proj(hidden_states)
|
692 |
+
key_states = self.k_proj(hidden_states)
|
693 |
+
value_states = self.v_proj(hidden_states)
|
694 |
+
|
695 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
696 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
697 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
698 |
+
|
699 |
+
kv_seq_len = key_states.shape[-2]
|
700 |
+
if past_key_value is not None:
|
701 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
702 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
703 |
+
|
704 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
705 |
+
|
706 |
+
if past_key_value is not None:
|
707 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
708 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
709 |
+
|
710 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
711 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
712 |
+
|
713 |
+
if attention_mask is not None:
|
714 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
715 |
+
raise ValueError(
|
716 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
717 |
+
)
|
718 |
+
|
719 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
720 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
721 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
722 |
+
query_states = query_states.contiguous()
|
723 |
+
key_states = key_states.contiguous()
|
724 |
+
value_states = value_states.contiguous()
|
725 |
+
|
726 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
727 |
+
query_states,
|
728 |
+
key_states,
|
729 |
+
value_states,
|
730 |
+
attn_mask=attention_mask,
|
731 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
732 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
733 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
734 |
+
)
|
735 |
+
|
736 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
737 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
738 |
+
|
739 |
+
attn_output = self.o_proj(attn_output)
|
740 |
+
|
741 |
+
return attn_output, None, past_key_value
|
742 |
+
|
743 |
+
|
744 |
+
LLAMA_ATTENTION_CLASSES = {
|
745 |
+
"eager": LlamaAttention,
|
746 |
+
"flash_attention_2": LlamaFlashAttention2,
|
747 |
+
"sdpa": LlamaSdpaAttention,
|
748 |
+
}
|
749 |
+
|
750 |
+
|
751 |
+
class LlamaDecoderLayer(nn.Module):
|
752 |
+
def __init__(self, config: LlamaConfig, layer_idx: int):
|
753 |
+
super().__init__()
|
754 |
+
self.hidden_size = config.hidden_size
|
755 |
+
|
756 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
757 |
+
|
758 |
+
self.mlp = LlamaMLP(config)
|
759 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
760 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
761 |
+
|
762 |
+
def forward(
|
763 |
+
self,
|
764 |
+
hidden_states: torch.Tensor,
|
765 |
+
attention_mask: Optional[torch.Tensor] = None,
|
766 |
+
position_ids: Optional[torch.LongTensor] = None,
|
767 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
768 |
+
output_attentions: Optional[bool] = False,
|
769 |
+
use_cache: Optional[bool] = False,
|
770 |
+
**kwargs,
|
771 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
772 |
+
"""
|
773 |
+
Args:
|
774 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
775 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
776 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
777 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
778 |
+
output_attentions (`bool`, *optional*):
|
779 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
780 |
+
returned tensors for more detail.
|
781 |
+
use_cache (`bool`, *optional*):
|
782 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
783 |
+
(see `past_key_values`).
|
784 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
785 |
+
"""
|
786 |
+
if "padding_mask" in kwargs:
|
787 |
+
warnings.warn(
|
788 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
789 |
+
)
|
790 |
+
|
791 |
+
residual = hidden_states
|
792 |
+
|
793 |
+
hidden_states = self.input_layernorm(hidden_states)
|
794 |
+
|
795 |
+
# Self Attention
|
796 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
797 |
+
hidden_states=hidden_states,
|
798 |
+
attention_mask=attention_mask,
|
799 |
+
position_ids=position_ids,
|
800 |
+
past_key_value=past_key_value,
|
801 |
+
output_attentions=output_attentions,
|
802 |
+
use_cache=use_cache,
|
803 |
+
**kwargs,
|
804 |
+
)
|
805 |
+
hidden_states = residual + hidden_states
|
806 |
+
|
807 |
+
# Fully Connected
|
808 |
+
residual = hidden_states
|
809 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
810 |
+
hidden_states = self.mlp(hidden_states)
|
811 |
+
hidden_states = residual + hidden_states
|
812 |
+
|
813 |
+
outputs = (hidden_states,)
|
814 |
+
|
815 |
+
if output_attentions:
|
816 |
+
outputs += (self_attn_weights,)
|
817 |
+
|
818 |
+
if use_cache:
|
819 |
+
outputs += (present_key_value,)
|
820 |
+
|
821 |
+
return outputs
|
822 |
+
|
823 |
+
|
824 |
+
LLAMA_START_DOCSTRING = r"""
|
825 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
826 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
827 |
+
etc.)
|
828 |
+
|
829 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
830 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
831 |
+
and behavior.
|
832 |
+
|
833 |
+
Parameters:
|
834 |
+
config ([`LlamaConfig`]):
|
835 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
836 |
+
load the weights associated with the model, only the configuration. Check out the
|
837 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
838 |
+
"""
|
839 |
+
|
840 |
+
|
841 |
+
@add_start_docstrings(
|
842 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
843 |
+
LLAMA_START_DOCSTRING,
|
844 |
+
)
|
845 |
+
class LlamaPreTrainedModel(PreTrainedModel):
|
846 |
+
config_class = LlamaConfig
|
847 |
+
base_model_prefix = "model"
|
848 |
+
supports_gradient_checkpointing = True
|
849 |
+
_no_split_modules = ["LlamaDecoderLayer"]
|
850 |
+
_skip_keys_device_placement = "past_key_values"
|
851 |
+
_supports_flash_attn_2 = True
|
852 |
+
_supports_sdpa = True
|
853 |
+
_supports_cache_class = True
|
854 |
+
|
855 |
+
def _init_weights(self, module):
|
856 |
+
std = self.config.initializer_range
|
857 |
+
if isinstance(module, nn.Linear):
|
858 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
859 |
+
if module.bias is not None:
|
860 |
+
module.bias.data.zero_()
|
861 |
+
elif isinstance(module, nn.Embedding):
|
862 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
863 |
+
if module.padding_idx is not None:
|
864 |
+
module.weight.data[module.padding_idx].zero_()
|
865 |
+
|
866 |
+
|
867 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
868 |
+
Args:
|
869 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
870 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
871 |
+
it.
|
872 |
+
|
873 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
874 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
875 |
+
|
876 |
+
[What are input IDs?](../glossary#input-ids)
|
877 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
878 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
879 |
+
|
880 |
+
- 1 for tokens that are **not masked**,
|
881 |
+
- 0 for tokens that are **masked**.
|
882 |
+
|
883 |
+
[What are attention masks?](../glossary#attention-mask)
|
884 |
+
|
885 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
886 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
887 |
+
|
888 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
889 |
+
`past_key_values`).
|
890 |
+
|
891 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
892 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
893 |
+
information on the default strategy.
|
894 |
+
|
895 |
+
- 1 indicates the head is **not masked**,
|
896 |
+
- 0 indicates the head is **masked**.
|
897 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
898 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
899 |
+
config.n_positions - 1]`.
|
900 |
+
|
901 |
+
[What are position IDs?](../glossary#position-ids)
|
902 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
903 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
904 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
905 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
906 |
+
|
907 |
+
Two formats are allowed:
|
908 |
+
- a [`~cache_utils.Cache`] instance;
|
909 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
910 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
911 |
+
cache format.
|
912 |
+
|
913 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
914 |
+
legacy cache format will be returned.
|
915 |
+
|
916 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
917 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
918 |
+
of shape `(batch_size, sequence_length)`.
|
919 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
920 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
921 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
922 |
+
model's internal embedding lookup matrix.
|
923 |
+
use_cache (`bool`, *optional*):
|
924 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
925 |
+
`past_key_values`).
|
926 |
+
output_attentions (`bool`, *optional*):
|
927 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
928 |
+
tensors for more detail.
|
929 |
+
output_hidden_states (`bool`, *optional*):
|
930 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
931 |
+
more detail.
|
932 |
+
return_dict (`bool`, *optional*):
|
933 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
934 |
+
"""
|
935 |
+
|
936 |
+
|
937 |
+
@add_start_docstrings(
|
938 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
939 |
+
LLAMA_START_DOCSTRING,
|
940 |
+
)
|
941 |
+
class LlamaModel(LlamaPreTrainedModel):
|
942 |
+
"""
|
943 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
|
944 |
+
|
945 |
+
Args:
|
946 |
+
config: LlamaConfig
|
947 |
+
"""
|
948 |
+
|
949 |
+
def __init__(self, config: LlamaConfig):
|
950 |
+
super().__init__(config)
|
951 |
+
self.padding_idx = config.pad_token_id
|
952 |
+
self.vocab_size = config.vocab_size
|
953 |
+
|
954 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
955 |
+
self.layers = nn.ModuleList(
|
956 |
+
[LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
957 |
+
)
|
958 |
+
self._use_sdpa = config._attn_implementation == "sdpa"
|
959 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
960 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
961 |
+
|
962 |
+
self.gradient_checkpointing = False
|
963 |
+
# Initialize weights and apply final processing
|
964 |
+
self.post_init()
|
965 |
+
|
966 |
+
def get_input_embeddings(self):
|
967 |
+
return self.embed_tokens
|
968 |
+
|
969 |
+
def set_input_embeddings(self, value):
|
970 |
+
self.embed_tokens = value
|
971 |
+
|
972 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
973 |
+
def forward(
|
974 |
+
self,
|
975 |
+
input_ids: torch.LongTensor = None,
|
976 |
+
attention_mask: Optional[torch.Tensor] = None,
|
977 |
+
position_ids: Optional[torch.LongTensor] = None,
|
978 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
979 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
980 |
+
use_cache: Optional[bool] = None,
|
981 |
+
output_attentions: Optional[bool] = None,
|
982 |
+
output_hidden_states: Optional[bool] = None,
|
983 |
+
return_dict: Optional[bool] = None,
|
984 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
985 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
986 |
+
output_hidden_states = (
|
987 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
988 |
+
)
|
989 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
990 |
+
|
991 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
992 |
+
|
993 |
+
# retrieve input_ids and inputs_embeds
|
994 |
+
if input_ids is not None and inputs_embeds is not None:
|
995 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
996 |
+
elif input_ids is not None:
|
997 |
+
batch_size, seq_length = input_ids.shape[:2]
|
998 |
+
elif inputs_embeds is not None:
|
999 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
1000 |
+
else:
|
1001 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1002 |
+
|
1003 |
+
if self.gradient_checkpointing and self.training:
|
1004 |
+
if use_cache:
|
1005 |
+
logger.warning_once(
|
1006 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
1007 |
+
)
|
1008 |
+
use_cache = False
|
1009 |
+
|
1010 |
+
past_key_values_length = 0
|
1011 |
+
if use_cache:
|
1012 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
1013 |
+
if use_legacy_cache:
|
1014 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
1015 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
1016 |
+
|
1017 |
+
if position_ids is None:
|
1018 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1019 |
+
position_ids = torch.arange(
|
1020 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
1021 |
+
)
|
1022 |
+
position_ids = position_ids.unsqueeze(0)
|
1023 |
+
|
1024 |
+
if inputs_embeds is None:
|
1025 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
1026 |
+
|
1027 |
+
if self._use_flash_attention_2:
|
1028 |
+
# 2d mask is passed through the layers
|
1029 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
1030 |
+
elif self._use_sdpa and not output_attentions:
|
1031 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
1032 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
1033 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
1034 |
+
attention_mask,
|
1035 |
+
(batch_size, seq_length),
|
1036 |
+
inputs_embeds,
|
1037 |
+
past_key_values_length,
|
1038 |
+
)
|
1039 |
+
else:
|
1040 |
+
# 4d mask is passed through the layers
|
1041 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1042 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
1043 |
+
)
|
1044 |
+
|
1045 |
+
# embed positions
|
1046 |
+
hidden_states = inputs_embeds
|
1047 |
+
|
1048 |
+
# decoder layers
|
1049 |
+
all_hidden_states = () if output_hidden_states else None
|
1050 |
+
all_self_attns = () if output_attentions else None
|
1051 |
+
next_decoder_cache = None
|
1052 |
+
|
1053 |
+
for decoder_layer in self.layers:
|
1054 |
+
if output_hidden_states:
|
1055 |
+
all_hidden_states += (hidden_states,)
|
1056 |
+
|
1057 |
+
if self.gradient_checkpointing and self.training:
|
1058 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1059 |
+
decoder_layer.__call__,
|
1060 |
+
hidden_states,
|
1061 |
+
attention_mask,
|
1062 |
+
position_ids,
|
1063 |
+
past_key_values,
|
1064 |
+
output_attentions,
|
1065 |
+
use_cache,
|
1066 |
+
)
|
1067 |
+
else:
|
1068 |
+
layer_outputs = decoder_layer(
|
1069 |
+
hidden_states,
|
1070 |
+
attention_mask=attention_mask,
|
1071 |
+
position_ids=position_ids,
|
1072 |
+
past_key_value=past_key_values,
|
1073 |
+
output_attentions=output_attentions,
|
1074 |
+
use_cache=use_cache,
|
1075 |
+
)
|
1076 |
+
|
1077 |
+
hidden_states = layer_outputs[0]
|
1078 |
+
|
1079 |
+
if use_cache:
|
1080 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1081 |
+
|
1082 |
+
if output_attentions:
|
1083 |
+
all_self_attns += (layer_outputs[1],)
|
1084 |
+
|
1085 |
+
hidden_states = self.norm(hidden_states)
|
1086 |
+
|
1087 |
+
# add hidden states from the last decoder layer
|
1088 |
+
if output_hidden_states:
|
1089 |
+
all_hidden_states += (hidden_states,)
|
1090 |
+
|
1091 |
+
next_cache = None
|
1092 |
+
if use_cache:
|
1093 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
1094 |
+
if not return_dict:
|
1095 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
1096 |
+
return BaseModelOutputWithPast(
|
1097 |
+
last_hidden_state=hidden_states,
|
1098 |
+
past_key_values=next_cache,
|
1099 |
+
hidden_states=all_hidden_states,
|
1100 |
+
attentions=all_self_attns,
|
1101 |
+
)
|
1102 |
+
|
1103 |
+
|
1104 |
+
class LlamaForCausalLM(LlamaPreTrainedModel):
|
1105 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1106 |
+
|
1107 |
+
def __init__(self, config):
|
1108 |
+
super().__init__(config)
|
1109 |
+
self.model = LlamaModel(config)
|
1110 |
+
self.vocab_size = config.vocab_size
|
1111 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1112 |
+
|
1113 |
+
# Initialize weights and apply final processing
|
1114 |
+
self.post_init()
|
1115 |
+
|
1116 |
+
def get_input_embeddings(self):
|
1117 |
+
return self.model.embed_tokens
|
1118 |
+
|
1119 |
+
def set_input_embeddings(self, value):
|
1120 |
+
self.model.embed_tokens = value
|
1121 |
+
|
1122 |
+
def get_output_embeddings(self):
|
1123 |
+
return self.lm_head
|
1124 |
+
|
1125 |
+
def set_output_embeddings(self, new_embeddings):
|
1126 |
+
self.lm_head = new_embeddings
|
1127 |
+
|
1128 |
+
def set_decoder(self, decoder):
|
1129 |
+
self.model = decoder
|
1130 |
+
|
1131 |
+
def get_decoder(self):
|
1132 |
+
return self.model
|
1133 |
+
|
1134 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1135 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1136 |
+
def forward(
|
1137 |
+
self,
|
1138 |
+
input_ids: torch.LongTensor = None,
|
1139 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1140 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1141 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1142 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1143 |
+
labels: Optional[torch.LongTensor] = None,
|
1144 |
+
use_cache: Optional[bool] = None,
|
1145 |
+
output_attentions: Optional[bool] = None,
|
1146 |
+
output_hidden_states: Optional[bool] = None,
|
1147 |
+
return_dict: Optional[bool] = None,
|
1148 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1149 |
+
r"""
|
1150 |
+
Args:
|
1151 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1152 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1153 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1154 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1155 |
+
|
1156 |
+
Returns:
|
1157 |
+
|
1158 |
+
Example:
|
1159 |
+
|
1160 |
+
```python
|
1161 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
1162 |
+
|
1163 |
+
>>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
1164 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
1165 |
+
|
1166 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1167 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1168 |
+
|
1169 |
+
>>> # Generate
|
1170 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1171 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1172 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1173 |
+
```"""
|
1174 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1175 |
+
output_hidden_states = (
|
1176 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1177 |
+
)
|
1178 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1179 |
+
|
1180 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1181 |
+
outputs = self.model(
|
1182 |
+
input_ids=input_ids,
|
1183 |
+
attention_mask=attention_mask,
|
1184 |
+
position_ids=position_ids,
|
1185 |
+
past_key_values=past_key_values,
|
1186 |
+
inputs_embeds=inputs_embeds,
|
1187 |
+
use_cache=use_cache,
|
1188 |
+
output_attentions=output_attentions,
|
1189 |
+
output_hidden_states=output_hidden_states,
|
1190 |
+
return_dict=return_dict,
|
1191 |
+
)
|
1192 |
+
|
1193 |
+
hidden_states = outputs[0]
|
1194 |
+
if self.config.pretraining_tp > 1:
|
1195 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
1196 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
1197 |
+
logits = torch.cat(logits, dim=-1)
|
1198 |
+
else:
|
1199 |
+
logits = self.lm_head(hidden_states)
|
1200 |
+
logits = logits.float()
|
1201 |
+
|
1202 |
+
loss = None
|
1203 |
+
if labels is not None:
|
1204 |
+
# Shift so that tokens < n predict n
|
1205 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1206 |
+
shift_labels = labels[..., 1:].contiguous()
|
1207 |
+
# Flatten the tokens
|
1208 |
+
loss_fct = CrossEntropyLoss()
|
1209 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1210 |
+
shift_labels = shift_labels.view(-1)
|
1211 |
+
# Enable model parallelism
|
1212 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1213 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1214 |
+
|
1215 |
+
if not return_dict:
|
1216 |
+
output = (logits,) + outputs[1:]
|
1217 |
+
return (loss,) + output if loss is not None else output
|
1218 |
+
|
1219 |
+
return CausalLMOutputWithPast(
|
1220 |
+
loss=loss,
|
1221 |
+
logits=logits,
|
1222 |
+
past_key_values=outputs.past_key_values,
|
1223 |
+
hidden_states=outputs.hidden_states,
|
1224 |
+
attentions=outputs.attentions,
|
1225 |
+
)
|
1226 |
+
|
1227 |
+
def prepare_inputs_for_generation(
|
1228 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
1229 |
+
):
|
1230 |
+
if past_key_values is not None:
|
1231 |
+
if isinstance(past_key_values, Cache):
|
1232 |
+
cache_length = past_key_values.get_seq_length()
|
1233 |
+
past_length = past_key_values.seen_tokens
|
1234 |
+
max_cache_length = past_key_values.get_max_length()
|
1235 |
+
else:
|
1236 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1237 |
+
max_cache_length = None
|
1238 |
+
|
1239 |
+
# Keep only the unprocessed tokens:
|
1240 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1241 |
+
# some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
|
1242 |
+
# input)
|
1243 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1244 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1245 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1246 |
+
# input_ids based on the past_length.
|
1247 |
+
elif past_length < input_ids.shape[1]:
|
1248 |
+
input_ids = input_ids[:, past_length:]
|
1249 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1250 |
+
|
1251 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1252 |
+
if (
|
1253 |
+
max_cache_length is not None
|
1254 |
+
and attention_mask is not None
|
1255 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1256 |
+
):
|
1257 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1258 |
+
|
1259 |
+
position_ids = kwargs.get("position_ids", None)
|
1260 |
+
if attention_mask is not None and position_ids is None:
|
1261 |
+
# create position_ids on the fly for batch generation
|
1262 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1263 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1264 |
+
if past_key_values:
|
1265 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1266 |
+
|
1267 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1268 |
+
if inputs_embeds is not None and past_key_values is None:
|
1269 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1270 |
+
else:
|
1271 |
+
model_inputs = {"input_ids": input_ids}
|
1272 |
+
|
1273 |
+
model_inputs.update(
|
1274 |
+
{
|
1275 |
+
"position_ids": position_ids,
|
1276 |
+
"past_key_values": past_key_values,
|
1277 |
+
"use_cache": kwargs.get("use_cache"),
|
1278 |
+
"attention_mask": attention_mask,
|
1279 |
+
}
|
1280 |
+
)
|
1281 |
+
return model_inputs
|
1282 |
+
|
1283 |
+
@staticmethod
|
1284 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1285 |
+
reordered_past = ()
|
1286 |
+
for layer_past in past_key_values:
|
1287 |
+
reordered_past += (
|
1288 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1289 |
+
)
|
1290 |
+
return reordered_past
|
1291 |
+
|
1292 |
+
|
1293 |
+
@add_start_docstrings(
|
1294 |
+
"""
|
1295 |
+
The LLaMa Model transformer with a sequence classification head on top (linear layer).
|
1296 |
+
|
1297 |
+
[`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1298 |
+
(e.g. GPT-2) do.
|
1299 |
+
|
1300 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1301 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1302 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1303 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1304 |
+
each row of the batch).
|
1305 |
+
""",
|
1306 |
+
LLAMA_START_DOCSTRING,
|
1307 |
+
)
|
1308 |
+
class LlamaForSequenceClassification(LlamaPreTrainedModel):
|
1309 |
+
def __init__(self, config):
|
1310 |
+
super().__init__(config)
|
1311 |
+
self.num_labels = config.num_labels
|
1312 |
+
self.model = LlamaModel(config)
|
1313 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1314 |
+
|
1315 |
+
# Initialize weights and apply final processing
|
1316 |
+
self.post_init()
|
1317 |
+
|
1318 |
+
def get_input_embeddings(self):
|
1319 |
+
return self.model.embed_tokens
|
1320 |
+
|
1321 |
+
def set_input_embeddings(self, value):
|
1322 |
+
self.model.embed_tokens = value
|
1323 |
+
|
1324 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1325 |
+
def forward(
|
1326 |
+
self,
|
1327 |
+
input_ids: torch.LongTensor = None,
|
1328 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1329 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1330 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1331 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1332 |
+
labels: Optional[torch.LongTensor] = None,
|
1333 |
+
use_cache: Optional[bool] = None,
|
1334 |
+
output_attentions: Optional[bool] = None,
|
1335 |
+
output_hidden_states: Optional[bool] = None,
|
1336 |
+
return_dict: Optional[bool] = None,
|
1337 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1338 |
+
r"""
|
1339 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1340 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1341 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1342 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1343 |
+
"""
|
1344 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1345 |
+
|
1346 |
+
transformer_outputs = self.model(
|
1347 |
+
input_ids,
|
1348 |
+
attention_mask=attention_mask,
|
1349 |
+
position_ids=position_ids,
|
1350 |
+
past_key_values=past_key_values,
|
1351 |
+
inputs_embeds=inputs_embeds,
|
1352 |
+
use_cache=use_cache,
|
1353 |
+
output_attentions=output_attentions,
|
1354 |
+
output_hidden_states=output_hidden_states,
|
1355 |
+
return_dict=return_dict,
|
1356 |
+
)
|
1357 |
+
hidden_states = transformer_outputs[0]
|
1358 |
+
logits = self.score(hidden_states)
|
1359 |
+
|
1360 |
+
if input_ids is not None:
|
1361 |
+
batch_size = input_ids.shape[0]
|
1362 |
+
else:
|
1363 |
+
batch_size = inputs_embeds.shape[0]
|
1364 |
+
|
1365 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1366 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1367 |
+
if self.config.pad_token_id is None:
|
1368 |
+
sequence_lengths = -1
|
1369 |
+
else:
|
1370 |
+
if input_ids is not None:
|
1371 |
+
sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
|
1372 |
+
logits.device
|
1373 |
+
)
|
1374 |
+
else:
|
1375 |
+
sequence_lengths = -1
|
1376 |
+
|
1377 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1378 |
+
|
1379 |
+
loss = None
|
1380 |
+
if labels is not None:
|
1381 |
+
labels = labels.to(logits.device)
|
1382 |
+
if self.config.problem_type is None:
|
1383 |
+
if self.num_labels == 1:
|
1384 |
+
self.config.problem_type = "regression"
|
1385 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1386 |
+
self.config.problem_type = "single_label_classification"
|
1387 |
+
else:
|
1388 |
+
self.config.problem_type = "multi_label_classification"
|
1389 |
+
|
1390 |
+
if self.config.problem_type == "regression":
|
1391 |
+
loss_fct = MSELoss()
|
1392 |
+
if self.num_labels == 1:
|
1393 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1394 |
+
else:
|
1395 |
+
loss = loss_fct(pooled_logits, labels)
|
1396 |
+
elif self.config.problem_type == "single_label_classification":
|
1397 |
+
loss_fct = CrossEntropyLoss()
|
1398 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1399 |
+
elif self.config.problem_type == "multi_label_classification":
|
1400 |
+
loss_fct = BCEWithLogitsLoss()
|
1401 |
+
loss = loss_fct(pooled_logits, labels)
|
1402 |
+
if not return_dict:
|
1403 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1404 |
+
return ((loss,) + output) if loss is not None else output
|
1405 |
+
|
1406 |
+
return SequenceClassifierOutputWithPast(
|
1407 |
+
loss=loss,
|
1408 |
+
logits=pooled_logits,
|
1409 |
+
past_key_values=transformer_outputs.past_key_values,
|
1410 |
+
hidden_states=transformer_outputs.hidden_states,
|
1411 |
+
attentions=transformer_outputs.attentions,
|
1412 |
+
)
|
qwen.tiktoken
ADDED
The diff for this file is too large to render.
See raw diff
|
|
special_tokens_map.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": "<|extra_203|>",
|
3 |
+
"eos_token": {
|
4 |
+
"content": "<|im_end|>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false
|
9 |
+
},
|
10 |
+
"pad_token": "<|endoftext|>",
|
11 |
+
"unk_token": "<|endoftext|>"
|
12 |
+
}
|
tokenization_qwen.py
ADDED
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Alibaba Cloud.
|
2 |
+
#
|
3 |
+
# This source code is licensed under the license found in the
|
4 |
+
# LICENSE file in the root directory of this source tree.
|
5 |
+
|
6 |
+
"""Tokenization classes for QWen."""
|
7 |
+
|
8 |
+
import base64
|
9 |
+
import logging
|
10 |
+
import os
|
11 |
+
import unicodedata
|
12 |
+
from typing import Collection, Dict, List, Set, Tuple, Union
|
13 |
+
|
14 |
+
import tiktoken
|
15 |
+
from transformers import PreTrainedTokenizer, AddedToken
|
16 |
+
|
17 |
+
logger = logging.getLogger(__name__)
|
18 |
+
|
19 |
+
|
20 |
+
VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken"}
|
21 |
+
|
22 |
+
PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
|
23 |
+
ENDOFTEXT = "<|endoftext|>"
|
24 |
+
IMSTART = "<|im_start|>"
|
25 |
+
IMEND = "<|im_end|>"
|
26 |
+
# as the default behavior is changed to allow special tokens in
|
27 |
+
# regular texts, the surface forms of special tokens need to be
|
28 |
+
# as different as possible to minimize the impact
|
29 |
+
EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
|
30 |
+
# changed to use actual index to avoid misconfiguration with vocabulary expansion
|
31 |
+
SPECIAL_START_ID = 151643
|
32 |
+
SPECIAL_TOKENS = tuple(
|
33 |
+
enumerate(
|
34 |
+
(
|
35 |
+
(
|
36 |
+
ENDOFTEXT,
|
37 |
+
IMSTART,
|
38 |
+
IMEND,
|
39 |
+
)
|
40 |
+
+ EXTRAS
|
41 |
+
),
|
42 |
+
start=SPECIAL_START_ID,
|
43 |
+
)
|
44 |
+
)
|
45 |
+
SPECIAL_TOKENS_SET = set(t for i, t in SPECIAL_TOKENS)
|
46 |
+
|
47 |
+
|
48 |
+
def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
|
49 |
+
with open(tiktoken_bpe_file, "rb") as f:
|
50 |
+
contents = f.read()
|
51 |
+
return {
|
52 |
+
base64.b64decode(token): int(rank)
|
53 |
+
for token, rank in (line.split() for line in contents.splitlines() if line)
|
54 |
+
}
|
55 |
+
|
56 |
+
|
57 |
+
class QWenTokenizer(PreTrainedTokenizer):
|
58 |
+
"""QWen tokenizer."""
|
59 |
+
|
60 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
61 |
+
|
62 |
+
def __init__(
|
63 |
+
self,
|
64 |
+
vocab_file,
|
65 |
+
errors="replace",
|
66 |
+
extra_vocab_file=None,
|
67 |
+
**kwargs,
|
68 |
+
):
|
69 |
+
super().__init__(**kwargs)
|
70 |
+
|
71 |
+
# how to handle errors in decoding UTF-8 byte sequences
|
72 |
+
# use ignore if you are in streaming inference
|
73 |
+
self.errors = errors
|
74 |
+
|
75 |
+
self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: Dict[bytes, int]
|
76 |
+
self.special_tokens = {
|
77 |
+
token: index
|
78 |
+
for index, token in SPECIAL_TOKENS
|
79 |
+
}
|
80 |
+
|
81 |
+
# try load extra vocab from file
|
82 |
+
if extra_vocab_file is not None:
|
83 |
+
used_ids = set(self.mergeable_ranks.values()) | set(self.special_tokens.values())
|
84 |
+
extra_mergeable_ranks = _load_tiktoken_bpe(extra_vocab_file)
|
85 |
+
for token, index in extra_mergeable_ranks.items():
|
86 |
+
if token in self.mergeable_ranks:
|
87 |
+
logger.info(f"extra token {token} exists, skipping")
|
88 |
+
continue
|
89 |
+
if index in used_ids:
|
90 |
+
logger.info(f'the index {index} for extra token {token} exists, skipping')
|
91 |
+
continue
|
92 |
+
self.mergeable_ranks[token] = index
|
93 |
+
# the index may be sparse after this, but don't worry tiktoken.Encoding will handle this
|
94 |
+
|
95 |
+
enc = tiktoken.Encoding(
|
96 |
+
"Qwen",
|
97 |
+
pat_str=PAT_STR,
|
98 |
+
mergeable_ranks=self.mergeable_ranks,
|
99 |
+
special_tokens=self.special_tokens,
|
100 |
+
)
|
101 |
+
assert (
|
102 |
+
len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
|
103 |
+
), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
|
104 |
+
|
105 |
+
self.decoder = {
|
106 |
+
v: k for k, v in self.mergeable_ranks.items()
|
107 |
+
} # type: dict[int, bytes|str]
|
108 |
+
self.decoder.update({v: k for k, v in self.special_tokens.items()})
|
109 |
+
|
110 |
+
self.tokenizer = enc # type: tiktoken.Encoding
|
111 |
+
|
112 |
+
self.eod_id = self.tokenizer.eot_token
|
113 |
+
self.im_start_id = self.special_tokens[IMSTART]
|
114 |
+
self.im_end_id = self.special_tokens[IMEND]
|
115 |
+
|
116 |
+
def __getstate__(self):
|
117 |
+
# for pickle lovers
|
118 |
+
state = self.__dict__.copy()
|
119 |
+
del state["tokenizer"]
|
120 |
+
return state
|
121 |
+
|
122 |
+
def __setstate__(self, state):
|
123 |
+
# tokenizer is not python native; don't pass it; rebuild it
|
124 |
+
self.__dict__.update(state)
|
125 |
+
enc = tiktoken.Encoding(
|
126 |
+
"Qwen",
|
127 |
+
pat_str=PAT_STR,
|
128 |
+
mergeable_ranks=self.mergeable_ranks,
|
129 |
+
special_tokens=self.special_tokens,
|
130 |
+
)
|
131 |
+
self.tokenizer = enc
|
132 |
+
|
133 |
+
def __len__(self) -> int:
|
134 |
+
return self.tokenizer.n_vocab
|
135 |
+
|
136 |
+
def get_vocab(self) -> Dict[bytes, int]:
|
137 |
+
return self.mergeable_ranks
|
138 |
+
|
139 |
+
def convert_tokens_to_ids(
|
140 |
+
self, tokens: Union[bytes, str, List[Union[bytes, str]]]
|
141 |
+
) -> List[int]:
|
142 |
+
ids = []
|
143 |
+
if isinstance(tokens, (str, bytes)):
|
144 |
+
if tokens in self.special_tokens:
|
145 |
+
return self.special_tokens[tokens]
|
146 |
+
else:
|
147 |
+
return self.mergeable_ranks.get(tokens)
|
148 |
+
for token in tokens:
|
149 |
+
if token in self.special_tokens:
|
150 |
+
ids.append(self.special_tokens[token])
|
151 |
+
else:
|
152 |
+
ids.append(self.mergeable_ranks.get(token))
|
153 |
+
return ids
|
154 |
+
|
155 |
+
def _add_tokens(
|
156 |
+
self,
|
157 |
+
new_tokens: Union[List[str], List[AddedToken]],
|
158 |
+
special_tokens: bool = False,
|
159 |
+
) -> int:
|
160 |
+
if not special_tokens and new_tokens:
|
161 |
+
raise ValueError("Adding regular tokens is not supported")
|
162 |
+
for token in new_tokens:
|
163 |
+
surface_form = token.content if isinstance(token, AddedToken) else token
|
164 |
+
if surface_form not in SPECIAL_TOKENS_SET:
|
165 |
+
raise ValueError("Adding unknown special tokens is not supported")
|
166 |
+
return 0
|
167 |
+
|
168 |
+
def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
|
169 |
+
"""
|
170 |
+
Save only the vocabulary of the tokenizer (vocabulary).
|
171 |
+
|
172 |
+
Returns:
|
173 |
+
`Tuple(str)`: Paths to the files saved.
|
174 |
+
"""
|
175 |
+
file_path = os.path.join(save_directory, "qwen.tiktoken")
|
176 |
+
with open(file_path, "w", encoding="utf8") as w:
|
177 |
+
for k, v in self.mergeable_ranks.items():
|
178 |
+
line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
|
179 |
+
w.write(line)
|
180 |
+
return (file_path,)
|
181 |
+
|
182 |
+
def tokenize(
|
183 |
+
self,
|
184 |
+
text: str,
|
185 |
+
allowed_special: Union[Set, str] = "all",
|
186 |
+
disallowed_special: Union[Collection, str] = (),
|
187 |
+
**kwargs,
|
188 |
+
) -> List[Union[bytes, str]]:
|
189 |
+
"""
|
190 |
+
Converts a string in a sequence of tokens.
|
191 |
+
|
192 |
+
Args:
|
193 |
+
text (`str`):
|
194 |
+
The sequence to be encoded.
|
195 |
+
allowed_special (`Literal["all"]` or `set`):
|
196 |
+
The surface forms of the tokens to be encoded as special tokens in regular texts.
|
197 |
+
Default to "all".
|
198 |
+
disallowed_special (`Literal["all"]` or `Collection`):
|
199 |
+
The surface forms of the tokens that should not be in regular texts and trigger errors.
|
200 |
+
Default to an empty tuple.
|
201 |
+
|
202 |
+
kwargs (additional keyword arguments, *optional*):
|
203 |
+
Will be passed to the underlying model specific encode method.
|
204 |
+
|
205 |
+
Returns:
|
206 |
+
`List[bytes|str]`: The list of tokens.
|
207 |
+
"""
|
208 |
+
tokens = []
|
209 |
+
text = unicodedata.normalize("NFC", text)
|
210 |
+
|
211 |
+
# this implementation takes a detour: text -> token id -> token surface forms
|
212 |
+
for t in self.tokenizer.encode(
|
213 |
+
text, allowed_special=allowed_special, disallowed_special=disallowed_special
|
214 |
+
):
|
215 |
+
tokens.append(self.decoder[t])
|
216 |
+
return tokens
|
217 |
+
|
218 |
+
def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
|
219 |
+
"""
|
220 |
+
Converts a sequence of tokens in a single string.
|
221 |
+
"""
|
222 |
+
text = ""
|
223 |
+
temp = b""
|
224 |
+
for t in tokens:
|
225 |
+
if isinstance(t, str):
|
226 |
+
if temp:
|
227 |
+
text += temp.decode("utf-8", errors=self.errors)
|
228 |
+
temp = b""
|
229 |
+
text += t
|
230 |
+
elif isinstance(t, bytes):
|
231 |
+
temp += t
|
232 |
+
else:
|
233 |
+
raise TypeError("token should only be of type types or str")
|
234 |
+
if temp:
|
235 |
+
text += temp.decode("utf-8", errors=self.errors)
|
236 |
+
return text
|
237 |
+
|
238 |
+
@property
|
239 |
+
def vocab_size(self):
|
240 |
+
return self.tokenizer.n_vocab
|
241 |
+
|
242 |
+
def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
|
243 |
+
"""Converts an id to a token, special tokens included"""
|
244 |
+
if index in self.decoder:
|
245 |
+
return self.decoder[index]
|
246 |
+
raise ValueError("unknown ids")
|
247 |
+
|
248 |
+
def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
|
249 |
+
"""Converts a token to an id using the vocab, special tokens included"""
|
250 |
+
if token in self.special_tokens:
|
251 |
+
return self.special_tokens[token]
|
252 |
+
if token in self.mergeable_ranks:
|
253 |
+
return self.mergeable_ranks[token]
|
254 |
+
raise ValueError("unknown token")
|
255 |
+
|
256 |
+
def _tokenize(self, text: str, **kwargs):
|
257 |
+
"""
|
258 |
+
Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
|
259 |
+
vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
|
260 |
+
|
261 |
+
Do NOT take care of added tokens.
|
262 |
+
"""
|
263 |
+
raise NotImplementedError
|
264 |
+
|
265 |
+
def _decode(
|
266 |
+
self,
|
267 |
+
token_ids: Union[int, List[int]],
|
268 |
+
skip_special_tokens: bool = False,
|
269 |
+
errors: str = None,
|
270 |
+
**kwargs,
|
271 |
+
) -> str:
|
272 |
+
if isinstance(token_ids, int):
|
273 |
+
token_ids = [token_ids]
|
274 |
+
if skip_special_tokens:
|
275 |
+
token_ids = [i for i in token_ids if i < self.eod_id]
|
276 |
+
return self.tokenizer.decode(token_ids, errors=errors or self.errors)
|
tokenizer_config.json
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {},
|
3 |
+
"auto_map": {
|
4 |
+
"AutoTokenizer": [
|
5 |
+
"tokenization_qwen.QWenTokenizer",
|
6 |
+
null
|
7 |
+
]
|
8 |
+
},
|
9 |
+
"bos_token": "<|extra_203|>",
|
10 |
+
"chat_template": "{% set system_message = 'You are a helpful assistant in medical domain.' %}{% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{% endif %}{% if system_message is defined %}{{ '<|im_start|>system\\n' + system_message + '<|im_end|>\\n' }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<|im_start|>user\\n' + content + '<|im_end|>\\n<|im_start|>assistant\\n' }}{% elif message['role'] == 'assistant' %}{{ content + '<|im_end|>' + '\\n' }}{% endif %}{% endfor %}",
|
11 |
+
"clean_up_tokenization_spaces": true,
|
12 |
+
"eos_token": "<|im_end|>",
|
13 |
+
"model_max_length": 8192,
|
14 |
+
"pad_token": "<|endoftext|>",
|
15 |
+
"padding_side": "right",
|
16 |
+
"split_special_tokens": false,
|
17 |
+
"tokenizer_class": "QWenTokenizer",
|
18 |
+
"unk_token": "<|endoftext|>"
|
19 |
+
}
|
trainer_state.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
training_args.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ccf17f75ab4075e935b748bdc34bd719b604947477e1b3d5c0fefb3ecfc42f82
|
3 |
+
size 6968
|
zero_to_fp32.py
ADDED
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
# Copyright (c) Microsoft Corporation.
|
4 |
+
# SPDX-License-Identifier: Apache-2.0
|
5 |
+
|
6 |
+
# DeepSpeed Team
|
7 |
+
|
8 |
+
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
|
9 |
+
# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
|
10 |
+
# the future. Once extracted, the weights don't require DeepSpeed and can be used in any
|
11 |
+
# application.
|
12 |
+
#
|
13 |
+
# example: python zero_to_fp32.py . pytorch_model.bin
|
14 |
+
|
15 |
+
import argparse
|
16 |
+
import torch
|
17 |
+
import glob
|
18 |
+
import math
|
19 |
+
import os
|
20 |
+
import re
|
21 |
+
from collections import OrderedDict
|
22 |
+
from dataclasses import dataclass
|
23 |
+
|
24 |
+
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
|
25 |
+
# DeepSpeed data structures it has to be available in the current python environment.
|
26 |
+
from deepspeed.utils import logger
|
27 |
+
from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
|
28 |
+
FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
|
29 |
+
FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
|
30 |
+
|
31 |
+
|
32 |
+
@dataclass
|
33 |
+
class zero_model_state:
|
34 |
+
buffers: dict()
|
35 |
+
param_shapes: dict()
|
36 |
+
shared_params: list
|
37 |
+
ds_version: int
|
38 |
+
frozen_param_shapes: dict()
|
39 |
+
frozen_param_fragments: dict()
|
40 |
+
|
41 |
+
|
42 |
+
debug = 0
|
43 |
+
|
44 |
+
# load to cpu
|
45 |
+
device = torch.device('cpu')
|
46 |
+
|
47 |
+
|
48 |
+
def atoi(text):
|
49 |
+
return int(text) if text.isdigit() else text
|
50 |
+
|
51 |
+
|
52 |
+
def natural_keys(text):
|
53 |
+
'''
|
54 |
+
alist.sort(key=natural_keys) sorts in human order
|
55 |
+
http://nedbatchelder.com/blog/200712/human_sorting.html
|
56 |
+
(See Toothy's implementation in the comments)
|
57 |
+
'''
|
58 |
+
return [atoi(c) for c in re.split(r'(\d+)', text)]
|
59 |
+
|
60 |
+
|
61 |
+
def get_model_state_file(checkpoint_dir, zero_stage):
|
62 |
+
if not os.path.isdir(checkpoint_dir):
|
63 |
+
raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
|
64 |
+
|
65 |
+
# there should be only one file
|
66 |
+
if zero_stage <= 2:
|
67 |
+
file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
|
68 |
+
elif zero_stage == 3:
|
69 |
+
file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
|
70 |
+
|
71 |
+
if not os.path.exists(file):
|
72 |
+
raise FileNotFoundError(f"can't find model states file at '{file}'")
|
73 |
+
|
74 |
+
return file
|
75 |
+
|
76 |
+
|
77 |
+
def get_checkpoint_files(checkpoint_dir, glob_pattern):
|
78 |
+
# XXX: need to test that this simple glob rule works for multi-node setup too
|
79 |
+
ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
|
80 |
+
|
81 |
+
if len(ckpt_files) == 0:
|
82 |
+
raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
|
83 |
+
|
84 |
+
return ckpt_files
|
85 |
+
|
86 |
+
|
87 |
+
def get_optim_files(checkpoint_dir):
|
88 |
+
return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
|
89 |
+
|
90 |
+
|
91 |
+
def get_model_state_files(checkpoint_dir):
|
92 |
+
return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
|
93 |
+
|
94 |
+
|
95 |
+
def parse_model_states(files):
|
96 |
+
zero_model_states = []
|
97 |
+
for file in files:
|
98 |
+
state_dict = torch.load(file, map_location=device)
|
99 |
+
|
100 |
+
if BUFFER_NAMES not in state_dict:
|
101 |
+
raise ValueError(f"{file} is not a model state checkpoint")
|
102 |
+
buffer_names = state_dict[BUFFER_NAMES]
|
103 |
+
if debug:
|
104 |
+
print("Found buffers:", buffer_names)
|
105 |
+
|
106 |
+
# recover just the buffers while restoring them to fp32 if they were saved in fp16
|
107 |
+
buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
|
108 |
+
param_shapes = state_dict[PARAM_SHAPES]
|
109 |
+
|
110 |
+
# collect parameters that are included in param_shapes
|
111 |
+
param_names = []
|
112 |
+
for s in param_shapes:
|
113 |
+
for name in s.keys():
|
114 |
+
param_names.append(name)
|
115 |
+
|
116 |
+
# update with frozen parameters
|
117 |
+
frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
|
118 |
+
if frozen_param_shapes is not None:
|
119 |
+
if debug:
|
120 |
+
print(f"Found frozen_param_shapes: {frozen_param_shapes}")
|
121 |
+
param_names += list(frozen_param_shapes.keys())
|
122 |
+
|
123 |
+
# handle shared params
|
124 |
+
shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
|
125 |
+
|
126 |
+
ds_version = state_dict.get(DS_VERSION, None)
|
127 |
+
|
128 |
+
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
|
129 |
+
|
130 |
+
z_model_state = zero_model_state(buffers=buffers,
|
131 |
+
param_shapes=param_shapes,
|
132 |
+
shared_params=shared_params,
|
133 |
+
ds_version=ds_version,
|
134 |
+
frozen_param_shapes=frozen_param_shapes,
|
135 |
+
frozen_param_fragments=frozen_param_fragments)
|
136 |
+
zero_model_states.append(z_model_state)
|
137 |
+
|
138 |
+
return zero_model_states
|
139 |
+
|
140 |
+
|
141 |
+
def parse_optim_states(files, ds_checkpoint_dir):
|
142 |
+
|
143 |
+
total_files = len(files)
|
144 |
+
state_dicts = []
|
145 |
+
for f in files:
|
146 |
+
state_dict = torch.load(f, map_location=device)
|
147 |
+
# immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
|
148 |
+
# and also handle the case where it was already removed by another helper script
|
149 |
+
state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
|
150 |
+
state_dicts.append(state_dict)
|
151 |
+
|
152 |
+
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
|
153 |
+
raise ValueError(f"{files[0]} is not a zero checkpoint")
|
154 |
+
zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
|
155 |
+
world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
|
156 |
+
|
157 |
+
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert
|
158 |
+
# parameters can be different from data parallelism for non-expert parameters. So we can just
|
159 |
+
# use the max of the partition_count to get the dp world_size.
|
160 |
+
|
161 |
+
if type(world_size) is list:
|
162 |
+
world_size = max(world_size)
|
163 |
+
|
164 |
+
if world_size != total_files:
|
165 |
+
raise ValueError(
|
166 |
+
f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
|
167 |
+
"Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
|
168 |
+
)
|
169 |
+
|
170 |
+
# the groups are named differently in each stage
|
171 |
+
if zero_stage <= 2:
|
172 |
+
fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
|
173 |
+
elif zero_stage == 3:
|
174 |
+
fp32_groups_key = FP32_FLAT_GROUPS
|
175 |
+
else:
|
176 |
+
raise ValueError(f"unknown zero stage {zero_stage}")
|
177 |
+
|
178 |
+
if zero_stage <= 2:
|
179 |
+
fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
|
180 |
+
elif zero_stage == 3:
|
181 |
+
# if there is more than one param group, there will be multiple flattened tensors - one
|
182 |
+
# flattened tensor per group - for simplicity merge them into a single tensor
|
183 |
+
#
|
184 |
+
# XXX: could make the script more memory efficient for when there are multiple groups - it
|
185 |
+
# will require matching the sub-lists of param_shapes for each param group flattened tensor
|
186 |
+
|
187 |
+
fp32_flat_groups = [
|
188 |
+
torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
|
189 |
+
]
|
190 |
+
|
191 |
+
return zero_stage, world_size, fp32_flat_groups
|
192 |
+
|
193 |
+
|
194 |
+
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir):
|
195 |
+
"""
|
196 |
+
Returns fp32 state_dict reconstructed from ds checkpoint
|
197 |
+
|
198 |
+
Args:
|
199 |
+
- ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
|
200 |
+
|
201 |
+
"""
|
202 |
+
print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
|
203 |
+
|
204 |
+
optim_files = get_optim_files(ds_checkpoint_dir)
|
205 |
+
zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
|
206 |
+
print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
|
207 |
+
|
208 |
+
model_files = get_model_state_files(ds_checkpoint_dir)
|
209 |
+
|
210 |
+
zero_model_states = parse_model_states(model_files)
|
211 |
+
print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
|
212 |
+
|
213 |
+
if zero_stage <= 2:
|
214 |
+
return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states)
|
215 |
+
elif zero_stage == 3:
|
216 |
+
return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states)
|
217 |
+
|
218 |
+
|
219 |
+
def _zero2_merge_frozen_params(state_dict, zero_model_states):
|
220 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
221 |
+
return
|
222 |
+
|
223 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
224 |
+
frozen_param_fragments = zero_model_states[0].frozen_param_fragments
|
225 |
+
|
226 |
+
if debug:
|
227 |
+
num_elem = sum(s.numel() for s in frozen_param_shapes.values())
|
228 |
+
print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
229 |
+
|
230 |
+
wanted_params = len(frozen_param_shapes)
|
231 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
232 |
+
avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
|
233 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
234 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
235 |
+
|
236 |
+
total_params = 0
|
237 |
+
total_numel = 0
|
238 |
+
for name, shape in frozen_param_shapes.items():
|
239 |
+
total_params += 1
|
240 |
+
unpartitioned_numel = shape.numel()
|
241 |
+
total_numel += unpartitioned_numel
|
242 |
+
|
243 |
+
state_dict[name] = frozen_param_fragments[name]
|
244 |
+
|
245 |
+
if debug:
|
246 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
247 |
+
|
248 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
249 |
+
|
250 |
+
|
251 |
+
def _has_callable(obj, fn):
|
252 |
+
attr = getattr(obj, fn, None)
|
253 |
+
return callable(attr)
|
254 |
+
|
255 |
+
|
256 |
+
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
257 |
+
param_shapes = zero_model_states[0].param_shapes
|
258 |
+
|
259 |
+
# Reconstruction protocol:
|
260 |
+
#
|
261 |
+
# XXX: document this
|
262 |
+
|
263 |
+
if debug:
|
264 |
+
for i in range(world_size):
|
265 |
+
for j in range(len(fp32_flat_groups[0])):
|
266 |
+
print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
|
267 |
+
|
268 |
+
# XXX: memory usage doubles here (zero2)
|
269 |
+
num_param_groups = len(fp32_flat_groups[0])
|
270 |
+
merged_single_partition_of_fp32_groups = []
|
271 |
+
for i in range(num_param_groups):
|
272 |
+
merged_partitions = [sd[i] for sd in fp32_flat_groups]
|
273 |
+
full_single_fp32_vector = torch.cat(merged_partitions, 0)
|
274 |
+
merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
|
275 |
+
avail_numel = sum(
|
276 |
+
[full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
|
277 |
+
|
278 |
+
if debug:
|
279 |
+
wanted_params = sum([len(shapes) for shapes in param_shapes])
|
280 |
+
wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
|
281 |
+
# not asserting if there is a mismatch due to possible padding
|
282 |
+
print(f"Have {avail_numel} numels to process.")
|
283 |
+
print(f"Need {wanted_numel} numels in {wanted_params} params.")
|
284 |
+
|
285 |
+
# params
|
286 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
287 |
+
# out-of-core computing solution
|
288 |
+
total_numel = 0
|
289 |
+
total_params = 0
|
290 |
+
for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
|
291 |
+
offset = 0
|
292 |
+
avail_numel = full_single_fp32_vector.numel()
|
293 |
+
for name, shape in shapes.items():
|
294 |
+
|
295 |
+
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
|
296 |
+
total_numel += unpartitioned_numel
|
297 |
+
total_params += 1
|
298 |
+
|
299 |
+
if debug:
|
300 |
+
print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
|
301 |
+
state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
|
302 |
+
offset += unpartitioned_numel
|
303 |
+
|
304 |
+
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
|
305 |
+
# avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
|
306 |
+
# paddings performed in the code it's almost impossible to predict the exact numbers w/o the
|
307 |
+
# live optimizer object, so we are checking that the numbers are within the right range
|
308 |
+
align_to = 2 * world_size
|
309 |
+
|
310 |
+
def zero2_align(x):
|
311 |
+
return align_to * math.ceil(x / align_to)
|
312 |
+
|
313 |
+
if debug:
|
314 |
+
print(f"original offset={offset}, avail_numel={avail_numel}")
|
315 |
+
|
316 |
+
offset = zero2_align(offset)
|
317 |
+
avail_numel = zero2_align(avail_numel)
|
318 |
+
|
319 |
+
if debug:
|
320 |
+
print(f"aligned offset={offset}, avail_numel={avail_numel}")
|
321 |
+
|
322 |
+
# Sanity check
|
323 |
+
if offset != avail_numel:
|
324 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
325 |
+
|
326 |
+
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
|
327 |
+
|
328 |
+
|
329 |
+
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states):
|
330 |
+
state_dict = OrderedDict()
|
331 |
+
|
332 |
+
# buffers
|
333 |
+
buffers = zero_model_states[0].buffers
|
334 |
+
state_dict.update(buffers)
|
335 |
+
if debug:
|
336 |
+
print(f"added {len(buffers)} buffers")
|
337 |
+
|
338 |
+
_zero2_merge_frozen_params(state_dict, zero_model_states)
|
339 |
+
|
340 |
+
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
341 |
+
|
342 |
+
# recover shared parameters
|
343 |
+
for pair in zero_model_states[0].shared_params:
|
344 |
+
if pair[1] in state_dict:
|
345 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
346 |
+
|
347 |
+
return state_dict
|
348 |
+
|
349 |
+
|
350 |
+
def zero3_partitioned_param_info(unpartitioned_numel, world_size):
|
351 |
+
remainder = unpartitioned_numel % world_size
|
352 |
+
padding_numel = (world_size - remainder) if remainder else 0
|
353 |
+
partitioned_numel = math.ceil(unpartitioned_numel / world_size)
|
354 |
+
return partitioned_numel, padding_numel
|
355 |
+
|
356 |
+
|
357 |
+
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
|
358 |
+
if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
|
359 |
+
return
|
360 |
+
|
361 |
+
if debug:
|
362 |
+
for i in range(world_size):
|
363 |
+
num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
|
364 |
+
print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
|
365 |
+
|
366 |
+
frozen_param_shapes = zero_model_states[0].frozen_param_shapes
|
367 |
+
wanted_params = len(frozen_param_shapes)
|
368 |
+
wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
|
369 |
+
avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
|
370 |
+
print(f'Frozen params: Have {avail_numel} numels to process.')
|
371 |
+
print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
|
372 |
+
|
373 |
+
total_params = 0
|
374 |
+
total_numel = 0
|
375 |
+
for name, shape in zero_model_states[0].frozen_param_shapes.items():
|
376 |
+
total_params += 1
|
377 |
+
unpartitioned_numel = shape.numel()
|
378 |
+
total_numel += unpartitioned_numel
|
379 |
+
|
380 |
+
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
|
381 |
+
state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
|
382 |
+
|
383 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
384 |
+
|
385 |
+
if debug:
|
386 |
+
print(
|
387 |
+
f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
388 |
+
)
|
389 |
+
|
390 |
+
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
|
391 |
+
|
392 |
+
|
393 |
+
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
|
394 |
+
param_shapes = zero_model_states[0].param_shapes
|
395 |
+
avail_numel = fp32_flat_groups[0].numel() * world_size
|
396 |
+
# Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
|
397 |
+
# param, re-consolidating each param, while dealing with padding if any
|
398 |
+
|
399 |
+
# merge list of dicts, preserving order
|
400 |
+
param_shapes = {k: v for d in param_shapes for k, v in d.items()}
|
401 |
+
|
402 |
+
if debug:
|
403 |
+
for i in range(world_size):
|
404 |
+
print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
|
405 |
+
|
406 |
+
wanted_params = len(param_shapes)
|
407 |
+
wanted_numel = sum(shape.numel() for shape in param_shapes.values())
|
408 |
+
# not asserting if there is a mismatch due to possible padding
|
409 |
+
avail_numel = fp32_flat_groups[0].numel() * world_size
|
410 |
+
print(f"Trainable params: Have {avail_numel} numels to process.")
|
411 |
+
print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
|
412 |
+
|
413 |
+
# params
|
414 |
+
# XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
|
415 |
+
# out-of-core computing solution
|
416 |
+
offset = 0
|
417 |
+
total_numel = 0
|
418 |
+
total_params = 0
|
419 |
+
for name, shape in param_shapes.items():
|
420 |
+
|
421 |
+
unpartitioned_numel = shape.numel()
|
422 |
+
total_numel += unpartitioned_numel
|
423 |
+
total_params += 1
|
424 |
+
|
425 |
+
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
|
426 |
+
|
427 |
+
if debug:
|
428 |
+
print(
|
429 |
+
f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
|
430 |
+
)
|
431 |
+
|
432 |
+
# XXX: memory usage doubles here
|
433 |
+
state_dict[name] = torch.cat(
|
434 |
+
tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
|
435 |
+
0).narrow(0, 0, unpartitioned_numel).view(shape)
|
436 |
+
offset += partitioned_numel
|
437 |
+
|
438 |
+
offset *= world_size
|
439 |
+
|
440 |
+
# Sanity check
|
441 |
+
if offset != avail_numel:
|
442 |
+
raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
|
443 |
+
|
444 |
+
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
|
445 |
+
|
446 |
+
|
447 |
+
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states):
|
448 |
+
state_dict = OrderedDict()
|
449 |
+
|
450 |
+
# buffers
|
451 |
+
buffers = zero_model_states[0].buffers
|
452 |
+
state_dict.update(buffers)
|
453 |
+
if debug:
|
454 |
+
print(f"added {len(buffers)} buffers")
|
455 |
+
|
456 |
+
_zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
|
457 |
+
|
458 |
+
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
|
459 |
+
|
460 |
+
# recover shared parameters
|
461 |
+
for pair in zero_model_states[0].shared_params:
|
462 |
+
if pair[1] in state_dict:
|
463 |
+
state_dict[pair[0]] = state_dict[pair[1]]
|
464 |
+
|
465 |
+
return state_dict
|
466 |
+
|
467 |
+
|
468 |
+
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None):
|
469 |
+
"""
|
470 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
|
471 |
+
``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
|
472 |
+
via a model hub.
|
473 |
+
|
474 |
+
Args:
|
475 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder
|
476 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
|
477 |
+
|
478 |
+
Returns:
|
479 |
+
- pytorch ``state_dict``
|
480 |
+
|
481 |
+
Note: this approach may not work if your application doesn't have sufficient free CPU memory and
|
482 |
+
you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
|
483 |
+
the checkpoint.
|
484 |
+
|
485 |
+
A typical usage might be ::
|
486 |
+
|
487 |
+
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
|
488 |
+
# do the training and checkpoint saving
|
489 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
|
490 |
+
model = model.cpu() # move to cpu
|
491 |
+
model.load_state_dict(state_dict)
|
492 |
+
# submit to model hub or save the model to share with others
|
493 |
+
|
494 |
+
In this example the ``model`` will no longer be usable in the deepspeed context of the same
|
495 |
+
application. i.e. you will need to re-initialize the deepspeed engine, since
|
496 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
497 |
+
|
498 |
+
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
|
499 |
+
|
500 |
+
"""
|
501 |
+
if tag is None:
|
502 |
+
latest_path = os.path.join(checkpoint_dir, 'latest')
|
503 |
+
if os.path.isfile(latest_path):
|
504 |
+
with open(latest_path, 'r') as fd:
|
505 |
+
tag = fd.read().strip()
|
506 |
+
else:
|
507 |
+
raise ValueError(f"Unable to find 'latest' file at {latest_path}")
|
508 |
+
|
509 |
+
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
|
510 |
+
|
511 |
+
if not os.path.isdir(ds_checkpoint_dir):
|
512 |
+
raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
|
513 |
+
|
514 |
+
return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir)
|
515 |
+
|
516 |
+
|
517 |
+
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None):
|
518 |
+
"""
|
519 |
+
Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
|
520 |
+
loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
|
521 |
+
|
522 |
+
Args:
|
523 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
524 |
+
- ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
|
525 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
526 |
+
"""
|
527 |
+
|
528 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
|
529 |
+
print(f"Saving fp32 state dict to {output_file}")
|
530 |
+
torch.save(state_dict, output_file)
|
531 |
+
|
532 |
+
|
533 |
+
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
|
534 |
+
"""
|
535 |
+
1. Put the provided model to cpu
|
536 |
+
2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
|
537 |
+
3. Load it into the provided model
|
538 |
+
|
539 |
+
Args:
|
540 |
+
- ``model``: the model object to update
|
541 |
+
- ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
|
542 |
+
- ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
|
543 |
+
|
544 |
+
Returns:
|
545 |
+
- ``model`: modified model
|
546 |
+
|
547 |
+
Make sure you have plenty of CPU memory available before you call this function. If you don't
|
548 |
+
have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
|
549 |
+
conveniently placed for you in the checkpoint folder.
|
550 |
+
|
551 |
+
A typical usage might be ::
|
552 |
+
|
553 |
+
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
|
554 |
+
model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
|
555 |
+
# submit to model hub or save the model to share with others
|
556 |
+
|
557 |
+
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
|
558 |
+
of the same application. i.e. you will need to re-initialize the deepspeed engine, since
|
559 |
+
``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
|
560 |
+
|
561 |
+
"""
|
562 |
+
logger.info(f"Extracting fp32 weights")
|
563 |
+
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
|
564 |
+
|
565 |
+
logger.info(f"Overwriting model with fp32 weights")
|
566 |
+
model = model.cpu()
|
567 |
+
model.load_state_dict(state_dict, strict=False)
|
568 |
+
|
569 |
+
return model
|
570 |
+
|
571 |
+
|
572 |
+
if __name__ == "__main__":
|
573 |
+
|
574 |
+
parser = argparse.ArgumentParser()
|
575 |
+
parser.add_argument("checkpoint_dir",
|
576 |
+
type=str,
|
577 |
+
help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
|
578 |
+
parser.add_argument(
|
579 |
+
"output_file",
|
580 |
+
type=str,
|
581 |
+
help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
|
582 |
+
parser.add_argument("-t",
|
583 |
+
"--tag",
|
584 |
+
type=str,
|
585 |
+
default=None,
|
586 |
+
help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
|
587 |
+
parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
|
588 |
+
args = parser.parse_args()
|
589 |
+
|
590 |
+
debug = args.debug
|
591 |
+
|
592 |
+
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag)
|