Commit
·
1a04f1b
1
Parent(s):
f6e9985
- added_tokens.json +0 -0
- config.json +34 -0
- configuration_qwen2.py +203 -0
- generation_config.json +14 -0
- merges.txt +0 -0
- model-00001-of-00005.safetensors +3 -0
- model-00002-of-00005.safetensors +3 -0
- model-00003-of-00005.safetensors +3 -0
- model-00004-of-00005.safetensors +3 -0
- model-00005-of-00005.safetensors +3 -0
- model.safetensors.index.json +496 -0
- modeling_qwen2.py +1584 -0
- special_tokens_map.json +31 -0
- tokenization_qwen2.py +341 -0
- tokenization_qwen2_fast.py +134 -0
- tokenizer_config.json +0 -0
- vocab.json +0 -0
added_tokens.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
config.json
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Qwen2MTPForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_qwen2.Qwen2MTPConfig",
|
7 |
+
"AutoModelForCausalLM": "modeling_qwen2.Qwen2MTPForCausalLM"
|
8 |
+
},
|
9 |
+
"attention_dropout": 0.0,
|
10 |
+
"bos_token_id": 151643,
|
11 |
+
"eos_token_id": 151645,
|
12 |
+
"hidden_act": "silu",
|
13 |
+
"hidden_size": 3584,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 18944,
|
16 |
+
"max_position_embeddings": 32768,
|
17 |
+
"max_window_layers": 28,
|
18 |
+
"model_type": "qwen2_mtp",
|
19 |
+
"num_attention_heads": 28,
|
20 |
+
"num_hidden_layers": 38,
|
21 |
+
"num_key_value_heads": 4,
|
22 |
+
"num_nextn_predict_layers": 10,
|
23 |
+
"rms_norm_eps": 1e-06,
|
24 |
+
"rope_scaling": null,
|
25 |
+
"rope_theta": 1000000.0,
|
26 |
+
"sliding_window": null,
|
27 |
+
"speech_token_offset": 151685,
|
28 |
+
"tie_word_embeddings": false,
|
29 |
+
"torch_dtype": "bfloat16",
|
30 |
+
"transformers_version": "4.49.0",
|
31 |
+
"use_cache": false,
|
32 |
+
"use_sliding_window": false,
|
33 |
+
"vocab_size": 168072
|
34 |
+
}
|
configuration_qwen2.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""Qwen2 model configuration"""
|
16 |
+
|
17 |
+
from transformers.configuration_utils import PretrainedConfig
|
18 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
19 |
+
from transformers.utils import logging
|
20 |
+
|
21 |
+
|
22 |
+
logger = logging.get_logger(__name__)
|
23 |
+
|
24 |
+
|
25 |
+
class Qwen2MTPConfig(PretrainedConfig):
|
26 |
+
r"""
|
27 |
+
This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
|
28 |
+
Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
29 |
+
with the defaults will yield a similar configuration to that of
|
30 |
+
Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
|
31 |
+
|
32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
33 |
+
documentation from [`PretrainedConfig`] for more information.
|
34 |
+
|
35 |
+
|
36 |
+
Args:
|
37 |
+
vocab_size (`int`, *optional*, defaults to 151936):
|
38 |
+
Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
|
39 |
+
`inputs_ids` passed when calling [`Qwen2Model`]
|
40 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
41 |
+
Dimension of the hidden representations.
|
42 |
+
intermediate_size (`int`, *optional*, defaults to 22016):
|
43 |
+
Dimension of the MLP representations.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
45 |
+
Number of hidden layers in the Transformer encoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
47 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
48 |
+
num_key_value_heads (`int`, *optional*, defaults to 32):
|
49 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
50 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
51 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
52 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
53 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
54 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
|
55 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
56 |
+
The non-linear activation function (function or string) in the decoder.
|
57 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
58 |
+
The maximum sequence length that this model might ever be used with.
|
59 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
60 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
61 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
62 |
+
The epsilon used by the rms normalization layers.
|
63 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
64 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
65 |
+
relevant if `config.is_decoder=True`.
|
66 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
67 |
+
Whether the model's input and output word embeddings should be tied.
|
68 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
69 |
+
The base period of the RoPE embeddings.
|
70 |
+
rope_scaling (`Dict`, *optional*):
|
71 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
72 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
73 |
+
accordingly.
|
74 |
+
Expected contents:
|
75 |
+
`rope_type` (`str`):
|
76 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
77 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
78 |
+
`factor` (`float`, *optional*):
|
79 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
80 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
81 |
+
original maximum pre-trained length.
|
82 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
83 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
84 |
+
pretraining.
|
85 |
+
`attention_factor` (`float`, *optional*):
|
86 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
87 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
88 |
+
`factor` field to infer the suggested value.
|
89 |
+
`beta_fast` (`float`, *optional*):
|
90 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
91 |
+
ramp function. If unspecified, it defaults to 32.
|
92 |
+
`beta_slow` (`float`, *optional*):
|
93 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
94 |
+
ramp function. If unspecified, it defaults to 1.
|
95 |
+
`short_factor` (`List[float]`, *optional*):
|
96 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
97 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
98 |
+
size divided by the number of attention heads divided by 2
|
99 |
+
`long_factor` (`List[float]`, *optional*):
|
100 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
101 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
102 |
+
size divided by the number of attention heads divided by 2
|
103 |
+
`low_freq_factor` (`float`, *optional*):
|
104 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
105 |
+
`high_freq_factor` (`float`, *optional*):
|
106 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
107 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
108 |
+
Whether to use sliding window attention.
|
109 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
110 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
111 |
+
max_window_layers (`int`, *optional*, defaults to 28):
|
112 |
+
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
113 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
114 |
+
The dropout ratio for the attention probabilities.
|
115 |
+
|
116 |
+
```python
|
117 |
+
>>> from transformers import Qwen2Model, Qwen2Config
|
118 |
+
|
119 |
+
>>> # Initializing a Qwen2 style configuration
|
120 |
+
>>> configuration = Qwen2Config()
|
121 |
+
|
122 |
+
>>> # Initializing a model from the Qwen2-7B style configuration
|
123 |
+
>>> model = Qwen2Model(configuration)
|
124 |
+
|
125 |
+
>>> # Accessing the model configuration
|
126 |
+
>>> configuration = model.config
|
127 |
+
```"""
|
128 |
+
|
129 |
+
model_type = "qwen2_mtp"
|
130 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
131 |
+
|
132 |
+
# Default tensor parallel plan for base model `Qwen2`
|
133 |
+
base_model_tp_plan = {
|
134 |
+
"layers.*.self_attn.q_proj": "colwise",
|
135 |
+
"layers.*.self_attn.k_proj": "colwise",
|
136 |
+
"layers.*.self_attn.v_proj": "colwise",
|
137 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
138 |
+
"layers.*.mlp.gate_proj": "colwise",
|
139 |
+
"layers.*.mlp.up_proj": "colwise",
|
140 |
+
"layers.*.mlp.down_proj": "rowwise",
|
141 |
+
}
|
142 |
+
|
143 |
+
def __init__(
|
144 |
+
self,
|
145 |
+
vocab_size=151936,
|
146 |
+
hidden_size=4096,
|
147 |
+
intermediate_size=22016,
|
148 |
+
num_hidden_layers=32,
|
149 |
+
num_attention_heads=32,
|
150 |
+
num_key_value_heads=32,
|
151 |
+
hidden_act="silu",
|
152 |
+
max_position_embeddings=32768,
|
153 |
+
initializer_range=0.02,
|
154 |
+
rms_norm_eps=1e-6,
|
155 |
+
use_cache=True,
|
156 |
+
tie_word_embeddings=False,
|
157 |
+
rope_theta=10000.0,
|
158 |
+
rope_scaling=None,
|
159 |
+
use_sliding_window=False,
|
160 |
+
sliding_window=4096,
|
161 |
+
max_window_layers=28,
|
162 |
+
attention_dropout=0.0,
|
163 |
+
num_nextn_predict_layers=1,
|
164 |
+
mtp_loss_weight=1.0,
|
165 |
+
speech_token_offset=151685,
|
166 |
+
**kwargs,
|
167 |
+
):
|
168 |
+
self.vocab_size = vocab_size
|
169 |
+
self.max_position_embeddings = max_position_embeddings
|
170 |
+
self.hidden_size = hidden_size
|
171 |
+
self.intermediate_size = intermediate_size
|
172 |
+
self.num_hidden_layers = num_hidden_layers
|
173 |
+
self.num_attention_heads = num_attention_heads
|
174 |
+
self.use_sliding_window = use_sliding_window
|
175 |
+
self.sliding_window = sliding_window if use_sliding_window else None
|
176 |
+
self.max_window_layers = max_window_layers
|
177 |
+
|
178 |
+
# for backward compatibility
|
179 |
+
if num_key_value_heads is None:
|
180 |
+
num_key_value_heads = num_attention_heads
|
181 |
+
|
182 |
+
self.num_key_value_heads = num_key_value_heads
|
183 |
+
self.hidden_act = hidden_act
|
184 |
+
self.initializer_range = initializer_range
|
185 |
+
self.rms_norm_eps = rms_norm_eps
|
186 |
+
self.use_cache = use_cache
|
187 |
+
self.rope_theta = rope_theta
|
188 |
+
self.rope_scaling = rope_scaling
|
189 |
+
self.attention_dropout = attention_dropout
|
190 |
+
# Validate the correctness of rotary position embeddings parameters
|
191 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
192 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
193 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
194 |
+
rope_config_validation(self)
|
195 |
+
|
196 |
+
self.num_nextn_predict_layers = num_nextn_predict_layers
|
197 |
+
self.mtp_loss_weight = mtp_loss_weight
|
198 |
+
self.speech_token_offset = speech_token_offset
|
199 |
+
|
200 |
+
super().__init__(
|
201 |
+
tie_word_embeddings=tie_word_embeddings,
|
202 |
+
**kwargs,
|
203 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 151643,
|
3 |
+
"do_sample": true,
|
4 |
+
"eos_token_id": [
|
5 |
+
151645,
|
6 |
+
151643
|
7 |
+
],
|
8 |
+
"pad_token_id": 151643,
|
9 |
+
"repetition_penalty": 1.05,
|
10 |
+
"temperature": 0.7,
|
11 |
+
"top_k": 20,
|
12 |
+
"top_p": 0.8,
|
13 |
+
"transformers_version": "4.49.0"
|
14 |
+
}
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
model-00001-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:15a55ce0fa761976491dd2fafb8c83ff823865495d403f12b379422210bd2322
|
3 |
+
size 4992406120
|
model-00002-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0da074d9a848809f6f82966822428685e5faab0402cf3ee213ae806919933474
|
3 |
+
size 4932751008
|
model-00003-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a0bdd8ccf2bf9dc7b22e54715c8fd32582fe5dcc9fe88870d79675a669fd48ef
|
3 |
+
size 4991495888
|
model-00004-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bc75ca5ef5cf07e49fee30ecc2da8581ed919ba782110088d3599cf39ce870c5
|
3 |
+
size 4000538944
|
model-00005-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4b683585f135b796b2951e1731681f516f0261ba29f40f339dc683a7c980ca73
|
3 |
+
size 1718688768
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,496 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 20635825152
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"lm_head.weight": "model-00005-of-00005.safetensors",
|
7 |
+
"model.embed_tokens.weight": "model-00001-of-00005.safetensors",
|
8 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
9 |
+
"model.layers.0.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
|
10 |
+
"model.layers.0.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
|
11 |
+
"model.layers.0.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
|
12 |
+
"model.layers.0.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
13 |
+
"model.layers.0.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
|
14 |
+
"model.layers.0.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
|
15 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
|
16 |
+
"model.layers.0.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
|
17 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
|
18 |
+
"model.layers.0.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
|
19 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
|
20 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
21 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
|
22 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
|
23 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
|
24 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
25 |
+
"model.layers.1.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
|
26 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
|
27 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
|
28 |
+
"model.layers.1.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
|
29 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
|
30 |
+
"model.layers.1.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
|
31 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
|
32 |
+
"model.layers.10.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
33 |
+
"model.layers.10.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
34 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
35 |
+
"model.layers.10.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
36 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
37 |
+
"model.layers.10.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
38 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
39 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
40 |
+
"model.layers.10.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
41 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
42 |
+
"model.layers.10.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
43 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
44 |
+
"model.layers.11.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
45 |
+
"model.layers.11.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
46 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
47 |
+
"model.layers.11.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
48 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
49 |
+
"model.layers.11.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
50 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
51 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
52 |
+
"model.layers.11.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
53 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
54 |
+
"model.layers.11.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
55 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
56 |
+
"model.layers.12.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
57 |
+
"model.layers.12.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
58 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
59 |
+
"model.layers.12.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
60 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
61 |
+
"model.layers.12.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
62 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
63 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
64 |
+
"model.layers.12.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
65 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
66 |
+
"model.layers.12.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
67 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
68 |
+
"model.layers.13.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
69 |
+
"model.layers.13.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
70 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
71 |
+
"model.layers.13.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
72 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
73 |
+
"model.layers.13.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
74 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
75 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
76 |
+
"model.layers.13.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
77 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
78 |
+
"model.layers.13.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
79 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
80 |
+
"model.layers.14.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
81 |
+
"model.layers.14.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
82 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
83 |
+
"model.layers.14.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
84 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
85 |
+
"model.layers.14.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
86 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
87 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
88 |
+
"model.layers.14.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
89 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
90 |
+
"model.layers.14.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
91 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
92 |
+
"model.layers.15.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
93 |
+
"model.layers.15.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
94 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
95 |
+
"model.layers.15.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
96 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
97 |
+
"model.layers.15.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
98 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
99 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
100 |
+
"model.layers.15.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
101 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
102 |
+
"model.layers.15.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
103 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
104 |
+
"model.layers.16.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
105 |
+
"model.layers.16.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
106 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
107 |
+
"model.layers.16.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
108 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
109 |
+
"model.layers.16.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
110 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
111 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
112 |
+
"model.layers.16.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
113 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
114 |
+
"model.layers.16.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
115 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
116 |
+
"model.layers.17.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
117 |
+
"model.layers.17.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
118 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
119 |
+
"model.layers.17.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
120 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
121 |
+
"model.layers.17.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
122 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
123 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
124 |
+
"model.layers.17.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
125 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
126 |
+
"model.layers.17.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
127 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
128 |
+
"model.layers.18.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
129 |
+
"model.layers.18.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
130 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
131 |
+
"model.layers.18.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
132 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
133 |
+
"model.layers.18.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
134 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
135 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
136 |
+
"model.layers.18.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
137 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
138 |
+
"model.layers.18.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
139 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
140 |
+
"model.layers.19.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
141 |
+
"model.layers.19.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
142 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
143 |
+
"model.layers.19.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
144 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
145 |
+
"model.layers.19.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
146 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
147 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
148 |
+
"model.layers.19.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
149 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
150 |
+
"model.layers.19.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
151 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
152 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
153 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
|
154 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
|
155 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
|
156 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
157 |
+
"model.layers.2.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
|
158 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
|
159 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
|
160 |
+
"model.layers.2.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
|
161 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
|
162 |
+
"model.layers.2.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
|
163 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
|
164 |
+
"model.layers.20.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
165 |
+
"model.layers.20.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
166 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
167 |
+
"model.layers.20.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
168 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
169 |
+
"model.layers.20.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
170 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
171 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
172 |
+
"model.layers.20.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
173 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
174 |
+
"model.layers.20.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
175 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
176 |
+
"model.layers.21.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
177 |
+
"model.layers.21.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
178 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
179 |
+
"model.layers.21.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
180 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
181 |
+
"model.layers.21.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
182 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
183 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
184 |
+
"model.layers.21.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
185 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
186 |
+
"model.layers.21.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
187 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
188 |
+
"model.layers.22.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
189 |
+
"model.layers.22.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
190 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
191 |
+
"model.layers.22.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
192 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
193 |
+
"model.layers.22.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
194 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
195 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
196 |
+
"model.layers.22.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
197 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
198 |
+
"model.layers.22.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
199 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
200 |
+
"model.layers.23.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
201 |
+
"model.layers.23.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
202 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
203 |
+
"model.layers.23.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
204 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
205 |
+
"model.layers.23.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
206 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
207 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
208 |
+
"model.layers.23.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
209 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
210 |
+
"model.layers.23.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
211 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
212 |
+
"model.layers.24.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
213 |
+
"model.layers.24.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
214 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
215 |
+
"model.layers.24.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
216 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
217 |
+
"model.layers.24.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
218 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
219 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
220 |
+
"model.layers.24.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
221 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
222 |
+
"model.layers.24.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
223 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
224 |
+
"model.layers.25.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
225 |
+
"model.layers.25.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
226 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
227 |
+
"model.layers.25.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
228 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
229 |
+
"model.layers.25.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
230 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
231 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
232 |
+
"model.layers.25.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
233 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
234 |
+
"model.layers.25.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
235 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
236 |
+
"model.layers.26.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
237 |
+
"model.layers.26.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
238 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
239 |
+
"model.layers.26.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
240 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
241 |
+
"model.layers.26.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
242 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
243 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
244 |
+
"model.layers.26.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
245 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
246 |
+
"model.layers.26.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
247 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
248 |
+
"model.layers.27.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
249 |
+
"model.layers.27.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
250 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
251 |
+
"model.layers.27.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
252 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
253 |
+
"model.layers.27.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
254 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
255 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
256 |
+
"model.layers.27.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
257 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
258 |
+
"model.layers.27.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
259 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
260 |
+
"model.layers.28.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
261 |
+
"model.layers.28.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
|
262 |
+
"model.layers.28.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
263 |
+
"model.layers.28.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
|
264 |
+
"model.layers.28.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
265 |
+
"model.layers.28.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
266 |
+
"model.layers.28.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
267 |
+
"model.layers.28.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
268 |
+
"model.layers.28.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
269 |
+
"model.layers.28.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
270 |
+
"model.layers.28.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
271 |
+
"model.layers.28.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
272 |
+
"model.layers.29.input_layernorm.weight": "model-00004-of-00005.safetensors",
|
273 |
+
"model.layers.29.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
|
274 |
+
"model.layers.29.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
|
275 |
+
"model.layers.29.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
|
276 |
+
"model.layers.29.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
|
277 |
+
"model.layers.29.self_attn.k_proj.bias": "model-00003-of-00005.safetensors",
|
278 |
+
"model.layers.29.self_attn.k_proj.weight": "model-00003-of-00005.safetensors",
|
279 |
+
"model.layers.29.self_attn.o_proj.weight": "model-00003-of-00005.safetensors",
|
280 |
+
"model.layers.29.self_attn.q_proj.bias": "model-00003-of-00005.safetensors",
|
281 |
+
"model.layers.29.self_attn.q_proj.weight": "model-00003-of-00005.safetensors",
|
282 |
+
"model.layers.29.self_attn.v_proj.bias": "model-00003-of-00005.safetensors",
|
283 |
+
"model.layers.29.self_attn.v_proj.weight": "model-00003-of-00005.safetensors",
|
284 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
285 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
|
286 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
|
287 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
|
288 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
289 |
+
"model.layers.3.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
|
290 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
|
291 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
|
292 |
+
"model.layers.3.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
|
293 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
|
294 |
+
"model.layers.3.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
|
295 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
|
296 |
+
"model.layers.30.input_layernorm.weight": "model-00004-of-00005.safetensors",
|
297 |
+
"model.layers.30.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
|
298 |
+
"model.layers.30.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
|
299 |
+
"model.layers.30.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
|
300 |
+
"model.layers.30.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
|
301 |
+
"model.layers.30.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
|
302 |
+
"model.layers.30.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
|
303 |
+
"model.layers.30.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
|
304 |
+
"model.layers.30.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
|
305 |
+
"model.layers.30.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
|
306 |
+
"model.layers.30.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
|
307 |
+
"model.layers.30.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
|
308 |
+
"model.layers.31.input_layernorm.weight": "model-00004-of-00005.safetensors",
|
309 |
+
"model.layers.31.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
|
310 |
+
"model.layers.31.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
|
311 |
+
"model.layers.31.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
|
312 |
+
"model.layers.31.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
|
313 |
+
"model.layers.31.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
|
314 |
+
"model.layers.31.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
|
315 |
+
"model.layers.31.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
|
316 |
+
"model.layers.31.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
|
317 |
+
"model.layers.31.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
|
318 |
+
"model.layers.31.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
|
319 |
+
"model.layers.31.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
|
320 |
+
"model.layers.32.input_layernorm.weight": "model-00004-of-00005.safetensors",
|
321 |
+
"model.layers.32.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
|
322 |
+
"model.layers.32.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
|
323 |
+
"model.layers.32.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
|
324 |
+
"model.layers.32.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
|
325 |
+
"model.layers.32.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
|
326 |
+
"model.layers.32.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
|
327 |
+
"model.layers.32.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
|
328 |
+
"model.layers.32.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
|
329 |
+
"model.layers.32.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
|
330 |
+
"model.layers.32.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
|
331 |
+
"model.layers.32.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
|
332 |
+
"model.layers.33.input_layernorm.weight": "model-00004-of-00005.safetensors",
|
333 |
+
"model.layers.33.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
|
334 |
+
"model.layers.33.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
|
335 |
+
"model.layers.33.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
|
336 |
+
"model.layers.33.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
|
337 |
+
"model.layers.33.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
|
338 |
+
"model.layers.33.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
|
339 |
+
"model.layers.33.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
|
340 |
+
"model.layers.33.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
|
341 |
+
"model.layers.33.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
|
342 |
+
"model.layers.33.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
|
343 |
+
"model.layers.33.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
|
344 |
+
"model.layers.34.input_layernorm.weight": "model-00004-of-00005.safetensors",
|
345 |
+
"model.layers.34.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
|
346 |
+
"model.layers.34.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
|
347 |
+
"model.layers.34.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
|
348 |
+
"model.layers.34.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
|
349 |
+
"model.layers.34.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
|
350 |
+
"model.layers.34.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
|
351 |
+
"model.layers.34.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
|
352 |
+
"model.layers.34.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
|
353 |
+
"model.layers.34.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
|
354 |
+
"model.layers.34.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
|
355 |
+
"model.layers.34.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
|
356 |
+
"model.layers.35.input_layernorm.weight": "model-00004-of-00005.safetensors",
|
357 |
+
"model.layers.35.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
|
358 |
+
"model.layers.35.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
|
359 |
+
"model.layers.35.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
|
360 |
+
"model.layers.35.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
|
361 |
+
"model.layers.35.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
|
362 |
+
"model.layers.35.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
|
363 |
+
"model.layers.35.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
|
364 |
+
"model.layers.35.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
|
365 |
+
"model.layers.35.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
|
366 |
+
"model.layers.35.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
|
367 |
+
"model.layers.35.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
|
368 |
+
"model.layers.36.input_layernorm.weight": "model-00004-of-00005.safetensors",
|
369 |
+
"model.layers.36.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
|
370 |
+
"model.layers.36.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
|
371 |
+
"model.layers.36.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
|
372 |
+
"model.layers.36.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
|
373 |
+
"model.layers.36.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
|
374 |
+
"model.layers.36.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
|
375 |
+
"model.layers.36.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
|
376 |
+
"model.layers.36.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
|
377 |
+
"model.layers.36.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
|
378 |
+
"model.layers.36.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
|
379 |
+
"model.layers.36.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
|
380 |
+
"model.layers.37.input_layernorm.weight": "model-00004-of-00005.safetensors",
|
381 |
+
"model.layers.37.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
|
382 |
+
"model.layers.37.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
|
383 |
+
"model.layers.37.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
|
384 |
+
"model.layers.37.post_attention_layernorm.weight": "model-00004-of-00005.safetensors",
|
385 |
+
"model.layers.37.self_attn.k_proj.bias": "model-00004-of-00005.safetensors",
|
386 |
+
"model.layers.37.self_attn.k_proj.weight": "model-00004-of-00005.safetensors",
|
387 |
+
"model.layers.37.self_attn.o_proj.weight": "model-00004-of-00005.safetensors",
|
388 |
+
"model.layers.37.self_attn.q_proj.bias": "model-00004-of-00005.safetensors",
|
389 |
+
"model.layers.37.self_attn.q_proj.weight": "model-00004-of-00005.safetensors",
|
390 |
+
"model.layers.37.self_attn.v_proj.bias": "model-00004-of-00005.safetensors",
|
391 |
+
"model.layers.37.self_attn.v_proj.weight": "model-00004-of-00005.safetensors",
|
392 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
393 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
|
394 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
|
395 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
|
396 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
397 |
+
"model.layers.4.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
|
398 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
|
399 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
|
400 |
+
"model.layers.4.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
|
401 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
|
402 |
+
"model.layers.4.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
|
403 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
|
404 |
+
"model.layers.5.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
405 |
+
"model.layers.5.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
|
406 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
|
407 |
+
"model.layers.5.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
|
408 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
409 |
+
"model.layers.5.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
|
410 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
|
411 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
|
412 |
+
"model.layers.5.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
|
413 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
|
414 |
+
"model.layers.5.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
|
415 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
|
416 |
+
"model.layers.6.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
417 |
+
"model.layers.6.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
|
418 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
|
419 |
+
"model.layers.6.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
|
420 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
421 |
+
"model.layers.6.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
|
422 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
|
423 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
|
424 |
+
"model.layers.6.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
|
425 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
|
426 |
+
"model.layers.6.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
|
427 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
|
428 |
+
"model.layers.7.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
429 |
+
"model.layers.7.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
|
430 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
|
431 |
+
"model.layers.7.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
|
432 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
433 |
+
"model.layers.7.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
|
434 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
|
435 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
|
436 |
+
"model.layers.7.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
|
437 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
|
438 |
+
"model.layers.7.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
|
439 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
|
440 |
+
"model.layers.8.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
441 |
+
"model.layers.8.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
442 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
443 |
+
"model.layers.8.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
444 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
445 |
+
"model.layers.8.self_attn.k_proj.bias": "model-00001-of-00005.safetensors",
|
446 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00001-of-00005.safetensors",
|
447 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00001-of-00005.safetensors",
|
448 |
+
"model.layers.8.self_attn.q_proj.bias": "model-00001-of-00005.safetensors",
|
449 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00001-of-00005.safetensors",
|
450 |
+
"model.layers.8.self_attn.v_proj.bias": "model-00001-of-00005.safetensors",
|
451 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00001-of-00005.safetensors",
|
452 |
+
"model.layers.9.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
453 |
+
"model.layers.9.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
|
454 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
|
455 |
+
"model.layers.9.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
|
456 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
457 |
+
"model.layers.9.self_attn.k_proj.bias": "model-00002-of-00005.safetensors",
|
458 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00002-of-00005.safetensors",
|
459 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00002-of-00005.safetensors",
|
460 |
+
"model.layers.9.self_attn.q_proj.bias": "model-00002-of-00005.safetensors",
|
461 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00002-of-00005.safetensors",
|
462 |
+
"model.layers.9.self_attn.v_proj.bias": "model-00002-of-00005.safetensors",
|
463 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00002-of-00005.safetensors",
|
464 |
+
"model.norm.weight": "model-00004-of-00005.safetensors",
|
465 |
+
"mtp_embed_norms.0.weight": "model-00005-of-00005.safetensors",
|
466 |
+
"mtp_embed_norms.1.weight": "model-00005-of-00005.safetensors",
|
467 |
+
"mtp_embed_norms.2.weight": "model-00005-of-00005.safetensors",
|
468 |
+
"mtp_embed_norms.3.weight": "model-00005-of-00005.safetensors",
|
469 |
+
"mtp_embed_norms.4.weight": "model-00005-of-00005.safetensors",
|
470 |
+
"mtp_embed_norms.5.weight": "model-00005-of-00005.safetensors",
|
471 |
+
"mtp_embed_norms.6.weight": "model-00005-of-00005.safetensors",
|
472 |
+
"mtp_embed_norms.7.weight": "model-00005-of-00005.safetensors",
|
473 |
+
"mtp_embed_norms.8.weight": "model-00005-of-00005.safetensors",
|
474 |
+
"mtp_embed_norms.9.weight": "model-00005-of-00005.safetensors",
|
475 |
+
"mtp_hidden_norms.0.weight": "model-00005-of-00005.safetensors",
|
476 |
+
"mtp_hidden_norms.1.weight": "model-00005-of-00005.safetensors",
|
477 |
+
"mtp_hidden_norms.2.weight": "model-00005-of-00005.safetensors",
|
478 |
+
"mtp_hidden_norms.3.weight": "model-00005-of-00005.safetensors",
|
479 |
+
"mtp_hidden_norms.4.weight": "model-00005-of-00005.safetensors",
|
480 |
+
"mtp_hidden_norms.5.weight": "model-00005-of-00005.safetensors",
|
481 |
+
"mtp_hidden_norms.6.weight": "model-00005-of-00005.safetensors",
|
482 |
+
"mtp_hidden_norms.7.weight": "model-00005-of-00005.safetensors",
|
483 |
+
"mtp_hidden_norms.8.weight": "model-00005-of-00005.safetensors",
|
484 |
+
"mtp_hidden_norms.9.weight": "model-00005-of-00005.safetensors",
|
485 |
+
"mtp_projs.0.weight": "model-00005-of-00005.safetensors",
|
486 |
+
"mtp_projs.1.weight": "model-00005-of-00005.safetensors",
|
487 |
+
"mtp_projs.2.weight": "model-00005-of-00005.safetensors",
|
488 |
+
"mtp_projs.3.weight": "model-00005-of-00005.safetensors",
|
489 |
+
"mtp_projs.4.weight": "model-00005-of-00005.safetensors",
|
490 |
+
"mtp_projs.5.weight": "model-00005-of-00005.safetensors",
|
491 |
+
"mtp_projs.6.weight": "model-00005-of-00005.safetensors",
|
492 |
+
"mtp_projs.7.weight": "model-00005-of-00005.safetensors",
|
493 |
+
"mtp_projs.8.weight": "model-00005-of-00005.safetensors",
|
494 |
+
"mtp_projs.9.weight": "model-00005-of-00005.safetensors"
|
495 |
+
}
|
496 |
+
}
|
modeling_qwen2.py
ADDED
@@ -0,0 +1,1584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
2 |
+
# This file was automatically generated from src/transformers/models/qwen2/modular_qwen2.py.
|
3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
5 |
+
# modular_qwen2.py file directly. One of our CI enforces this.
|
6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
7 |
+
from typing import Callable, List, Optional, Tuple, Union
|
8 |
+
|
9 |
+
import torch
|
10 |
+
from torch import nn
|
11 |
+
|
12 |
+
from transformers.activations import ACT2FN
|
13 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
14 |
+
from transformers.generation import GenerationMixin
|
15 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
16 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
17 |
+
from transformers.modeling_outputs import (
|
18 |
+
BaseModelOutputWithPast,
|
19 |
+
CausalLMOutputWithPast,
|
20 |
+
QuestionAnsweringModelOutput,
|
21 |
+
SequenceClassifierOutputWithPast,
|
22 |
+
TokenClassifierOutput,
|
23 |
+
)
|
24 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
25 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
26 |
+
from transformers.processing_utils import Unpack
|
27 |
+
from transformers.utils import (
|
28 |
+
LossKwargs,
|
29 |
+
add_code_sample_docstrings,
|
30 |
+
add_start_docstrings,
|
31 |
+
add_start_docstrings_to_model_forward,
|
32 |
+
logging,
|
33 |
+
replace_return_docstrings,
|
34 |
+
)
|
35 |
+
from .configuration_qwen2 import Qwen2MTPConfig as Qwen2Config
|
36 |
+
|
37 |
+
|
38 |
+
logger = logging.get_logger(__name__)
|
39 |
+
logger.setLevel(logging.INFO)
|
40 |
+
|
41 |
+
_CHECKPOINT_FOR_DOC = "meta-qwen2/Qwen2-2-7b-hf"
|
42 |
+
_CONFIG_FOR_DOC = "Qwen2Config"
|
43 |
+
|
44 |
+
|
45 |
+
def fixed_cross_entropy(source, target, num_items_in_batch: int = None, ignore_index: int = -100, **kwargs):
|
46 |
+
reduction = "sum" if num_items_in_batch is not None else "mean"
|
47 |
+
loss = nn.functional.cross_entropy(source, target, ignore_index=ignore_index, reduction=reduction)
|
48 |
+
if reduction == "sum":
|
49 |
+
loss = loss / num_items_in_batch
|
50 |
+
return loss
|
51 |
+
|
52 |
+
|
53 |
+
def ForCausalLMLoss(
|
54 |
+
logits, labels, vocab_size: int, num_items_in_batch: int = None, ignore_index: int = -100, **kwargs
|
55 |
+
):
|
56 |
+
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
57 |
+
# logits = logits.float()
|
58 |
+
labels = labels.to(logits.device)
|
59 |
+
# Shift so that tokens < n predict n
|
60 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
61 |
+
shift_labels = labels[..., 1:].contiguous()
|
62 |
+
|
63 |
+
# Flatten the tokens
|
64 |
+
shift_logits = shift_logits.view(-1, vocab_size)
|
65 |
+
shift_labels = shift_labels.view(-1)
|
66 |
+
# Enable model parallelism
|
67 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
68 |
+
loss = fixed_cross_entropy(shift_logits, shift_labels, num_items_in_batch, ignore_index, **kwargs)
|
69 |
+
return loss
|
70 |
+
|
71 |
+
|
72 |
+
def compute_kl_loss(logits, labels):
|
73 |
+
# import pdb;pdb.set_trace()
|
74 |
+
*_, vocab_size = logits.shape
|
75 |
+
# Convert logits to log probabilities
|
76 |
+
log_probs = torch.nn.functional.log_softmax(logits, dim=-1)
|
77 |
+
# Convert labels to probabilities
|
78 |
+
target_probs = torch.nn.functional.softmax(labels, dim=-1)
|
79 |
+
# Define the KL Divergence loss function
|
80 |
+
loss_fct = nn.KLDivLoss(reduction='batchmean')
|
81 |
+
# Compute the loss
|
82 |
+
loss = loss_fct(log_probs.view(-1, vocab_size), target_probs.view(-1, vocab_size))
|
83 |
+
return loss
|
84 |
+
|
85 |
+
|
86 |
+
class Qwen2MLP(nn.Module):
|
87 |
+
def __init__(self, config):
|
88 |
+
super().__init__()
|
89 |
+
self.config = config
|
90 |
+
self.hidden_size = config.hidden_size
|
91 |
+
self.intermediate_size = config.intermediate_size
|
92 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
93 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
94 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
95 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
96 |
+
|
97 |
+
def forward(self, x):
|
98 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
99 |
+
return down_proj
|
100 |
+
|
101 |
+
|
102 |
+
def rotate_half(x):
|
103 |
+
"""Rotates half the hidden dims of the input."""
|
104 |
+
x1 = x[..., : x.shape[-1] // 2]
|
105 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
106 |
+
return torch.cat((-x2, x1), dim=-1)
|
107 |
+
|
108 |
+
|
109 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
110 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
111 |
+
|
112 |
+
Args:
|
113 |
+
q (`torch.Tensor`): The query tensor.
|
114 |
+
k (`torch.Tensor`): The key tensor.
|
115 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
116 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
117 |
+
position_ids (`torch.Tensor`, *optional*):
|
118 |
+
Deprecated and unused.
|
119 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
120 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
121 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
122 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
123 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
124 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
125 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
126 |
+
Returns:
|
127 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
128 |
+
"""
|
129 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
130 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
131 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
132 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
133 |
+
return q_embed, k_embed
|
134 |
+
|
135 |
+
|
136 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
137 |
+
"""
|
138 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
139 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
140 |
+
"""
|
141 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
142 |
+
if n_rep == 1:
|
143 |
+
return hidden_states
|
144 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
145 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
146 |
+
|
147 |
+
|
148 |
+
def eager_attention_forward(
|
149 |
+
module: nn.Module,
|
150 |
+
query: torch.Tensor,
|
151 |
+
key: torch.Tensor,
|
152 |
+
value: torch.Tensor,
|
153 |
+
attention_mask: Optional[torch.Tensor],
|
154 |
+
scaling: float,
|
155 |
+
dropout: float = 0.0,
|
156 |
+
**kwargs,
|
157 |
+
):
|
158 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
159 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
160 |
+
|
161 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
162 |
+
if attention_mask is not None:
|
163 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
164 |
+
attn_weights = attn_weights + causal_mask
|
165 |
+
|
166 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
167 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
168 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
169 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
170 |
+
|
171 |
+
return attn_output, attn_weights
|
172 |
+
|
173 |
+
|
174 |
+
class Qwen2Attention(nn.Module):
|
175 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
176 |
+
|
177 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
178 |
+
super().__init__()
|
179 |
+
self.config = config
|
180 |
+
self.layer_idx = layer_idx
|
181 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
182 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
183 |
+
self.scaling = self.head_dim**-0.5
|
184 |
+
self.attention_dropout = config.attention_dropout
|
185 |
+
self.is_causal = True
|
186 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
|
187 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
188 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
|
189 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
190 |
+
|
191 |
+
def forward(
|
192 |
+
self,
|
193 |
+
hidden_states: torch.Tensor,
|
194 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
195 |
+
attention_mask: Optional[torch.Tensor],
|
196 |
+
past_key_value: Optional[Cache] = None,
|
197 |
+
cache_position: Optional[torch.LongTensor] = None,
|
198 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
199 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
200 |
+
input_shape = hidden_states.shape[:-1]
|
201 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
202 |
+
|
203 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
204 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
205 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
206 |
+
|
207 |
+
cos, sin = position_embeddings
|
208 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
209 |
+
|
210 |
+
if past_key_value is not None:
|
211 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
212 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
213 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
214 |
+
|
215 |
+
sliding_window = None
|
216 |
+
if (
|
217 |
+
self.config.use_sliding_window
|
218 |
+
and getattr(self.config, "sliding_window", None) is not None
|
219 |
+
and self.layer_idx >= self.config.max_window_layers
|
220 |
+
):
|
221 |
+
sliding_window = self.config.sliding_window
|
222 |
+
|
223 |
+
attention_interface: Callable = eager_attention_forward
|
224 |
+
if self.config._attn_implementation != "eager":
|
225 |
+
if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
|
226 |
+
logger.warning_once(
|
227 |
+
"`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
|
228 |
+
'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
229 |
+
)
|
230 |
+
else:
|
231 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
232 |
+
|
233 |
+
attn_output, attn_weights = attention_interface(
|
234 |
+
self,
|
235 |
+
query_states,
|
236 |
+
key_states,
|
237 |
+
value_states,
|
238 |
+
attention_mask,
|
239 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
240 |
+
scaling=self.scaling,
|
241 |
+
sliding_window=sliding_window, # main diff with Llama
|
242 |
+
**kwargs,
|
243 |
+
)
|
244 |
+
|
245 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
246 |
+
attn_output = self.o_proj(attn_output)
|
247 |
+
return attn_output, attn_weights
|
248 |
+
|
249 |
+
|
250 |
+
class Qwen2RMSNorm(nn.Module):
|
251 |
+
def __init__(self, hidden_size, eps=1e-6):
|
252 |
+
"""
|
253 |
+
Qwen2RMSNorm is equivalent to T5LayerNorm
|
254 |
+
"""
|
255 |
+
super().__init__()
|
256 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
257 |
+
self.variance_epsilon = eps
|
258 |
+
|
259 |
+
def forward(self, hidden_states):
|
260 |
+
input_dtype = hidden_states.dtype
|
261 |
+
hidden_states = hidden_states.to(torch.float32)
|
262 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
263 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
264 |
+
return self.weight * hidden_states.to(input_dtype)
|
265 |
+
|
266 |
+
def extra_repr(self):
|
267 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
268 |
+
|
269 |
+
|
270 |
+
class Qwen2DecoderLayer(nn.Module):
|
271 |
+
def __init__(self, config: Qwen2Config, layer_idx: int):
|
272 |
+
super().__init__()
|
273 |
+
self.hidden_size = config.hidden_size
|
274 |
+
self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
|
275 |
+
self.mlp = Qwen2MLP(config)
|
276 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
277 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
278 |
+
if config.sliding_window and config._attn_implementation != "flash_attention_2":
|
279 |
+
logger.warning_once(
|
280 |
+
f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
|
281 |
+
"unexpected results may be encountered."
|
282 |
+
)
|
283 |
+
|
284 |
+
def forward(
|
285 |
+
self,
|
286 |
+
hidden_states: torch.Tensor,
|
287 |
+
attention_mask: Optional[torch.Tensor] = None,
|
288 |
+
position_ids: Optional[torch.LongTensor] = None,
|
289 |
+
past_key_value: Optional[Cache] = None,
|
290 |
+
output_attentions: Optional[bool] = False,
|
291 |
+
use_cache: Optional[bool] = False,
|
292 |
+
cache_position: Optional[torch.LongTensor] = None,
|
293 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
294 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
295 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
296 |
+
residual = hidden_states
|
297 |
+
|
298 |
+
hidden_states = self.input_layernorm(hidden_states)
|
299 |
+
|
300 |
+
# Self Attention
|
301 |
+
hidden_states, self_attn_weights = self.self_attn(
|
302 |
+
hidden_states=hidden_states,
|
303 |
+
attention_mask=attention_mask,
|
304 |
+
position_ids=position_ids,
|
305 |
+
past_key_value=past_key_value,
|
306 |
+
output_attentions=output_attentions,
|
307 |
+
use_cache=use_cache,
|
308 |
+
cache_position=cache_position,
|
309 |
+
position_embeddings=position_embeddings,
|
310 |
+
**kwargs,
|
311 |
+
)
|
312 |
+
hidden_states = residual + hidden_states
|
313 |
+
|
314 |
+
# Fully Connected
|
315 |
+
residual = hidden_states
|
316 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
317 |
+
hidden_states = self.mlp(hidden_states)
|
318 |
+
hidden_states = residual + hidden_states
|
319 |
+
|
320 |
+
outputs = (hidden_states,)
|
321 |
+
if output_attentions:
|
322 |
+
outputs += (self_attn_weights,)
|
323 |
+
|
324 |
+
return outputs
|
325 |
+
|
326 |
+
|
327 |
+
class Qwen2RotaryEmbedding(nn.Module):
|
328 |
+
def __init__(self, config: Qwen2Config, device=None):
|
329 |
+
super().__init__()
|
330 |
+
# BC: "rope_type" was originally "type"
|
331 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
332 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
333 |
+
else:
|
334 |
+
self.rope_type = "default"
|
335 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
336 |
+
self.original_max_seq_len = config.max_position_embeddings
|
337 |
+
|
338 |
+
self.config = config
|
339 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
340 |
+
|
341 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
342 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
343 |
+
self.original_inv_freq = self.inv_freq
|
344 |
+
|
345 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
346 |
+
"""
|
347 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
348 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
349 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
350 |
+
"""
|
351 |
+
seq_len = torch.max(position_ids) + 1
|
352 |
+
if seq_len > self.max_seq_len_cached: # growth
|
353 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
354 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
355 |
+
self.max_seq_len_cached = seq_len
|
356 |
+
|
357 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
358 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
359 |
+
# the buffer is automatically moved, but not the original copy)
|
360 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
361 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
362 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
363 |
+
|
364 |
+
@torch.no_grad()
|
365 |
+
def forward(self, x, position_ids):
|
366 |
+
if "dynamic" in self.rope_type:
|
367 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
368 |
+
|
369 |
+
# Core RoPE block
|
370 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
371 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
372 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
373 |
+
device_type = x.device.type
|
374 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
375 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
376 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
377 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
378 |
+
cos = emb.cos()
|
379 |
+
sin = emb.sin()
|
380 |
+
|
381 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
382 |
+
cos = cos * self.attention_scaling
|
383 |
+
sin = sin * self.attention_scaling
|
384 |
+
|
385 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
386 |
+
|
387 |
+
|
388 |
+
QWEN2_START_DOCSTRING = r"""
|
389 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
390 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
391 |
+
etc.)
|
392 |
+
|
393 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
394 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
395 |
+
and behavior.
|
396 |
+
|
397 |
+
Parameters:
|
398 |
+
config ([`Qwen2Config`]):
|
399 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
400 |
+
load the weights associated with the model, only the configuration. Check out the
|
401 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
402 |
+
"""
|
403 |
+
|
404 |
+
|
405 |
+
@add_start_docstrings(
|
406 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
407 |
+
QWEN2_START_DOCSTRING,
|
408 |
+
)
|
409 |
+
class Qwen2PreTrainedModel(PreTrainedModel):
|
410 |
+
config_class = Qwen2Config
|
411 |
+
base_model_prefix = "model"
|
412 |
+
supports_gradient_checkpointing = True
|
413 |
+
_no_split_modules = ["Qwen2DecoderLayer"]
|
414 |
+
_skip_keys_device_placement = ["past_key_values"]
|
415 |
+
_supports_flash_attn_2 = True
|
416 |
+
_supports_sdpa = True
|
417 |
+
_supports_flex_attn = True
|
418 |
+
_supports_cache_class = True
|
419 |
+
_supports_quantized_cache = True
|
420 |
+
_supports_static_cache = True
|
421 |
+
|
422 |
+
def _init_weights(self, module):
|
423 |
+
std = self.config.initializer_range
|
424 |
+
if isinstance(module, nn.Linear):
|
425 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
426 |
+
if module.bias is not None:
|
427 |
+
module.bias.data.zero_()
|
428 |
+
elif isinstance(module, nn.Embedding):
|
429 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
430 |
+
if module.padding_idx is not None:
|
431 |
+
module.weight.data[module.padding_idx].zero_()
|
432 |
+
|
433 |
+
|
434 |
+
QWEN2_INPUTS_DOCSTRING = r"""
|
435 |
+
Args:
|
436 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
437 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
438 |
+
it.
|
439 |
+
|
440 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
441 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
442 |
+
|
443 |
+
[What are input IDs?](../glossary#input-ids)
|
444 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
445 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
446 |
+
|
447 |
+
- 1 for tokens that are **not masked**,
|
448 |
+
- 0 for tokens that are **masked**.
|
449 |
+
|
450 |
+
[What are attention masks?](../glossary#attention-mask)
|
451 |
+
|
452 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
453 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
454 |
+
|
455 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
456 |
+
`past_key_values`).
|
457 |
+
|
458 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
459 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
460 |
+
information on the default strategy.
|
461 |
+
|
462 |
+
- 1 indicates the head is **not masked**,
|
463 |
+
- 0 indicates the head is **masked**.
|
464 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
465 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
466 |
+
config.n_positions - 1]`.
|
467 |
+
|
468 |
+
[What are position IDs?](../glossary#position-ids)
|
469 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
470 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
471 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
472 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
473 |
+
|
474 |
+
Two formats are allowed:
|
475 |
+
- a [`~cache_utils.Cache`] instance, see our
|
476 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
477 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
478 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
479 |
+
cache format.
|
480 |
+
|
481 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
482 |
+
legacy cache format will be returned.
|
483 |
+
|
484 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
485 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
486 |
+
of shape `(batch_size, sequence_length)`.
|
487 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
488 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
489 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
490 |
+
model's internal embedding lookup matrix.
|
491 |
+
use_cache (`bool`, *optional*):
|
492 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
493 |
+
`past_key_values`).
|
494 |
+
output_attentions (`bool`, *optional*):
|
495 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
496 |
+
tensors for more detail.
|
497 |
+
output_hidden_states (`bool`, *optional*):
|
498 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
499 |
+
more detail.
|
500 |
+
return_dict (`bool`, *optional*):
|
501 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
502 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
503 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
504 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
505 |
+
the complete sequence length.
|
506 |
+
"""
|
507 |
+
|
508 |
+
|
509 |
+
@add_start_docstrings(
|
510 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
511 |
+
QWEN2_START_DOCSTRING,
|
512 |
+
)
|
513 |
+
class Qwen2Model(Qwen2PreTrainedModel):
|
514 |
+
"""
|
515 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
|
516 |
+
|
517 |
+
Args:
|
518 |
+
config: Qwen2Config
|
519 |
+
"""
|
520 |
+
|
521 |
+
def __init__(self, config: Qwen2Config):
|
522 |
+
super().__init__(config)
|
523 |
+
self.padding_idx = config.pad_token_id
|
524 |
+
self.vocab_size = config.vocab_size
|
525 |
+
|
526 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
527 |
+
self.layers = nn.ModuleList(
|
528 |
+
[Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
529 |
+
)
|
530 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
531 |
+
self.rotary_emb = Qwen2RotaryEmbedding(config=config)
|
532 |
+
self.gradient_checkpointing = False
|
533 |
+
|
534 |
+
# Initialize weights and apply final processing
|
535 |
+
self.post_init()
|
536 |
+
|
537 |
+
def get_input_embeddings(self):
|
538 |
+
return self.embed_tokens
|
539 |
+
|
540 |
+
def set_input_embeddings(self, value):
|
541 |
+
self.embed_tokens = value
|
542 |
+
|
543 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
544 |
+
def forward(
|
545 |
+
self,
|
546 |
+
input_ids: torch.LongTensor = None,
|
547 |
+
attention_mask: Optional[torch.Tensor] = None,
|
548 |
+
position_ids: Optional[torch.LongTensor] = None,
|
549 |
+
past_key_values: Optional[Cache] = None,
|
550 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
551 |
+
use_cache: Optional[bool] = None,
|
552 |
+
output_attentions: Optional[bool] = None,
|
553 |
+
output_hidden_states: Optional[bool] = None,
|
554 |
+
return_dict: Optional[bool] = None,
|
555 |
+
cache_position: Optional[torch.LongTensor] = None,
|
556 |
+
layer_idxs = None,
|
557 |
+
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
|
558 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
559 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
560 |
+
output_hidden_states = (
|
561 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
562 |
+
)
|
563 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
564 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
565 |
+
|
566 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
567 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
568 |
+
|
569 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
570 |
+
logger.warning_once(
|
571 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
572 |
+
)
|
573 |
+
use_cache = False
|
574 |
+
|
575 |
+
if inputs_embeds is None:
|
576 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
577 |
+
|
578 |
+
if use_cache and past_key_values is None:
|
579 |
+
past_key_values = DynamicCache()
|
580 |
+
|
581 |
+
if cache_position is None:
|
582 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
583 |
+
cache_position = torch.arange(
|
584 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
585 |
+
)
|
586 |
+
|
587 |
+
if position_ids is None:
|
588 |
+
position_ids = cache_position.unsqueeze(0)
|
589 |
+
|
590 |
+
causal_mask = self._update_causal_mask(
|
591 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
592 |
+
)
|
593 |
+
|
594 |
+
hidden_states = inputs_embeds
|
595 |
+
|
596 |
+
# create position embeddings to be shared across the decoder layers
|
597 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
598 |
+
|
599 |
+
# decoder layers
|
600 |
+
all_hidden_states = () if output_hidden_states else None
|
601 |
+
all_self_attns = () if output_attentions else None
|
602 |
+
|
603 |
+
if layer_idxs is None:
|
604 |
+
layer_idxs = list(range(self.config.num_hidden_layers))
|
605 |
+
layers = [self.layers[layer_idx] for layer_idx in layer_idxs]
|
606 |
+
|
607 |
+
for decoder_layer in layers:
|
608 |
+
if output_hidden_states:
|
609 |
+
all_hidden_states += (hidden_states,)
|
610 |
+
|
611 |
+
if self.gradient_checkpointing and self.training:
|
612 |
+
layer_outputs = self._gradient_checkpointing_func(
|
613 |
+
decoder_layer.__call__,
|
614 |
+
hidden_states,
|
615 |
+
causal_mask,
|
616 |
+
position_ids,
|
617 |
+
past_key_values,
|
618 |
+
output_attentions,
|
619 |
+
use_cache,
|
620 |
+
cache_position,
|
621 |
+
position_embeddings,
|
622 |
+
**flash_attn_kwargs,
|
623 |
+
)
|
624 |
+
else:
|
625 |
+
layer_outputs = decoder_layer(
|
626 |
+
hidden_states,
|
627 |
+
attention_mask=causal_mask,
|
628 |
+
position_ids=position_ids,
|
629 |
+
past_key_value=past_key_values,
|
630 |
+
output_attentions=output_attentions,
|
631 |
+
use_cache=use_cache,
|
632 |
+
cache_position=cache_position,
|
633 |
+
position_embeddings=position_embeddings,
|
634 |
+
**flash_attn_kwargs,
|
635 |
+
)
|
636 |
+
|
637 |
+
hidden_states = layer_outputs[0]
|
638 |
+
|
639 |
+
if output_attentions:
|
640 |
+
all_self_attns += (layer_outputs[1],)
|
641 |
+
|
642 |
+
hidden_states = self.norm(hidden_states)
|
643 |
+
|
644 |
+
# add hidden states from the last decoder layer
|
645 |
+
if output_hidden_states:
|
646 |
+
all_hidden_states += (hidden_states,)
|
647 |
+
|
648 |
+
output = BaseModelOutputWithPast(
|
649 |
+
last_hidden_state=hidden_states,
|
650 |
+
past_key_values=past_key_values if use_cache else None,
|
651 |
+
hidden_states=all_hidden_states,
|
652 |
+
attentions=all_self_attns,
|
653 |
+
)
|
654 |
+
return output if return_dict else output.to_tuple()
|
655 |
+
|
656 |
+
def _update_causal_mask(
|
657 |
+
self,
|
658 |
+
attention_mask: torch.Tensor,
|
659 |
+
input_tensor: torch.Tensor,
|
660 |
+
cache_position: torch.Tensor,
|
661 |
+
past_key_values: Cache,
|
662 |
+
output_attentions: bool,
|
663 |
+
):
|
664 |
+
if self.config._attn_implementation == "flash_attention_2":
|
665 |
+
if attention_mask is not None and (attention_mask == 0.0).any():
|
666 |
+
return attention_mask
|
667 |
+
return None
|
668 |
+
|
669 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
670 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
671 |
+
# to infer the attention mask.
|
672 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
673 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
674 |
+
|
675 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
676 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
677 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
678 |
+
attention_mask,
|
679 |
+
inputs_embeds=input_tensor,
|
680 |
+
past_key_values_length=past_seen_tokens,
|
681 |
+
is_training=self.training,
|
682 |
+
):
|
683 |
+
return None
|
684 |
+
|
685 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
686 |
+
sequence_length = input_tensor.shape[1]
|
687 |
+
if using_static_cache:
|
688 |
+
target_length = past_key_values.get_max_cache_shape()
|
689 |
+
else:
|
690 |
+
target_length = (
|
691 |
+
attention_mask.shape[-1]
|
692 |
+
if isinstance(attention_mask, torch.Tensor)
|
693 |
+
else past_seen_tokens + sequence_length + 1
|
694 |
+
)
|
695 |
+
|
696 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
697 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
698 |
+
attention_mask,
|
699 |
+
sequence_length=sequence_length,
|
700 |
+
target_length=target_length,
|
701 |
+
dtype=dtype,
|
702 |
+
device=device,
|
703 |
+
cache_position=cache_position,
|
704 |
+
batch_size=input_tensor.shape[0],
|
705 |
+
)
|
706 |
+
|
707 |
+
if (
|
708 |
+
self.config._attn_implementation == "sdpa"
|
709 |
+
and attention_mask is not None
|
710 |
+
and attention_mask.device.type == "cuda"
|
711 |
+
and not output_attentions
|
712 |
+
):
|
713 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
714 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
715 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
716 |
+
min_dtype = torch.finfo(dtype).min
|
717 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
718 |
+
|
719 |
+
return causal_mask
|
720 |
+
|
721 |
+
@staticmethod
|
722 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
723 |
+
attention_mask: torch.Tensor,
|
724 |
+
sequence_length: int,
|
725 |
+
target_length: int,
|
726 |
+
dtype: torch.dtype,
|
727 |
+
device: torch.device,
|
728 |
+
cache_position: torch.Tensor,
|
729 |
+
batch_size: int,
|
730 |
+
**kwargs,
|
731 |
+
):
|
732 |
+
"""
|
733 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
734 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
735 |
+
|
736 |
+
Args:
|
737 |
+
attention_mask (`torch.Tensor`):
|
738 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
739 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
740 |
+
sequence_length (`int`):
|
741 |
+
The sequence length being processed.
|
742 |
+
target_length (`int`):
|
743 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
744 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
745 |
+
dtype (`torch.dtype`):
|
746 |
+
The dtype to use for the 4D attention mask.
|
747 |
+
device (`torch.device`):
|
748 |
+
The device to plcae the 4D attention mask on.
|
749 |
+
cache_position (`torch.Tensor`):
|
750 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
751 |
+
batch_size (`torch.Tensor`):
|
752 |
+
Batch size.
|
753 |
+
"""
|
754 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
755 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
756 |
+
causal_mask = attention_mask
|
757 |
+
else:
|
758 |
+
min_dtype = torch.finfo(dtype).min
|
759 |
+
causal_mask = torch.full(
|
760 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
761 |
+
)
|
762 |
+
if sequence_length != 1:
|
763 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
764 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
765 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
766 |
+
if attention_mask is not None:
|
767 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
768 |
+
mask_length = attention_mask.shape[-1]
|
769 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
770 |
+
padding_mask = padding_mask == 0
|
771 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
772 |
+
padding_mask, min_dtype
|
773 |
+
)
|
774 |
+
|
775 |
+
return causal_mask
|
776 |
+
|
777 |
+
|
778 |
+
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
|
779 |
+
|
780 |
+
|
781 |
+
class Qwen2MTPForCausalLM(Qwen2PreTrainedModel, GenerationMixin):
|
782 |
+
_tied_weights_keys = ["lm_head.weight"]
|
783 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
784 |
+
|
785 |
+
def __init__(self, config):
|
786 |
+
super().__init__(config)
|
787 |
+
self.model = Qwen2Model(config)
|
788 |
+
self.vocab_size = config.vocab_size
|
789 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
790 |
+
|
791 |
+
self.mtp_projs = nn.ModuleList(
|
792 |
+
[nn.Linear(2 * config.hidden_size, config.hidden_size, bias=False) for _ in range(self.config.num_nextn_predict_layers)]
|
793 |
+
)
|
794 |
+
|
795 |
+
self.mtp_embed_norms = nn.ModuleList([Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) for _ in range(self.config.num_nextn_predict_layers)])
|
796 |
+
self.mtp_hidden_norms = nn.ModuleList([Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) for _ in range(self.config.num_nextn_predict_layers)])
|
797 |
+
|
798 |
+
# Initialize weights and apply final processing
|
799 |
+
self.post_init()
|
800 |
+
|
801 |
+
def get_input_embeddings(self):
|
802 |
+
return self.model.embed_tokens
|
803 |
+
|
804 |
+
def set_input_embeddings(self, value):
|
805 |
+
self.model.embed_tokens = value
|
806 |
+
|
807 |
+
def get_output_embeddings(self):
|
808 |
+
return self.lm_head
|
809 |
+
|
810 |
+
def set_output_embeddings(self, new_embeddings):
|
811 |
+
self.lm_head = new_embeddings
|
812 |
+
|
813 |
+
def set_decoder(self, decoder):
|
814 |
+
self.model = decoder
|
815 |
+
|
816 |
+
def get_decoder(self):
|
817 |
+
return self.model
|
818 |
+
|
819 |
+
def mtp_forward(
|
820 |
+
self,
|
821 |
+
mtp_idx,
|
822 |
+
input_ids: torch.LongTensor = None,
|
823 |
+
hidden_states: torch.Tensor = None,
|
824 |
+
attention_mask: Optional[torch.Tensor] = None,
|
825 |
+
position_ids: Optional[torch.LongTensor] = None,
|
826 |
+
past_key_values: Optional[Cache] = None,
|
827 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
828 |
+
labels: Optional[torch.LongTensor] = None,
|
829 |
+
kl_labels: Optional[torch.Tensor] = None,
|
830 |
+
use_cache: Optional[bool] = None,
|
831 |
+
output_attentions: Optional[bool] = None,
|
832 |
+
output_hidden_states: Optional[bool] = None,
|
833 |
+
return_dict: Optional[bool] = None,
|
834 |
+
cache_position: Optional[torch.LongTensor] = None,
|
835 |
+
num_logits_to_keep: int = 0,
|
836 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
837 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
838 |
+
|
839 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
840 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
841 |
+
|
842 |
+
if inputs_embeds is None:
|
843 |
+
inputs_embeds = self.model.embed_tokens(input_ids)
|
844 |
+
# inputs_embeds = inputs_embeds.to(hidden_states.device)
|
845 |
+
|
846 |
+
inputs_embeds = torch.cat(
|
847 |
+
(
|
848 |
+
self.mtp_embed_norms[mtp_idx](inputs_embeds),
|
849 |
+
self.mtp_hidden_norms[mtp_idx](hidden_states),
|
850 |
+
),
|
851 |
+
dim=-1,
|
852 |
+
)
|
853 |
+
|
854 |
+
inputs_embeds = self.mtp_projs[mtp_idx](inputs_embeds)
|
855 |
+
|
856 |
+
outputs = self.model(
|
857 |
+
input_ids=None,
|
858 |
+
attention_mask=attention_mask,
|
859 |
+
position_ids=position_ids,
|
860 |
+
past_key_values=past_key_values,
|
861 |
+
inputs_embeds=inputs_embeds,
|
862 |
+
use_cache=use_cache,
|
863 |
+
output_attentions=output_attentions,
|
864 |
+
output_hidden_states=output_hidden_states,
|
865 |
+
return_dict=return_dict,
|
866 |
+
cache_position=cache_position,
|
867 |
+
layer_idxs=[self.config.num_hidden_layers - self.config.num_nextn_predict_layers + mtp_idx],
|
868 |
+
**kwargs,
|
869 |
+
)
|
870 |
+
|
871 |
+
hidden_states = outputs[0]
|
872 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
873 |
+
|
874 |
+
if labels is not None:
|
875 |
+
loss = []
|
876 |
+
# ce_loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
877 |
+
ce_loss = ForCausalLMLoss(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
878 |
+
|
879 |
+
loss += [ce_loss]
|
880 |
+
|
881 |
+
if False:
|
882 |
+
kl_logits = logits.contiguous()
|
883 |
+
kl_labels = kl_labels.contiguous()
|
884 |
+
kl_loss = compute_kl_loss(kl_logits, kl_labels)
|
885 |
+
|
886 |
+
kl_loss_weight = 1
|
887 |
+
loss += [kl_loss_weight * kl_loss]
|
888 |
+
|
889 |
+
if self.training and torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
|
890 |
+
with torch.no_grad():
|
891 |
+
logger.info(f"\tMTP {mtp_idx=} {loss=}")
|
892 |
+
else:
|
893 |
+
loss = None
|
894 |
+
|
895 |
+
return outputs, logits, loss
|
896 |
+
|
897 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
898 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
899 |
+
def forward(
|
900 |
+
self,
|
901 |
+
input_ids: torch.LongTensor = None,
|
902 |
+
attention_mask: Optional[torch.Tensor] = None,
|
903 |
+
position_ids: Optional[torch.LongTensor] = None,
|
904 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
905 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
906 |
+
labels: Optional[torch.LongTensor] = None,
|
907 |
+
use_cache: Optional[bool] = None,
|
908 |
+
output_attentions: Optional[bool] = None,
|
909 |
+
output_hidden_states: Optional[bool] = None,
|
910 |
+
return_dict: Optional[bool] = None,
|
911 |
+
cache_position: Optional[torch.LongTensor] = None,
|
912 |
+
num_logits_to_keep: int = 0,
|
913 |
+
**kwargs: Unpack[KwargsForCausalLM],
|
914 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
915 |
+
r"""
|
916 |
+
Args:
|
917 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
918 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
919 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
920 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
921 |
+
|
922 |
+
num_logits_to_keep (`int`, *optional*):
|
923 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
924 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
925 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
926 |
+
|
927 |
+
Returns:
|
928 |
+
|
929 |
+
Example:
|
930 |
+
|
931 |
+
```python
|
932 |
+
>>> from transformers import AutoTokenizer, Qwen2ForCausalLM
|
933 |
+
|
934 |
+
>>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
935 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
|
936 |
+
|
937 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
938 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
939 |
+
|
940 |
+
>>> # Generate
|
941 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
942 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
943 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
944 |
+
```"""
|
945 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
946 |
+
output_hidden_states = (
|
947 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
948 |
+
)
|
949 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
950 |
+
|
951 |
+
# ===============================================================================================
|
952 |
+
if not self.training:
|
953 |
+
if input_ids is not None:
|
954 |
+
num_input_tokens = input_ids.size(1)
|
955 |
+
if inputs_embeds is not None:
|
956 |
+
num_input_tokens = inputs_embeds.size(1)
|
957 |
+
|
958 |
+
if use_cache:
|
959 |
+
if self.input_ids is None and self.inputs_embeds is None:
|
960 |
+
if input_ids is not None:
|
961 |
+
self.input_ids = input_ids
|
962 |
+
if inputs_embeds is not None:
|
963 |
+
self.inputs_embeds = inputs_embeds
|
964 |
+
if position_ids is not None:
|
965 |
+
self.position_ids = position_ids
|
966 |
+
|
967 |
+
else:
|
968 |
+
if input_ids is not None:
|
969 |
+
self.input_ids = torch.cat([self.input_ids, input_ids], dim=1)
|
970 |
+
if inputs_embeds is not None:
|
971 |
+
self.inputs_embeds = torch.cat([self.inputs_embeds, inputs_embeds], dim=1)
|
972 |
+
if position_ids is not None:
|
973 |
+
self.position_ids = torch.cat([self.position_ids, position_ids], dim=1)
|
974 |
+
|
975 |
+
else:
|
976 |
+
self.input_ids = input_ids
|
977 |
+
self.inputs_embeds = inputs_embeds
|
978 |
+
self.position_ids = position_ids
|
979 |
+
|
980 |
+
self.attention_mask = attention_mask
|
981 |
+
|
982 |
+
if self.num_prefill_tokens < 0:
|
983 |
+
self.num_prefill_tokens = self.input_ids.size(1)
|
984 |
+
num_decode_tokens = self.input_ids.size(1) - self.num_prefill_tokens
|
985 |
+
|
986 |
+
if self.mtp_inference_mode[num_decode_tokens] == "M":
|
987 |
+
self.mtp_idx = -1
|
988 |
+
elif self.mtp_inference_mode[num_decode_tokens] == "m":
|
989 |
+
if self.mtp_inference_mode[num_decode_tokens - 1] == "M":
|
990 |
+
self.mtp_idx = 0
|
991 |
+
else:
|
992 |
+
pass
|
993 |
+
|
994 |
+
# if True:
|
995 |
+
if False:
|
996 |
+
print("=" * 100)
|
997 |
+
print(f"{self.mtp_idx=}")
|
998 |
+
print(f"{self.num_prefill_tokens=}")
|
999 |
+
print(f"{num_decode_tokens=}")
|
1000 |
+
print(f"{self.mtp_inference_mode=}")
|
1001 |
+
if self.input_ids is not None:
|
1002 |
+
print(f"{self.input_ids.size()=}")
|
1003 |
+
if self.inputs_embeds is not None:
|
1004 |
+
print(f"{self.inputs_embeds.size()=}")
|
1005 |
+
if self.hidden_states[self.mtp_idx] is not None:
|
1006 |
+
print(f"{self.hidden_states[self.mtp_idx].size()=}")
|
1007 |
+
|
1008 |
+
|
1009 |
+
if self.mtp_idx > -1 and self.mtp_idx < self.config.num_nextn_predict_layers and num_input_tokens == 1:
|
1010 |
+
layer_idx = self.config.num_hidden_layers - self.config.num_nextn_predict_layers + self.mtp_idx
|
1011 |
+
|
1012 |
+
if use_cache:
|
1013 |
+
if len(past_key_values.key_cache) > layer_idx:
|
1014 |
+
num_seen_tokens = past_key_values.key_cache[layer_idx].size(2)
|
1015 |
+
else:
|
1016 |
+
num_seen_tokens = 0
|
1017 |
+
else:
|
1018 |
+
num_seen_tokens = 0
|
1019 |
+
|
1020 |
+
hidden_states = self.hidden_states[self.mtp_idx][:, num_seen_tokens:, :]
|
1021 |
+
|
1022 |
+
if self.input_ids is not None:
|
1023 |
+
input_ids = self.input_ids[:, num_seen_tokens + self.mtp_idx + 1:]
|
1024 |
+
if self.inputs_embeds is not None:
|
1025 |
+
inputs_embeds = self.inputs_embeds[:, num_seen_tokens + self.mtp_idx + 1:, :]
|
1026 |
+
if self.position_ids is not None:
|
1027 |
+
position_ids = self.position_ids[:, num_seen_tokens + self.mtp_idx + 1:]
|
1028 |
+
attention_mask = self.attention_mask[:, num_seen_tokens + self.mtp_idx + 1:]
|
1029 |
+
|
1030 |
+
if False:
|
1031 |
+
# if True:
|
1032 |
+
print("=" * 100)
|
1033 |
+
print(f"{self.mtp_idx=}")
|
1034 |
+
print(f"{layer_idx=}")
|
1035 |
+
if input_ids is not None:
|
1036 |
+
print(f"{input_ids.size()=} {input_ids=}")
|
1037 |
+
if inputs_embeds is not None:
|
1038 |
+
print(f"{inputs_embeds.size()=} {inputs_embeds=}")
|
1039 |
+
print(f"{hidden_states.size()=} {hidden_states=}")
|
1040 |
+
if attention_mask is not None:
|
1041 |
+
print(f"{attention_mask.size()=} {attention_mask=}")
|
1042 |
+
if position_ids is not None:
|
1043 |
+
print(f"{position_ids.size()=} {position_ids=}")
|
1044 |
+
if use_cache and len(past_key_values.key_cache) > layer_idx:
|
1045 |
+
print(f"{past_key_values.key_cache[layer_idx].size()=}")
|
1046 |
+
print(f"{use_cache=}")
|
1047 |
+
print(f"{num_logits_to_keep=}")
|
1048 |
+
print(f"{output_attentions=}")
|
1049 |
+
print(f"{output_hidden_states=}")
|
1050 |
+
print(f"{cache_position=}")
|
1051 |
+
|
1052 |
+
mtp_outputs, logits, _ = self.mtp_forward(
|
1053 |
+
self.mtp_idx,
|
1054 |
+
input_ids=input_ids,
|
1055 |
+
hidden_states=hidden_states,
|
1056 |
+
attention_mask=attention_mask,
|
1057 |
+
position_ids=position_ids,
|
1058 |
+
past_key_values=past_key_values,
|
1059 |
+
inputs_embeds=inputs_embeds,
|
1060 |
+
labels=None,
|
1061 |
+
kl_labels=None,
|
1062 |
+
use_cache=use_cache,
|
1063 |
+
output_attentions=output_attentions,
|
1064 |
+
output_hidden_states=output_hidden_states,
|
1065 |
+
return_dict=return_dict,
|
1066 |
+
cache_position=cache_position,
|
1067 |
+
num_logits_to_keep=num_logits_to_keep,
|
1068 |
+
**kwargs,
|
1069 |
+
)
|
1070 |
+
hidden_states = mtp_outputs.last_hidden_state
|
1071 |
+
|
1072 |
+
self.mtp_idx += 1
|
1073 |
+
if use_cache:
|
1074 |
+
if self.hidden_states[self.mtp_idx] is None:
|
1075 |
+
self.hidden_states[self.mtp_idx] = hidden_states
|
1076 |
+
else:
|
1077 |
+
self.hidden_states[self.mtp_idx] = torch.cat([self.hidden_states[self.mtp_idx], hidden_states], dim=1)
|
1078 |
+
|
1079 |
+
else:
|
1080 |
+
self.hidden_states[self.mtp_idx] = hidden_states
|
1081 |
+
|
1082 |
+
return CausalLMOutputWithPast(
|
1083 |
+
loss=None,
|
1084 |
+
logits=logits,
|
1085 |
+
past_key_values=past_key_values,
|
1086 |
+
hidden_states=mtp_outputs.hidden_states,
|
1087 |
+
attentions=mtp_outputs.attentions,
|
1088 |
+
)
|
1089 |
+
|
1090 |
+
if use_cache and past_key_values is not None:
|
1091 |
+
if len(past_key_values.key_cache) > 0:
|
1092 |
+
# print(f"{past_key_values.key_cache[0].size()=}")
|
1093 |
+
num_seen_tokens = past_key_values.key_cache[0].size(2)
|
1094 |
+
else:
|
1095 |
+
num_seen_tokens = 0
|
1096 |
+
else:
|
1097 |
+
num_seen_tokens = 0
|
1098 |
+
|
1099 |
+
if self.input_ids is not None:
|
1100 |
+
input_ids = self.input_ids[:, num_seen_tokens:]
|
1101 |
+
if self.inputs_embeds is not None:
|
1102 |
+
inputs_embeds = self.inputs_embeds[:, num_seen_tokens:, :]
|
1103 |
+
if self.position_ids is not None:
|
1104 |
+
position_ids = self.position_ids[:, num_seen_tokens:]
|
1105 |
+
attention_mask = attention_mask
|
1106 |
+
|
1107 |
+
# ===============================================================================================
|
1108 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1109 |
+
outputs = self.model(
|
1110 |
+
input_ids=input_ids,
|
1111 |
+
attention_mask=attention_mask,
|
1112 |
+
position_ids=position_ids,
|
1113 |
+
past_key_values=past_key_values,
|
1114 |
+
inputs_embeds=inputs_embeds,
|
1115 |
+
use_cache=use_cache,
|
1116 |
+
output_attentions=output_attentions,
|
1117 |
+
output_hidden_states=output_hidden_states,
|
1118 |
+
return_dict=return_dict,
|
1119 |
+
cache_position=cache_position,
|
1120 |
+
layer_idxs=list(range(self.config.num_hidden_layers - self.config.num_nextn_predict_layers)),
|
1121 |
+
**kwargs,
|
1122 |
+
)
|
1123 |
+
|
1124 |
+
hidden_states = outputs[0]
|
1125 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
1126 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
1127 |
+
|
1128 |
+
loss = None
|
1129 |
+
if labels is not None:
|
1130 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
1131 |
+
# loss = ForCausalLMLoss(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
1132 |
+
if self.training and torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
|
1133 |
+
with torch.no_grad():
|
1134 |
+
logger.info(f"STP {loss=}")
|
1135 |
+
|
1136 |
+
# ===============================================================================================
|
1137 |
+
if labels is not None and self.config.num_nextn_predict_layers > 0:
|
1138 |
+
|
1139 |
+
if self.lm_head.weight.requires_grad:
|
1140 |
+
if inputs_embeds is None:
|
1141 |
+
inputs_embeds = self.model.embed_tokens(input_ids)
|
1142 |
+
|
1143 |
+
inputs_embeds = inputs_embeds
|
1144 |
+
hidden_states = hidden_states
|
1145 |
+
kl_labels = logits
|
1146 |
+
|
1147 |
+
else:
|
1148 |
+
with torch.no_grad():
|
1149 |
+
if inputs_embeds is None:
|
1150 |
+
inputs_embeds = self.model.embed_tokens(input_ids)
|
1151 |
+
|
1152 |
+
inputs_embeds = inputs_embeds.detach()
|
1153 |
+
hidden_states = hidden_states.detach()
|
1154 |
+
kl_labels = logits.detach()
|
1155 |
+
|
1156 |
+
if self.lm_head.weight.requires_grad:
|
1157 |
+
pass
|
1158 |
+
else:
|
1159 |
+
loss = 0.0
|
1160 |
+
|
1161 |
+
for mtp_idx in range(self.config.num_nextn_predict_layers):
|
1162 |
+
|
1163 |
+
# SFT with data packing
|
1164 |
+
if True:
|
1165 |
+
mtp_mask = position_ids > mtp_idx
|
1166 |
+
# input_ids = input_ids[mtp_mask].unsqueeze(0)
|
1167 |
+
inputs_embeds = inputs_embeds[mtp_mask].unsqueeze(0)
|
1168 |
+
if attention_mask is not None:
|
1169 |
+
attention_mask = attention_mask[mtp_mask].unsqueeze(0)
|
1170 |
+
if position_ids is not None:
|
1171 |
+
position_ids = position_ids[mtp_mask].unsqueeze(0)
|
1172 |
+
labels = labels[mtp_mask].unsqueeze(0)
|
1173 |
+
kl_labels = kl_labels[mtp_mask].unsqueeze(0)
|
1174 |
+
|
1175 |
+
mtp_mask = torch.cat((mtp_mask[:, 1:], mtp_mask[:, :1]), dim=1)
|
1176 |
+
hidden_states = hidden_states[mtp_mask].unsqueeze(0)
|
1177 |
+
|
1178 |
+
cu_seq_lens_q, cu_seq_lens_k, max_length_q, max_length_k = prepare_fa2_from_position_ids_for_mtp(position_ids, mtp_idx)
|
1179 |
+
# kwargs["cu_seq_lens_q"] = cu_seq_lens_q
|
1180 |
+
# kwargs["cu_seq_lens_k"] = cu_seq_lens_k
|
1181 |
+
# kwargs["max_length_q"] = max_length_q
|
1182 |
+
# kwargs["max_length_k"] = max_length_k
|
1183 |
+
|
1184 |
+
# print(f"{cu_seq_lens_q}")
|
1185 |
+
# print(f"{cu_seq_lens_k}")
|
1186 |
+
# print(f"{max_length_q}")
|
1187 |
+
# print(f"{max_length_k}")
|
1188 |
+
|
1189 |
+
mtp_outputs, _, mtp_loss = self.mtp_forward(
|
1190 |
+
mtp_idx,
|
1191 |
+
input_ids=None,
|
1192 |
+
hidden_states=hidden_states,
|
1193 |
+
attention_mask=attention_mask,
|
1194 |
+
position_ids=position_ids,
|
1195 |
+
past_key_values=past_key_values,
|
1196 |
+
inputs_embeds=inputs_embeds,
|
1197 |
+
labels=labels,
|
1198 |
+
kl_labels=kl_labels,
|
1199 |
+
use_cache=use_cache,
|
1200 |
+
output_attentions=output_attentions,
|
1201 |
+
output_hidden_states=output_hidden_states,
|
1202 |
+
return_dict=return_dict,
|
1203 |
+
cache_position=cache_position,
|
1204 |
+
num_logits_to_keep=num_logits_to_keep,
|
1205 |
+
cu_seq_lens_q=cu_seq_lens_q,
|
1206 |
+
cu_seq_lens_k=cu_seq_lens_k,
|
1207 |
+
max_length_q=max_length_q,
|
1208 |
+
max_length_k=max_length_k,
|
1209 |
+
**kwargs,
|
1210 |
+
)
|
1211 |
+
|
1212 |
+
loss += sum(mtp_loss) / self.config.num_nextn_predict_layers * self.config.mtp_loss_weight
|
1213 |
+
|
1214 |
+
hidden_states = mtp_outputs.last_hidden_state
|
1215 |
+
|
1216 |
+
if not self.training:
|
1217 |
+
self.mtp_idx = 0
|
1218 |
+
|
1219 |
+
if use_cache:
|
1220 |
+
if self.hidden_states[self.mtp_idx] is None:
|
1221 |
+
self.hidden_states[self.mtp_idx] = hidden_states
|
1222 |
+
|
1223 |
+
else:
|
1224 |
+
self.hidden_states[self.mtp_idx] = torch.cat([self.hidden_states[self.mtp_idx], hidden_states], dim=1)
|
1225 |
+
|
1226 |
+
else:
|
1227 |
+
self.hidden_states[self.mtp_idx] = hidden_states
|
1228 |
+
|
1229 |
+
# ===============================================================================================
|
1230 |
+
|
1231 |
+
if not return_dict:
|
1232 |
+
output = (logits,) + outputs[1:]
|
1233 |
+
return (loss,) + output if loss is not None else output
|
1234 |
+
|
1235 |
+
return CausalLMOutputWithPast(
|
1236 |
+
loss=loss,
|
1237 |
+
logits=logits,
|
1238 |
+
past_key_values=outputs.past_key_values,
|
1239 |
+
hidden_states=outputs.hidden_states,
|
1240 |
+
attentions=outputs.attentions,
|
1241 |
+
)
|
1242 |
+
|
1243 |
+
def _prepare_mtp_for_generation(
|
1244 |
+
self,
|
1245 |
+
mtp_inference_mode,
|
1246 |
+
max_new_tokens,
|
1247 |
+
):
|
1248 |
+
|
1249 |
+
self.input_ids = None
|
1250 |
+
self.inputs_embeds = None
|
1251 |
+
self.hidden_states = [None] * (self.config.num_nextn_predict_layers + 1)
|
1252 |
+
self.position_ids = None
|
1253 |
+
self.attention_mask = None
|
1254 |
+
|
1255 |
+
self.mtp_idx = -1
|
1256 |
+
self.num_prefill_tokens = -1
|
1257 |
+
|
1258 |
+
assert isinstance(mtp_inference_mode, list)
|
1259 |
+
assert len(mtp_inference_mode) >= 2
|
1260 |
+
assert len(mtp_inference_mode) % 2 == 0
|
1261 |
+
|
1262 |
+
main_nums = mtp_inference_mode[::2]
|
1263 |
+
mtp_nums = mtp_inference_mode[1::2]
|
1264 |
+
|
1265 |
+
mtp_inference_mode = []
|
1266 |
+
while len(mtp_inference_mode) < max_new_tokens:
|
1267 |
+
|
1268 |
+
if len(mtp_nums) > 1:
|
1269 |
+
mtp_num = mtp_nums.pop(0)
|
1270 |
+
else:
|
1271 |
+
mtp_num = mtp_nums[0]
|
1272 |
+
|
1273 |
+
if len(main_nums) > 1:
|
1274 |
+
main_num = main_nums.pop(0)
|
1275 |
+
else:
|
1276 |
+
main_num = main_nums[0]
|
1277 |
+
|
1278 |
+
mtp_inference_mode += "M" * main_num + "m" * mtp_num
|
1279 |
+
|
1280 |
+
self.mtp_inference_mode = mtp_inference_mode
|
1281 |
+
|
1282 |
+
def _prepare_cache_for_generation(self, *args, **kwargs):
|
1283 |
+
|
1284 |
+
generation_config = args[0]
|
1285 |
+
mtp_inference_mode = getattr(generation_config, "mtp_inference_mode", [1, self.config.num_nextn_predict_layers])
|
1286 |
+
max_new_tokens = generation_config.max_new_tokens
|
1287 |
+
|
1288 |
+
self._prepare_mtp_for_generation(mtp_inference_mode, max_new_tokens)
|
1289 |
+
|
1290 |
+
return super()._prepare_cache_for_generation(*args, **kwargs)
|
1291 |
+
|
1292 |
+
|
1293 |
+
@add_start_docstrings(
|
1294 |
+
"""
|
1295 |
+
The Qwen2 Model transformer with a sequence classification head on top (linear layer).
|
1296 |
+
|
1297 |
+
[`Qwen2ForSequenceClassification`] 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 |
+
QWEN2_START_DOCSTRING,
|
1307 |
+
)
|
1308 |
+
class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
|
1309 |
+
def __init__(self, config):
|
1310 |
+
super().__init__(config)
|
1311 |
+
self.num_labels = config.num_labels
|
1312 |
+
self.model = Qwen2Model(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(QWEN2_INPUTS_DOCSTRING)
|
1325 |
+
def forward(
|
1326 |
+
self,
|
1327 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1328 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1329 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1330 |
+
past_key_values: Optional[Union[Cache, 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 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1372 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1373 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1374 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1375 |
+
else:
|
1376 |
+
sequence_lengths = -1
|
1377 |
+
|
1378 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1379 |
+
|
1380 |
+
loss = None
|
1381 |
+
if labels is not None:
|
1382 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
1383 |
+
|
1384 |
+
if not return_dict:
|
1385 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1386 |
+
return ((loss,) + output) if loss is not None else output
|
1387 |
+
|
1388 |
+
return SequenceClassifierOutputWithPast(
|
1389 |
+
loss=loss,
|
1390 |
+
logits=pooled_logits,
|
1391 |
+
past_key_values=transformer_outputs.past_key_values,
|
1392 |
+
hidden_states=transformer_outputs.hidden_states,
|
1393 |
+
attentions=transformer_outputs.attentions,
|
1394 |
+
)
|
1395 |
+
|
1396 |
+
|
1397 |
+
@add_start_docstrings(
|
1398 |
+
"""
|
1399 |
+
The Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
1400 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
1401 |
+
""",
|
1402 |
+
QWEN2_START_DOCSTRING,
|
1403 |
+
)
|
1404 |
+
class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
|
1405 |
+
def __init__(self, config):
|
1406 |
+
super().__init__(config)
|
1407 |
+
self.num_labels = config.num_labels
|
1408 |
+
self.model = Qwen2Model(config)
|
1409 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
1410 |
+
classifier_dropout = config.classifier_dropout
|
1411 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
1412 |
+
classifier_dropout = config.hidden_dropout
|
1413 |
+
else:
|
1414 |
+
classifier_dropout = 0.1
|
1415 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1416 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
1417 |
+
|
1418 |
+
# Initialize weights and apply final processing
|
1419 |
+
self.post_init()
|
1420 |
+
|
1421 |
+
def get_input_embeddings(self):
|
1422 |
+
return self.model.embed_tokens
|
1423 |
+
|
1424 |
+
def set_input_embeddings(self, value):
|
1425 |
+
self.model.embed_tokens = value
|
1426 |
+
|
1427 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1428 |
+
@add_code_sample_docstrings(
|
1429 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1430 |
+
output_type=TokenClassifierOutput,
|
1431 |
+
config_class=_CONFIG_FOR_DOC,
|
1432 |
+
)
|
1433 |
+
def forward(
|
1434 |
+
self,
|
1435 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1436 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1437 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1438 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1439 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1440 |
+
labels: Optional[torch.LongTensor] = None,
|
1441 |
+
use_cache: Optional[bool] = None,
|
1442 |
+
output_attentions: Optional[bool] = None,
|
1443 |
+
output_hidden_states: Optional[bool] = None,
|
1444 |
+
return_dict: Optional[bool] = None,
|
1445 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
1446 |
+
r"""
|
1447 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1448 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1449 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1450 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1451 |
+
"""
|
1452 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1453 |
+
|
1454 |
+
outputs = self.model(
|
1455 |
+
input_ids,
|
1456 |
+
attention_mask=attention_mask,
|
1457 |
+
position_ids=position_ids,
|
1458 |
+
past_key_values=past_key_values,
|
1459 |
+
inputs_embeds=inputs_embeds,
|
1460 |
+
use_cache=use_cache,
|
1461 |
+
output_attentions=output_attentions,
|
1462 |
+
output_hidden_states=output_hidden_states,
|
1463 |
+
return_dict=return_dict,
|
1464 |
+
)
|
1465 |
+
sequence_output = outputs[0]
|
1466 |
+
sequence_output = self.dropout(sequence_output)
|
1467 |
+
logits = self.score(sequence_output)
|
1468 |
+
|
1469 |
+
loss = None
|
1470 |
+
if labels is not None:
|
1471 |
+
loss = self.loss_function(logits, labels, self.config)
|
1472 |
+
|
1473 |
+
if not return_dict:
|
1474 |
+
output = (logits,) + outputs[2:]
|
1475 |
+
return ((loss,) + output) if loss is not None else output
|
1476 |
+
|
1477 |
+
return TokenClassifierOutput(
|
1478 |
+
loss=loss,
|
1479 |
+
logits=logits,
|
1480 |
+
hidden_states=outputs.hidden_states,
|
1481 |
+
attentions=outputs.attentions,
|
1482 |
+
)
|
1483 |
+
|
1484 |
+
|
1485 |
+
@add_start_docstrings(
|
1486 |
+
"""
|
1487 |
+
The Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
|
1488 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1489 |
+
""",
|
1490 |
+
QWEN2_START_DOCSTRING,
|
1491 |
+
)
|
1492 |
+
class Qwen2ForQuestionAnswering(Qwen2PreTrainedModel):
|
1493 |
+
base_model_prefix = "transformer"
|
1494 |
+
|
1495 |
+
def __init__(self, config):
|
1496 |
+
super().__init__(config)
|
1497 |
+
self.transformer = Qwen2Model(config)
|
1498 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1499 |
+
|
1500 |
+
# Initialize weights and apply final processing
|
1501 |
+
self.post_init()
|
1502 |
+
|
1503 |
+
def get_input_embeddings(self):
|
1504 |
+
return self.transformer.embed_tokens
|
1505 |
+
|
1506 |
+
def set_input_embeddings(self, value):
|
1507 |
+
self.transformer.embed_tokens = value
|
1508 |
+
|
1509 |
+
@add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
|
1510 |
+
def forward(
|
1511 |
+
self,
|
1512 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1513 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1514 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1515 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1516 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1517 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1518 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1519 |
+
output_attentions: Optional[bool] = None,
|
1520 |
+
output_hidden_states: Optional[bool] = None,
|
1521 |
+
return_dict: Optional[bool] = None,
|
1522 |
+
**kwargs,
|
1523 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1524 |
+
r"""
|
1525 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1526 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1527 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1528 |
+
are not taken into account for computing the loss.
|
1529 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1530 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1531 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1532 |
+
are not taken into account for computing the loss.
|
1533 |
+
"""
|
1534 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1535 |
+
|
1536 |
+
outputs = self.transformer(
|
1537 |
+
input_ids,
|
1538 |
+
attention_mask=attention_mask,
|
1539 |
+
position_ids=position_ids,
|
1540 |
+
past_key_values=past_key_values,
|
1541 |
+
inputs_embeds=inputs_embeds,
|
1542 |
+
output_attentions=output_attentions,
|
1543 |
+
output_hidden_states=output_hidden_states,
|
1544 |
+
return_dict=return_dict,
|
1545 |
+
)
|
1546 |
+
|
1547 |
+
sequence_output = outputs[0]
|
1548 |
+
|
1549 |
+
logits = self.qa_outputs(sequence_output)
|
1550 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1551 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1552 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1553 |
+
|
1554 |
+
loss = None
|
1555 |
+
if start_positions is not None and end_positions is not None:
|
1556 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
1557 |
+
|
1558 |
+
if not return_dict:
|
1559 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1560 |
+
return ((loss,) + output) if loss is not None else output
|
1561 |
+
|
1562 |
+
return QuestionAnsweringModelOutput(
|
1563 |
+
loss=loss,
|
1564 |
+
start_logits=start_logits,
|
1565 |
+
end_logits=end_logits,
|
1566 |
+
hidden_states=outputs.hidden_states,
|
1567 |
+
attentions=outputs.attentions,
|
1568 |
+
)
|
1569 |
+
|
1570 |
+
|
1571 |
+
def prepare_fa2_from_position_ids_for_mtp(position_ids, mtp_idx):
|
1572 |
+
position_ids = position_ids.flatten()
|
1573 |
+
indices_q = torch.arange(position_ids.size(0), device=position_ids.device, dtype=torch.int32)
|
1574 |
+
|
1575 |
+
cu_seq_lens = torch.cat(
|
1576 |
+
(
|
1577 |
+
indices_q[position_ids == mtp_idx + 1],
|
1578 |
+
torch.tensor(position_ids.size(), device=position_ids.device, dtype=torch.int32),
|
1579 |
+
)
|
1580 |
+
)
|
1581 |
+
|
1582 |
+
max_length = position_ids.max() + 1 - 1 - mtp_idx
|
1583 |
+
|
1584 |
+
return cu_seq_lens, cu_seq_lens, max_length, max_length
|
special_tokens_map.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<|im_start|>",
|
4 |
+
"<|im_end|>",
|
5 |
+
"<|object_ref_start|>",
|
6 |
+
"<|object_ref_end|>",
|
7 |
+
"<|box_start|>",
|
8 |
+
"<|box_end|>",
|
9 |
+
"<|quad_start|>",
|
10 |
+
"<|quad_end|>",
|
11 |
+
"<|vision_start|>",
|
12 |
+
"<|vision_end|>",
|
13 |
+
"<|vision_pad|>",
|
14 |
+
"<|image_pad|>",
|
15 |
+
"<|video_pad|>"
|
16 |
+
],
|
17 |
+
"eos_token": {
|
18 |
+
"content": "<|im_end|>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": false,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
},
|
24 |
+
"pad_token": {
|
25 |
+
"content": "<|endoftext|>",
|
26 |
+
"lstrip": false,
|
27 |
+
"normalized": false,
|
28 |
+
"rstrip": false,
|
29 |
+
"single_word": false
|
30 |
+
}
|
31 |
+
}
|
tokenization_qwen2.py
ADDED
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""Tokenization classes for Qwen2."""
|
16 |
+
|
17 |
+
import json
|
18 |
+
import os
|
19 |
+
import unicodedata
|
20 |
+
from functools import lru_cache
|
21 |
+
from typing import Optional, Tuple
|
22 |
+
|
23 |
+
import regex as re
|
24 |
+
|
25 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
26 |
+
from transformers.utils import logging
|
27 |
+
|
28 |
+
|
29 |
+
logger = logging.get_logger(__name__)
|
30 |
+
|
31 |
+
VOCAB_FILES_NAMES = {
|
32 |
+
"vocab_file": "vocab.json",
|
33 |
+
"merges_file": "merges.txt",
|
34 |
+
}
|
35 |
+
|
36 |
+
|
37 |
+
MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
|
38 |
+
|
39 |
+
PRETOKENIZE_REGEX = 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+"""
|
40 |
+
|
41 |
+
|
42 |
+
@lru_cache()
|
43 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
|
44 |
+
def bytes_to_unicode():
|
45 |
+
"""
|
46 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
47 |
+
characters the bpe code barfs on.
|
48 |
+
|
49 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
50 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
51 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
52 |
+
tables between utf-8 bytes and unicode strings.
|
53 |
+
"""
|
54 |
+
bs = (
|
55 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
56 |
+
)
|
57 |
+
cs = bs[:]
|
58 |
+
n = 0
|
59 |
+
for b in range(2**8):
|
60 |
+
if b not in bs:
|
61 |
+
bs.append(b)
|
62 |
+
cs.append(2**8 + n)
|
63 |
+
n += 1
|
64 |
+
cs = [chr(n) for n in cs]
|
65 |
+
return dict(zip(bs, cs))
|
66 |
+
|
67 |
+
|
68 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
|
69 |
+
def get_pairs(word):
|
70 |
+
"""
|
71 |
+
Return set of symbol pairs in a word.
|
72 |
+
|
73 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
74 |
+
"""
|
75 |
+
pairs = set()
|
76 |
+
prev_char = word[0]
|
77 |
+
for char in word[1:]:
|
78 |
+
pairs.add((prev_char, char))
|
79 |
+
prev_char = char
|
80 |
+
return pairs
|
81 |
+
|
82 |
+
|
83 |
+
class Qwen2Tokenizer(PreTrainedTokenizer):
|
84 |
+
"""
|
85 |
+
Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
|
86 |
+
|
87 |
+
Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
|
88 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
89 |
+
|
90 |
+
```python
|
91 |
+
>>> from transformers import Qwen2Tokenizer
|
92 |
+
|
93 |
+
>>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
|
94 |
+
>>> tokenizer("Hello world")["input_ids"]
|
95 |
+
[9707, 1879]
|
96 |
+
|
97 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
98 |
+
[21927, 1879]
|
99 |
+
```
|
100 |
+
This is expected.
|
101 |
+
|
102 |
+
You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
|
103 |
+
|
104 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
105 |
+
this superclass for more information regarding those methods.
|
106 |
+
|
107 |
+
Args:
|
108 |
+
vocab_file (`str`):
|
109 |
+
Path to the vocabulary file.
|
110 |
+
merges_file (`str`):
|
111 |
+
Path to the merges file.
|
112 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
113 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
114 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
115 |
+
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
116 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
117 |
+
token instead.
|
118 |
+
bos_token (`str`, *optional*):
|
119 |
+
The beginning of sequence token. Not applicable for this tokenizer.
|
120 |
+
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
121 |
+
The end of sequence token.
|
122 |
+
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
123 |
+
The token used for padding, for example when batching sequences of different lengths.
|
124 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
125 |
+
Whether or not the model should cleanup the spaces that were added when splitting the input text during the
|
126 |
+
tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
|
127 |
+
split_special_tokens (`bool`, *optional*, defaults to `False`):
|
128 |
+
Whether or not the special tokens should be split during the tokenization process. The default behavior is
|
129 |
+
to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
|
130 |
+
['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
|
131 |
+
'|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
|
132 |
+
"""
|
133 |
+
|
134 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
135 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
136 |
+
max_model_input_sizes = MAX_MODEL_INPUT_SIZES
|
137 |
+
model_input_names = ["input_ids", "attention_mask"]
|
138 |
+
|
139 |
+
def __init__(
|
140 |
+
self,
|
141 |
+
vocab_file,
|
142 |
+
merges_file,
|
143 |
+
errors="replace",
|
144 |
+
unk_token="<|endoftext|>",
|
145 |
+
bos_token=None,
|
146 |
+
eos_token="<|endoftext|>",
|
147 |
+
pad_token="<|endoftext|>",
|
148 |
+
clean_up_tokenization_spaces=False,
|
149 |
+
split_special_tokens=False,
|
150 |
+
**kwargs,
|
151 |
+
):
|
152 |
+
# Qwen vocab does not contain control tokens; added tokens need to be special
|
153 |
+
bos_token = (
|
154 |
+
AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
155 |
+
if isinstance(bos_token, str)
|
156 |
+
else bos_token
|
157 |
+
)
|
158 |
+
eos_token = (
|
159 |
+
AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
160 |
+
if isinstance(eos_token, str)
|
161 |
+
else eos_token
|
162 |
+
)
|
163 |
+
unk_token = (
|
164 |
+
AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
165 |
+
if isinstance(unk_token, str)
|
166 |
+
else unk_token
|
167 |
+
)
|
168 |
+
pad_token = (
|
169 |
+
AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
170 |
+
if isinstance(pad_token, str)
|
171 |
+
else pad_token
|
172 |
+
)
|
173 |
+
|
174 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
175 |
+
self.encoder = json.load(vocab_handle)
|
176 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
177 |
+
self.errors = errors # how to handle errors in decoding
|
178 |
+
self.byte_encoder = bytes_to_unicode()
|
179 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
180 |
+
bpe_merges = []
|
181 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
182 |
+
for line in merges_handle:
|
183 |
+
line = line.strip()
|
184 |
+
if not line or line.startswith("#"):
|
185 |
+
continue
|
186 |
+
bpe_merges.append(tuple(line.split()))
|
187 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
188 |
+
# NOTE: the cache can grow without bound and will get really large for long running processes
|
189 |
+
# (esp. for texts of language that do not use space between word, e.g. Chinese); technically
|
190 |
+
# not a memory leak but appears as one.
|
191 |
+
# GPT2Tokenizer has the same problem, so let's be consistent.
|
192 |
+
self.cache = {}
|
193 |
+
|
194 |
+
self.pat = re.compile(PRETOKENIZE_REGEX)
|
195 |
+
|
196 |
+
if kwargs.get("add_prefix_space", False):
|
197 |
+
logger.warning_once(
|
198 |
+
f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
|
199 |
+
)
|
200 |
+
|
201 |
+
super().__init__(
|
202 |
+
errors=errors,
|
203 |
+
bos_token=bos_token,
|
204 |
+
eos_token=eos_token,
|
205 |
+
pad_token=pad_token,
|
206 |
+
unk_token=unk_token,
|
207 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
208 |
+
split_special_tokens=split_special_tokens,
|
209 |
+
**kwargs,
|
210 |
+
)
|
211 |
+
|
212 |
+
@property
|
213 |
+
def vocab_size(self) -> int:
|
214 |
+
return len(self.encoder)
|
215 |
+
|
216 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
|
217 |
+
def get_vocab(self):
|
218 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
219 |
+
|
220 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
|
221 |
+
def bpe(self, token):
|
222 |
+
if token in self.cache:
|
223 |
+
return self.cache[token]
|
224 |
+
word = tuple(token)
|
225 |
+
pairs = get_pairs(word)
|
226 |
+
|
227 |
+
if not pairs:
|
228 |
+
return token
|
229 |
+
|
230 |
+
while True:
|
231 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
232 |
+
if bigram not in self.bpe_ranks:
|
233 |
+
break
|
234 |
+
first, second = bigram
|
235 |
+
new_word = []
|
236 |
+
i = 0
|
237 |
+
while i < len(word):
|
238 |
+
try:
|
239 |
+
j = word.index(first, i)
|
240 |
+
except ValueError:
|
241 |
+
new_word.extend(word[i:])
|
242 |
+
break
|
243 |
+
else:
|
244 |
+
new_word.extend(word[i:j])
|
245 |
+
i = j
|
246 |
+
|
247 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
248 |
+
new_word.append(first + second)
|
249 |
+
i += 2
|
250 |
+
else:
|
251 |
+
new_word.append(word[i])
|
252 |
+
i += 1
|
253 |
+
new_word = tuple(new_word)
|
254 |
+
word = new_word
|
255 |
+
if len(word) == 1:
|
256 |
+
break
|
257 |
+
else:
|
258 |
+
pairs = get_pairs(word)
|
259 |
+
word = " ".join(word)
|
260 |
+
self.cache[token] = word
|
261 |
+
return word
|
262 |
+
|
263 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
|
264 |
+
def _tokenize(self, text):
|
265 |
+
"""Tokenize a string."""
|
266 |
+
bpe_tokens = []
|
267 |
+
for token in re.findall(self.pat, text):
|
268 |
+
token = "".join(
|
269 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
270 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
271 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
272 |
+
return bpe_tokens
|
273 |
+
|
274 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
|
275 |
+
def _convert_token_to_id(self, token):
|
276 |
+
"""Converts a token (str) in an id using the vocab."""
|
277 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
278 |
+
|
279 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
|
280 |
+
def _convert_id_to_token(self, index):
|
281 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
282 |
+
return self.decoder.get(index)
|
283 |
+
|
284 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
|
285 |
+
def convert_tokens_to_string(self, tokens):
|
286 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
287 |
+
text = "".join(tokens)
|
288 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
289 |
+
return text
|
290 |
+
|
291 |
+
def decode(
|
292 |
+
self,
|
293 |
+
token_ids,
|
294 |
+
skip_special_tokens: bool = False,
|
295 |
+
clean_up_tokenization_spaces: Optional[bool] = False,
|
296 |
+
spaces_between_special_tokens: bool = False,
|
297 |
+
**kwargs,
|
298 |
+
) -> str:
|
299 |
+
# `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
|
300 |
+
# and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
|
301 |
+
return super().decode(
|
302 |
+
token_ids,
|
303 |
+
skip_special_tokens=skip_special_tokens,
|
304 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
305 |
+
spaces_between_special_tokens=spaces_between_special_tokens,
|
306 |
+
**kwargs,
|
307 |
+
)
|
308 |
+
|
309 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
|
310 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
311 |
+
if not os.path.isdir(save_directory):
|
312 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
313 |
+
return
|
314 |
+
vocab_file = os.path.join(
|
315 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
316 |
+
)
|
317 |
+
merge_file = os.path.join(
|
318 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
319 |
+
)
|
320 |
+
|
321 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
322 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
323 |
+
|
324 |
+
index = 0
|
325 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
326 |
+
writer.write("#version: 0.2\n")
|
327 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
328 |
+
if index != token_index:
|
329 |
+
logger.warning(
|
330 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
331 |
+
" Please check that the tokenizer is not corrupted!"
|
332 |
+
)
|
333 |
+
index = token_index
|
334 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
335 |
+
index += 1
|
336 |
+
|
337 |
+
return vocab_file, merge_file
|
338 |
+
|
339 |
+
def prepare_for_tokenization(self, text, **kwargs):
|
340 |
+
text = unicodedata.normalize("NFC", text)
|
341 |
+
return (text, kwargs)
|
tokenization_qwen2_fast.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""Tokenization classes for Qwen2."""
|
16 |
+
|
17 |
+
from typing import Optional, Tuple
|
18 |
+
|
19 |
+
from transformers.tokenization_utils import AddedToken
|
20 |
+
from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
|
21 |
+
from transformers.utils import logging
|
22 |
+
from .tokenization_qwen2 import Qwen2Tokenizer
|
23 |
+
|
24 |
+
|
25 |
+
logger = logging.get_logger(__name__)
|
26 |
+
|
27 |
+
VOCAB_FILES_NAMES = {
|
28 |
+
"vocab_file": "vocab.json",
|
29 |
+
"merges_file": "merges.txt",
|
30 |
+
"tokenizer_file": "tokenizer.json",
|
31 |
+
}
|
32 |
+
|
33 |
+
|
34 |
+
MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
|
35 |
+
|
36 |
+
|
37 |
+
class Qwen2TokenizerFast(PreTrainedTokenizerFast):
|
38 |
+
"""
|
39 |
+
Construct a "fast" Qwen2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
|
40 |
+
Byte-Pair-Encoding.
|
41 |
+
|
42 |
+
Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
|
43 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
44 |
+
|
45 |
+
```python
|
46 |
+
>>> from transformers import Qwen2TokenizerFast
|
47 |
+
|
48 |
+
>>> tokenizer = Qwen2TokenizerFast.from_pretrained("Qwen/Qwen-tokenizer")
|
49 |
+
>>> tokenizer("Hello world")["input_ids"]
|
50 |
+
[9707, 1879]
|
51 |
+
|
52 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
53 |
+
[21927, 1879]
|
54 |
+
```
|
55 |
+
This is expected.
|
56 |
+
|
57 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
58 |
+
refer to this superclass for more information regarding those methods.
|
59 |
+
|
60 |
+
Args:
|
61 |
+
vocab_file (`str`, *optional*):
|
62 |
+
Path to the vocabulary file.
|
63 |
+
merges_file (`str`, *optional*):
|
64 |
+
Path to the merges file.
|
65 |
+
tokenizer_file (`str`, *optional*):
|
66 |
+
Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
|
67 |
+
contains everything needed to load the tokenizer.
|
68 |
+
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
69 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
70 |
+
token instead. Not applicable to this tokenizer.
|
71 |
+
bos_token (`str`, *optional*):
|
72 |
+
The beginning of sequence token. Not applicable for this tokenizer.
|
73 |
+
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
74 |
+
The end of sequence token.
|
75 |
+
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
76 |
+
The token used for padding, for example when batching sequences of different lengths.
|
77 |
+
"""
|
78 |
+
|
79 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
80 |
+
model_input_names = ["input_ids", "attention_mask"]
|
81 |
+
slow_tokenizer_class = Qwen2Tokenizer
|
82 |
+
|
83 |
+
def __init__(
|
84 |
+
self,
|
85 |
+
vocab_file=None,
|
86 |
+
merges_file=None,
|
87 |
+
tokenizer_file=None,
|
88 |
+
unk_token="<|endoftext|>",
|
89 |
+
bos_token=None,
|
90 |
+
eos_token="<|endoftext|>",
|
91 |
+
pad_token="<|endoftext|>",
|
92 |
+
**kwargs,
|
93 |
+
):
|
94 |
+
# We need to at least pass vocab_file and merges_file to base class
|
95 |
+
# in case a slow tokenizer needs to be initialized; other can be
|
96 |
+
# configured through files.
|
97 |
+
# following GPT2TokenizerFast, also adding unk_token, bos_token, and eos_token
|
98 |
+
|
99 |
+
bos_token = (
|
100 |
+
AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
101 |
+
if isinstance(bos_token, str)
|
102 |
+
else bos_token
|
103 |
+
)
|
104 |
+
eos_token = (
|
105 |
+
AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
106 |
+
if isinstance(eos_token, str)
|
107 |
+
else eos_token
|
108 |
+
)
|
109 |
+
unk_token = (
|
110 |
+
AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
111 |
+
if isinstance(unk_token, str)
|
112 |
+
else unk_token
|
113 |
+
)
|
114 |
+
pad_token = (
|
115 |
+
AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
116 |
+
if isinstance(pad_token, str)
|
117 |
+
else pad_token
|
118 |
+
)
|
119 |
+
|
120 |
+
super().__init__(
|
121 |
+
vocab_file=vocab_file,
|
122 |
+
merges_file=merges_file,
|
123 |
+
tokenizer_file=tokenizer_file,
|
124 |
+
unk_token=unk_token,
|
125 |
+
bos_token=bos_token,
|
126 |
+
eos_token=eos_token,
|
127 |
+
pad_token=pad_token,
|
128 |
+
**kwargs,
|
129 |
+
)
|
130 |
+
|
131 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2_fast.GPT2TokenizerFast.save_vocabulary
|
132 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
133 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
134 |
+
return tuple(files)
|
tokenizer_config.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|