p2o6e100 commited on
Commit
29539a2
·
1 Parent(s): ad29924

init commit

Browse files
added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<|endoftext|>": 106152,
3
+ "<|im_end|>": 106154,
4
+ "<|im_start|>": 106153
5
+ }
config.json ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab_size": 106155,
3
+ "max_position_embeddings": 32768,
4
+ "hidden_size": 2688,
5
+ "intermediate_size": 18944,
6
+ "num_hidden_layers": 28,
7
+ "num_attention_heads": 21,
8
+ "use_sliding_window": false,
9
+ "sliding_window": null,
10
+ "max_window_layers": 28,
11
+ "pruned_layers": [
12
+ 4,
13
+ 5,
14
+ 6,
15
+ 7,
16
+ 8,
17
+ 9,
18
+ 10,
19
+ 11,
20
+ 12,
21
+ 13,
22
+ 14,
23
+ 15,
24
+ 16,
25
+ 17,
26
+ 18,
27
+ 19,
28
+ 20,
29
+ 21,
30
+ 22,
31
+ 23,
32
+ 24
33
+ ],
34
+ "pruned_intermediate_size": 14208,
35
+ "num_key_value_heads": 3,
36
+ "hidden_act": "silu",
37
+ "initializer_range": 0.02,
38
+ "rms_norm_eps": 1e-06,
39
+ "use_cache": true,
40
+ "rope_theta": 1000000.0,
41
+ "attention_dropout": 0.0,
42
+ "return_dict": true,
43
+ "output_hidden_states": false,
44
+ "output_attentions": false,
45
+ "torchscript": false,
46
+ "torch_dtype": "float16",
47
+ "use_bfloat16": false,
48
+ "tf_legacy_loss": false,
49
+ "pruned_heads": {},
50
+ "tie_word_embeddings": false,
51
+ "chunk_size_feed_forward": 0,
52
+ "is_encoder_decoder": false,
53
+ "is_decoder": false,
54
+ "cross_attention_hidden_size": null,
55
+ "add_cross_attention": false,
56
+ "tie_encoder_decoder": false,
57
+ "max_length": 20,
58
+ "min_length": 0,
59
+ "do_sample": false,
60
+ "early_stopping": false,
61
+ "num_beams": 1,
62
+ "num_beam_groups": 1,
63
+ "diversity_penalty": 0.0,
64
+ "temperature": 1.0,
65
+ "top_k": 50,
66
+ "top_p": 1.0,
67
+ "typical_p": 1.0,
68
+ "repetition_penalty": 1.0,
69
+ "length_penalty": 1.0,
70
+ "no_repeat_ngram_size": 0,
71
+ "encoder_no_repeat_ngram_size": 0,
72
+ "bad_words_ids": null,
73
+ "num_return_sequences": 1,
74
+ "output_scores": false,
75
+ "return_dict_in_generate": false,
76
+ "forced_bos_token_id": null,
77
+ "forced_eos_token_id": null,
78
+ "remove_invalid_values": false,
79
+ "exponential_decay_length_penalty": null,
80
+ "suppress_tokens": null,
81
+ "begin_suppress_tokens": null,
82
+ "architectures": [
83
+ "Qwen2ForCausalLM"
84
+ ],
85
+ "finetuning_task": null,
86
+ "id2label": {
87
+ "0": "LABEL_0",
88
+ "1": "LABEL_1"
89
+ },
90
+ "label2id": {
91
+ "LABEL_0": 0,
92
+ "LABEL_1": 1
93
+ },
94
+ "tokenizer_class": null,
95
+ "prefix": null,
96
+ "bos_token_id": 106153,
97
+ "pad_token_id": null,
98
+ "eos_token_id": 106154,
99
+ "sep_token_id": null,
100
+ "decoder_start_token_id": null,
101
+ "task_specific_params": null,
102
+ "problem_type": null,
103
+ "_name_or_path": "Qwen-2-lm-pruned-0.7-width-pruned-a0m4-ft6506-concat-alpaca_bi_chat-0.05-param-ratio-0.67-top5_delta0.15-ft/checkpoint-12000",
104
+ "transformers_version": "4.44.2",
105
+ "auto_map": {
106
+ "AutoConfig": "configuration_qwen2.Qwen2Config",
107
+ "AutoModelForCausalLM": "modeling_qwen2.Qwen2ForCausalLM"
108
+ },
109
+ "model_type": "qwen2",
110
+ "truncation_ranks": {
111
+ "model.layers.0.mlp.down_proj": 2109,
112
+ "model.layers.0.mlp.gate_up_proj": 819,
113
+ "model.layers.0.self_attn.o_proj": 845,
114
+ "model.layers.0.self_attn.qkv_proj": 1495,
115
+ "model.layers.1.mlp.down_proj": 1657,
116
+ "model.layers.1.mlp.gate_up_proj": 1310,
117
+ "model.layers.1.self_attn.o_proj": 154,
118
+ "model.layers.1.self_attn.qkv_proj": 176,
119
+ "model.layers.10.self_attn.o_proj": 615,
120
+ "model.layers.10.self_attn.qkv_proj": 703,
121
+ "model.layers.11.mlp.down_proj": 286,
122
+ "model.layers.11.mlp.gate_up_proj": 318,
123
+ "model.layers.11.self_attn.o_proj": 384,
124
+ "model.layers.11.self_attn.qkv_proj": 439,
125
+ "model.layers.12.mlp.down_proj": 1574,
126
+ "model.layers.12.mlp.gate_up_proj": 2705,
127
+ "model.layers.12.self_attn.o_proj": 154,
128
+ "model.layers.12.self_attn.qkv_proj": 176,
129
+ "model.layers.13.mlp.down_proj": 716,
130
+ "model.layers.13.mlp.gate_up_proj": 1273,
131
+ "model.layers.13.self_attn.o_proj": 615,
132
+ "model.layers.13.self_attn.qkv_proj": 703,
133
+ "model.layers.14.mlp.down_proj": 716,
134
+ "model.layers.14.mlp.gate_up_proj": 1751,
135
+ "model.layers.14.self_attn.o_proj": 384,
136
+ "model.layers.14.self_attn.qkv_proj": 439,
137
+ "model.layers.15.mlp.down_proj": 716,
138
+ "model.layers.15.mlp.gate_up_proj": 1273,
139
+ "model.layers.15.self_attn.o_proj": 154,
140
+ "model.layers.15.self_attn.qkv_proj": 176,
141
+ "model.layers.16.mlp.down_proj": 716,
142
+ "model.layers.16.mlp.gate_up_proj": 1273,
143
+ "model.layers.16.self_attn.o_proj": 384,
144
+ "model.layers.16.self_attn.qkv_proj": 439,
145
+ "model.layers.17.mlp.down_proj": 1145,
146
+ "model.layers.17.mlp.gate_up_proj": 1751,
147
+ "model.layers.17.self_attn.o_proj": 384,
148
+ "model.layers.17.self_attn.qkv_proj": 439,
149
+ "model.layers.18.mlp.down_proj": 1145,
150
+ "model.layers.18.mlp.gate_up_proj": 1273,
151
+ "model.layers.18.self_attn.o_proj": 384,
152
+ "model.layers.18.self_attn.qkv_proj": 439,
153
+ "model.layers.19.mlp.gate_up_proj": 1751,
154
+ "model.layers.19.self_attn.o_proj": 384,
155
+ "model.layers.19.self_attn.qkv_proj": 703,
156
+ "model.layers.2.mlp.down_proj": 1657,
157
+ "model.layers.2.mlp.gate_up_proj": 1801,
158
+ "model.layers.2.self_attn.o_proj": 154,
159
+ "model.layers.2.self_attn.qkv_proj": 176,
160
+ "model.layers.20.self_attn.o_proj": 384,
161
+ "model.layers.20.self_attn.qkv_proj": 703,
162
+ "model.layers.21.self_attn.o_proj": 615,
163
+ "model.layers.21.self_attn.qkv_proj": 703,
164
+ "model.layers.22.self_attn.o_proj": 615,
165
+ "model.layers.22.self_attn.qkv_proj": 967,
166
+ "model.layers.23.self_attn.o_proj": 615,
167
+ "model.layers.23.self_attn.qkv_proj": 703,
168
+ "model.layers.24.self_attn.o_proj": 384,
169
+ "model.layers.24.self_attn.qkv_proj": 439,
170
+ "model.layers.25.self_attn.o_proj": 154,
171
+ "model.layers.25.self_attn.qkv_proj": 439,
172
+ "model.layers.26.self_attn.o_proj": 384,
173
+ "model.layers.26.self_attn.qkv_proj": 439,
174
+ "model.layers.27.mlp.gate_up_proj": 2783,
175
+ "model.layers.27.self_attn.o_proj": 384,
176
+ "model.layers.27.self_attn.qkv_proj": 176,
177
+ "model.layers.3.mlp.down_proj": 1205,
178
+ "model.layers.3.mlp.gate_up_proj": 1310,
179
+ "model.layers.3.self_attn.o_proj": 615,
180
+ "model.layers.3.self_attn.qkv_proj": 439,
181
+ "model.layers.4.mlp.down_proj": 1145,
182
+ "model.layers.4.mlp.gate_up_proj": 1273,
183
+ "model.layers.4.self_attn.o_proj": 384,
184
+ "model.layers.4.self_attn.qkv_proj": 439,
185
+ "model.layers.5.mlp.down_proj": 286,
186
+ "model.layers.5.mlp.gate_up_proj": 318,
187
+ "model.layers.5.self_attn.o_proj": 154,
188
+ "model.layers.5.self_attn.qkv_proj": 439,
189
+ "model.layers.6.mlp.down_proj": 1574,
190
+ "model.layers.6.self_attn.o_proj": 154,
191
+ "model.layers.6.self_attn.qkv_proj": 439,
192
+ "model.layers.7.self_attn.o_proj": 615,
193
+ "model.layers.7.self_attn.qkv_proj": 703,
194
+ "model.layers.8.mlp.down_proj": 1574,
195
+ "model.layers.8.mlp.gate_up_proj": 1751,
196
+ "model.layers.8.self_attn.o_proj": 615,
197
+ "model.layers.8.self_attn.qkv_proj": 703,
198
+ "model.layers.9.mlp.gate_up_proj": 2705,
199
+ "model.layers.9.self_attn.o_proj": 384,
200
+ "model.layers.9.self_attn.qkv_proj": 703
201
+ },
202
+ "ori_hidden_size": 3584
203
+ }
configuration_qwen2.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class Qwen2Config(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`Qwen2Model`]. It is used to instantiate a
27
+ Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of
29
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 151936):
37
+ Vocabulary size of the Qwen2 model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`Qwen2Model`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 22016):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer encoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ num_key_value_heads (`int`, *optional*, defaults to 32):
48
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
49
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
50
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
51
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
52
+ by meanpooling all the original heads within that group. For more details checkout [this
53
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
55
+ The non-linear activation function (function or string) in the decoder.
56
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
57
+ The maximum sequence length that this model might ever be used with.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether the model's input and output word embeddings should be tied.
67
+ rope_theta (`float`, *optional*, defaults to 10000.0):
68
+ The base period of the RoPE embeddings.
69
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
70
+ Whether to use sliding window attention.
71
+ sliding_window (`int`, *optional*, defaults to 4096):
72
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
73
+ max_window_layers (`int`, *optional*, defaults to 28):
74
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
75
+ attention_dropout (`float`, *optional*, defaults to 0.0):
76
+ The dropout ratio for the attention probabilities.
77
+
78
+ ```python
79
+ >>> from transformers import Qwen2Model, Qwen2Config
80
+
81
+ >>> # Initializing a Qwen2 style configuration
82
+ >>> configuration = Qwen2Config()
83
+
84
+ >>> # Initializing a model from the Qwen2-7B style configuration
85
+ >>> model = Qwen2Model(configuration)
86
+
87
+ >>> # Accessing the model configuration
88
+ >>> configuration = model.config
89
+ ```"""
90
+
91
+ model_type = "qwen2"
92
+ keys_to_ignore_at_inference = ["past_key_values"]
93
+
94
+ def __init__(
95
+ self,
96
+ vocab_size=151936,
97
+ hidden_size=4096,
98
+ intermediate_size=22016,
99
+ num_hidden_layers=32,
100
+ num_attention_heads=32,
101
+ num_key_value_heads=32,
102
+ hidden_act="silu",
103
+ max_position_embeddings=32768,
104
+ initializer_range=0.02,
105
+ rms_norm_eps=1e-6,
106
+ use_cache=True,
107
+ tie_word_embeddings=False,
108
+ rope_theta=10000.0,
109
+ use_sliding_window=False,
110
+ sliding_window=4096,
111
+ max_window_layers=28,
112
+ attention_dropout=0.0,
113
+ pruned_layers=[],
114
+ pruned_intermediate_size=12185,
115
+ pruned_hidden_size=3584,
116
+ pruned_num_attention_heads=28,
117
+ pruned_num_key_value_heads=7,
118
+ truncation_ranks=None,
119
+ **kwargs,
120
+ ):
121
+ self.vocab_size = vocab_size
122
+ self.max_position_embeddings = max_position_embeddings
123
+ self.hidden_size = hidden_size
124
+ self.intermediate_size = intermediate_size
125
+ self.num_hidden_layers = num_hidden_layers
126
+ self.num_attention_heads = num_attention_heads
127
+ self.use_sliding_window = use_sliding_window
128
+ self.sliding_window = sliding_window if use_sliding_window else None
129
+ self.max_window_layers = max_window_layers
130
+ self.pruned_layers = pruned_layers
131
+ self.pruned_intermediate_size=pruned_intermediate_size,
132
+ self.pruned_hidden_size=pruned_hidden_size,
133
+ self.pruned_num_attention_heads=pruned_num_attention_heads
134
+ self.pruned_num_key_value_heads=pruned_num_key_value_heads
135
+
136
+ # for backward compatibility
137
+ if num_key_value_heads is None:
138
+ num_key_value_heads = num_attention_heads
139
+
140
+ self.num_key_value_heads = num_key_value_heads
141
+ self.hidden_act = hidden_act
142
+ self.initializer_range = initializer_range
143
+ self.rms_norm_eps = rms_norm_eps
144
+ self.use_cache = use_cache
145
+ self.rope_theta = rope_theta
146
+ self.attention_dropout = attention_dropout
147
+
148
+ super().__init__(
149
+ tie_word_embeddings=tie_word_embeddings,
150
+ **kwargs,
151
+ )
152
+
153
+ # for asvd
154
+ self.truncation_ranks = truncation_ranks
155
+
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 106153,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 106154,
6
+ 106152
7
+ ],
8
+ "pad_token_id": 106152,
9
+ "repetition_penalty": 1.05,
10
+ "temperature": 0.7,
11
+ "top_k": 20,
12
+ "top_p": 0.8,
13
+ "transformers_version": "4.44.2"
14
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a14ee5800e0b3c61c8d8d980356e559d2323d7c87e3b764320e8542724cf4a8
3
+ size 4954994872
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64ba80f111624cc4a4cc1b577389c01f37c1fd99d71d302e86a6f5f080f39dea
3
+ size 3037218584
model.safetensors.index.json ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 7992178432
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00002-of-00002.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.0.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.0.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.0.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
17
+ "model.layers.0.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.0.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.1.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.1.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.1.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.1.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.1.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.1.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.1.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
28
+ "model.layers.1.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.1.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.10.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.10.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.10.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
37
+ "model.layers.10.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.10.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.11.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.11.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.11.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.11.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.11.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.11.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.11.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
48
+ "model.layers.11.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.11.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.12.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.12.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.12.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.12.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.12.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.12.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.12.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
59
+ "model.layers.12.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.12.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.13.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.13.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.13.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.13.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.13.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.13.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.13.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
70
+ "model.layers.13.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.13.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.14.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.14.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.14.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.14.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.14.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.14.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.14.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
81
+ "model.layers.14.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.14.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.15.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
85
+ "model.layers.15.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.15.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.15.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
88
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.15.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
90
+ "model.layers.15.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.15.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
92
+ "model.layers.15.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
93
+ "model.layers.15.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
94
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
95
+ "model.layers.16.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
96
+ "model.layers.16.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.16.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
98
+ "model.layers.16.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
99
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
100
+ "model.layers.16.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
101
+ "model.layers.16.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
102
+ "model.layers.16.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
103
+ "model.layers.16.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
104
+ "model.layers.16.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
105
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
106
+ "model.layers.17.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
107
+ "model.layers.17.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
108
+ "model.layers.17.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
109
+ "model.layers.17.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
110
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
111
+ "model.layers.17.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
112
+ "model.layers.17.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
113
+ "model.layers.17.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
114
+ "model.layers.17.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
115
+ "model.layers.17.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
116
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
117
+ "model.layers.18.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
118
+ "model.layers.18.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
119
+ "model.layers.18.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
120
+ "model.layers.18.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
121
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
122
+ "model.layers.18.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
123
+ "model.layers.18.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
124
+ "model.layers.18.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
125
+ "model.layers.18.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
126
+ "model.layers.18.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
127
+ "model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
128
+ "model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
129
+ "model.layers.19.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
130
+ "model.layers.19.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
131
+ "model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
132
+ "model.layers.19.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
133
+ "model.layers.19.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
134
+ "model.layers.19.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
135
+ "model.layers.19.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
136
+ "model.layers.19.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
137
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
138
+ "model.layers.2.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
139
+ "model.layers.2.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
140
+ "model.layers.2.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
141
+ "model.layers.2.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
142
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
143
+ "model.layers.2.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
144
+ "model.layers.2.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
145
+ "model.layers.2.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
146
+ "model.layers.2.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.2.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.20.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
153
+ "model.layers.20.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
154
+ "model.layers.20.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
155
+ "model.layers.20.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
156
+ "model.layers.20.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
157
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
158
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
159
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
160
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
161
+ "model.layers.21.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
162
+ "model.layers.21.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
163
+ "model.layers.21.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
164
+ "model.layers.21.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
165
+ "model.layers.21.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
166
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
167
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
168
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
169
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
170
+ "model.layers.22.self_attn.o_proj.ALinear.weight": "model-00002-of-00002.safetensors",
171
+ "model.layers.22.self_attn.o_proj.BLinear.weight": "model-00002-of-00002.safetensors",
172
+ "model.layers.22.self_attn.qkv_proj.ALinear.bias": "model-00002-of-00002.safetensors",
173
+ "model.layers.22.self_attn.qkv_proj.ALinear.weight": "model-00002-of-00002.safetensors",
174
+ "model.layers.22.self_attn.qkv_proj.BLinear.weight": "model-00002-of-00002.safetensors",
175
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
176
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
177
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
178
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
179
+ "model.layers.23.self_attn.o_proj.ALinear.weight": "model-00002-of-00002.safetensors",
180
+ "model.layers.23.self_attn.o_proj.BLinear.weight": "model-00002-of-00002.safetensors",
181
+ "model.layers.23.self_attn.qkv_proj.ALinear.bias": "model-00002-of-00002.safetensors",
182
+ "model.layers.23.self_attn.qkv_proj.ALinear.weight": "model-00002-of-00002.safetensors",
183
+ "model.layers.23.self_attn.qkv_proj.BLinear.weight": "model-00002-of-00002.safetensors",
184
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
185
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
186
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
187
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
188
+ "model.layers.24.self_attn.o_proj.ALinear.weight": "model-00002-of-00002.safetensors",
189
+ "model.layers.24.self_attn.o_proj.BLinear.weight": "model-00002-of-00002.safetensors",
190
+ "model.layers.24.self_attn.qkv_proj.ALinear.bias": "model-00002-of-00002.safetensors",
191
+ "model.layers.24.self_attn.qkv_proj.ALinear.weight": "model-00002-of-00002.safetensors",
192
+ "model.layers.24.self_attn.qkv_proj.BLinear.weight": "model-00002-of-00002.safetensors",
193
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
194
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
195
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
196
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
197
+ "model.layers.25.self_attn.o_proj.ALinear.weight": "model-00002-of-00002.safetensors",
198
+ "model.layers.25.self_attn.o_proj.BLinear.weight": "model-00002-of-00002.safetensors",
199
+ "model.layers.25.self_attn.qkv_proj.ALinear.bias": "model-00002-of-00002.safetensors",
200
+ "model.layers.25.self_attn.qkv_proj.ALinear.weight": "model-00002-of-00002.safetensors",
201
+ "model.layers.25.self_attn.qkv_proj.BLinear.weight": "model-00002-of-00002.safetensors",
202
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
203
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
204
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00002-of-00002.safetensors",
205
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
206
+ "model.layers.26.self_attn.o_proj.ALinear.weight": "model-00002-of-00002.safetensors",
207
+ "model.layers.26.self_attn.o_proj.BLinear.weight": "model-00002-of-00002.safetensors",
208
+ "model.layers.26.self_attn.qkv_proj.ALinear.bias": "model-00002-of-00002.safetensors",
209
+ "model.layers.26.self_attn.qkv_proj.ALinear.weight": "model-00002-of-00002.safetensors",
210
+ "model.layers.26.self_attn.qkv_proj.BLinear.weight": "model-00002-of-00002.safetensors",
211
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
212
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
213
+ "model.layers.27.mlp.gate_up_proj.ALinear.weight": "model-00002-of-00002.safetensors",
214
+ "model.layers.27.mlp.gate_up_proj.BLinear.weight": "model-00002-of-00002.safetensors",
215
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
216
+ "model.layers.27.self_attn.o_proj.ALinear.weight": "model-00002-of-00002.safetensors",
217
+ "model.layers.27.self_attn.o_proj.BLinear.weight": "model-00002-of-00002.safetensors",
218
+ "model.layers.27.self_attn.qkv_proj.ALinear.bias": "model-00002-of-00002.safetensors",
219
+ "model.layers.27.self_attn.qkv_proj.ALinear.weight": "model-00002-of-00002.safetensors",
220
+ "model.layers.27.self_attn.qkv_proj.BLinear.weight": "model-00002-of-00002.safetensors",
221
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
222
+ "model.layers.3.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
223
+ "model.layers.3.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
224
+ "model.layers.3.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
225
+ "model.layers.3.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
226
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
227
+ "model.layers.3.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
228
+ "model.layers.3.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
229
+ "model.layers.3.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
230
+ "model.layers.3.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
231
+ "model.layers.3.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
232
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
233
+ "model.layers.4.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
234
+ "model.layers.4.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
235
+ "model.layers.4.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
236
+ "model.layers.4.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
237
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
238
+ "model.layers.4.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
239
+ "model.layers.4.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
240
+ "model.layers.4.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
241
+ "model.layers.4.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
242
+ "model.layers.4.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
243
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
244
+ "model.layers.5.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
245
+ "model.layers.5.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
246
+ "model.layers.5.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
247
+ "model.layers.5.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
248
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
249
+ "model.layers.5.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
250
+ "model.layers.5.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
251
+ "model.layers.5.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
252
+ "model.layers.5.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
253
+ "model.layers.5.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
254
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
255
+ "model.layers.6.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
256
+ "model.layers.6.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
257
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
258
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
259
+ "model.layers.6.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
260
+ "model.layers.6.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
261
+ "model.layers.6.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
262
+ "model.layers.6.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
263
+ "model.layers.6.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
264
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
265
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
266
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00001-of-00002.safetensors",
267
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
268
+ "model.layers.7.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
269
+ "model.layers.7.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
270
+ "model.layers.7.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
271
+ "model.layers.7.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
272
+ "model.layers.7.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
273
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
274
+ "model.layers.8.mlp.down_proj.ALinear.weight": "model-00001-of-00002.safetensors",
275
+ "model.layers.8.mlp.down_proj.BLinear.weight": "model-00001-of-00002.safetensors",
276
+ "model.layers.8.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
277
+ "model.layers.8.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
278
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
279
+ "model.layers.8.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
280
+ "model.layers.8.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
281
+ "model.layers.8.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
282
+ "model.layers.8.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
283
+ "model.layers.8.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
284
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
285
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
286
+ "model.layers.9.mlp.gate_up_proj.ALinear.weight": "model-00001-of-00002.safetensors",
287
+ "model.layers.9.mlp.gate_up_proj.BLinear.weight": "model-00001-of-00002.safetensors",
288
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
289
+ "model.layers.9.self_attn.o_proj.ALinear.weight": "model-00001-of-00002.safetensors",
290
+ "model.layers.9.self_attn.o_proj.BLinear.weight": "model-00001-of-00002.safetensors",
291
+ "model.layers.9.self_attn.qkv_proj.ALinear.bias": "model-00001-of-00002.safetensors",
292
+ "model.layers.9.self_attn.qkv_proj.ALinear.weight": "model-00001-of-00002.safetensors",
293
+ "model.layers.9.self_attn.qkv_proj.BLinear.weight": "model-00001-of-00002.safetensors",
294
+ "model.norm.weight": "model-00002-of-00002.safetensors"
295
+ }
296
+ }
modeling_qwen2.py ADDED
@@ -0,0 +1,1481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch Qwen2 model."""
21
+
22
+ import math
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
32
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ SequenceClassifierOutputWithPast,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_qwen2 import Qwen2Config
49
+
50
+
51
+ if is_flash_attn_2_available():
52
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ _CHECKPOINT_FOR_DOC = "Qwen/Qwen2-7B-beta"
59
+ _CONFIG_FOR_DOC = "Qwen2Config"
60
+
61
+
62
+ # Copied from transformers.models.llama.modeling_llama._prepare_4d_causal_attention_mask_with_cache_position
63
+ def _prepare_4d_causal_attention_mask_with_cache_position(
64
+ attention_mask: torch.Tensor,
65
+ sequence_length: int,
66
+ target_length: int,
67
+ dtype: torch.dtype,
68
+ device: torch.device,
69
+ min_dtype: float,
70
+ cache_position: torch.Tensor,
71
+ batch_size: int,
72
+ ):
73
+ """
74
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
75
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
76
+
77
+ Args:
78
+ attention_mask (`torch.Tensor`):
79
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
80
+ sequence_length (`int`):
81
+ The sequence length being processed.
82
+ target_length (`int`):
83
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
84
+ dtype (`torch.dtype`):
85
+ The dtype to use for the 4D attention mask.
86
+ device (`torch.device`):
87
+ The device to plcae the 4D attention mask on.
88
+ min_dtype (`float`):
89
+ The minimum value representable with the dtype `dtype`.
90
+ cache_position (`torch.Tensor`):
91
+ Indices depicting the position of the input sequence tokens in the sequence.
92
+ batch_size (`torch.Tensor`):
93
+ Batch size.
94
+ """
95
+ if attention_mask is not None and attention_mask.dim() == 4:
96
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
97
+ causal_mask = attention_mask
98
+ else:
99
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
100
+ if sequence_length != 1:
101
+ causal_mask = torch.triu(causal_mask, diagonal=1)
102
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
103
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
104
+ if attention_mask is not None:
105
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
106
+ mask_length = attention_mask.shape[-1]
107
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
108
+ padding_mask = padding_mask == 0
109
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
110
+ padding_mask, min_dtype
111
+ )
112
+
113
+ return causal_mask
114
+
115
+
116
+ class ASVDLinear(nn.Module):
117
+ def __init__(self, in_features, out_features, rank, bias=False):
118
+ super().__init__()
119
+ # self.BLinear = nn.Linear(in_features, rank, bias=False)
120
+ # self.ALinear = nn.Linear(rank, out_features, bias=bias)
121
+ self.BLinear = nn.Linear(in_features, rank, bias=False)
122
+ self.ALinear = nn.Linear(rank, out_features, bias=bias)
123
+
124
+ self.BLinear.weight.requires_grad = False
125
+ self.ALinear.weight.requires_grad = False
126
+
127
+ def forward(self, input):
128
+ # return self.ALinear(self.BLinear(input))
129
+ y = self.BLinear(input)
130
+ y = self.ALinear(y)
131
+ return y
132
+
133
+
134
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2
135
+ class Qwen2RMSNorm(nn.Module):
136
+ def __init__(self, hidden_size, eps=1e-6):
137
+ """
138
+ Qwen2RMSNorm is equivalent to T5LayerNorm
139
+ """
140
+ super().__init__()
141
+ self.weight = nn.Parameter(torch.ones(hidden_size))
142
+ self.variance_epsilon = eps
143
+
144
+ def forward(self, hidden_states):
145
+ input_dtype = hidden_states.dtype
146
+ hidden_states = hidden_states.to(torch.float32)
147
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
148
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
149
+ return self.weight * hidden_states.to(input_dtype)
150
+
151
+ def extra_repr(self):
152
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
153
+
154
+
155
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Qwen2
156
+ class Qwen2RotaryEmbedding(nn.Module):
157
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
158
+ super().__init__()
159
+
160
+ self.dim = dim
161
+ self.max_position_embeddings = max_position_embeddings
162
+ self.base = base
163
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
164
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
165
+
166
+ # Build here to make `torch.jit.trace` work.
167
+ self._set_cos_sin_cache(
168
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
169
+ )
170
+
171
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
172
+ self.max_seq_len_cached = seq_len
173
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
174
+
175
+ freqs = torch.outer(t, self.inv_freq)
176
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
177
+ emb = torch.cat((freqs, freqs), dim=-1)
178
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
179
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
180
+
181
+ def forward(self, x, seq_len=None):
182
+ # x: [bs, num_attention_heads, seq_len, head_size]
183
+ if seq_len > self.max_seq_len_cached:
184
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
185
+
186
+ return (
187
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
188
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
189
+ )
190
+
191
+
192
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
193
+ def rotate_half(x):
194
+ """Rotates half the hidden dims of the input."""
195
+ x1 = x[..., : x.shape[-1] // 2]
196
+ x2 = x[..., x.shape[-1] // 2 :]
197
+ return torch.cat((-x2, x1), dim=-1)
198
+
199
+
200
+ # Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
201
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
202
+ """Applies Rotary Position Embedding to the query and key tensors.
203
+
204
+ Args:
205
+ q (`torch.Tensor`): The query tensor.
206
+ k (`torch.Tensor`): The key tensor.
207
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
208
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
209
+ position_ids (`torch.Tensor`):
210
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
211
+ used to pass offsetted position ids when working with a KV-cache.
212
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
213
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
214
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
215
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
216
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
217
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
218
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
219
+ Returns:
220
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
221
+ """
222
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
223
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
224
+ q_embed = (q * cos) + (rotate_half(q) * sin)
225
+ k_embed = (k * cos) + (rotate_half(k) * sin)
226
+ return q_embed, k_embed
227
+
228
+
229
+ # Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2
230
+ class Qwen2MLP(nn.Module):
231
+ def __init__(self, config, layer_idx: Optional[int] = None):
232
+ super().__init__()
233
+ self.hidden_size = config.ori_hidden_size
234
+ self.layer_idx = layer_idx
235
+ truncation_ranks = config.truncation_ranks
236
+ if self.layer_idx in config.pruned_layers:
237
+ self.intermediate_size = config.pruned_intermediate_size[0]
238
+ else:
239
+ self.intermediate_size = config.intermediate_size
240
+ layer_name = f"model.layers.{self.layer_idx}.mlp.gate_up_proj"
241
+ if truncation_ranks.get(layer_name, None) is not None:
242
+ print(f"Using ASVDLinear for {layer_name}")
243
+ self.gate_up_proj = ASVDLinear(self.hidden_size, self.intermediate_size * 2, truncation_ranks[layer_name])
244
+ else:
245
+ self.gate_up_proj = nn.Linear(
246
+ in_features=self.hidden_size,
247
+ out_features=self.intermediate_size * 2,
248
+ bias=False,
249
+ )
250
+
251
+ layer_name = f"model.layers.{self.layer_idx}.mlp.down_proj"
252
+ if truncation_ranks.get(layer_name, None) is not None:
253
+ print(f"Using ASVDLinear for {layer_name}")
254
+ self.down_proj = ASVDLinear(self.intermediate_size, self.hidden_size, truncation_ranks[layer_name])
255
+ else:
256
+ self.down_proj = nn.Linear(
257
+ in_features=self.intermediate_size,
258
+ out_features=self.hidden_size,
259
+ bias=False,
260
+ )
261
+ self.act_fn = ACT2FN[config.hidden_act]
262
+
263
+ def forward(self, hidden_state):
264
+ concat_x1_x2 = self.gate_up_proj(hidden_state)
265
+ x1, x2 = torch.split(concat_x1_x2, concat_x1_x2.size(-1) // 2, dim=-1)
266
+ return self.down_proj(self.act_fn(x1) * x2)
267
+
268
+
269
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
270
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
271
+ """
272
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
273
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
274
+ """
275
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
276
+ if n_rep == 1:
277
+ return hidden_states
278
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
279
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
280
+
281
+
282
+ class Qwen2Attention(nn.Module):
283
+ """
284
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
285
+ and "Generating Long Sequences with Sparse Transformers".
286
+ """
287
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
288
+ super().__init__()
289
+ self.config = config
290
+ self.layer_idx = layer_idx
291
+ if layer_idx is None:
292
+ logger.warning_once(
293
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
294
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
295
+ "when creating this class."
296
+ )
297
+ truncation_ranks = config.truncation_ranks
298
+
299
+ self.hidden_size = config.ori_hidden_size
300
+ self.num_heads = config.num_attention_heads
301
+ self.head_dim = config.hidden_size // self.num_heads
302
+ self.num_key_value_heads = config.num_key_value_heads
303
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
304
+ self.max_position_embeddings = config.max_position_embeddings
305
+ self.rope_theta = config.rope_theta
306
+ self.is_causal = True
307
+ self.attention_dropout = config.attention_dropout
308
+
309
+ # if (self.head_dim * self.num_heads) != self.hidden_size:
310
+ # raise ValueError(
311
+ # f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
312
+ # f" and `num_heads`: {self.num_heads})."
313
+ # )
314
+ layer_name = f"model.layers.{self.layer_idx}.self_attn.qkv_proj"
315
+ if truncation_ranks.get(layer_name, None) is not None:
316
+ print(f"Using ASVDLinear for {layer_name}")
317
+ self.qkv_proj = ASVDLinear(
318
+ self.hidden_size, (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim, truncation_ranks[layer_name], bias=True
319
+ )
320
+ else:
321
+ self.qkv_proj = nn.Linear(self.hidden_size, (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim, bias=True)
322
+
323
+ layer_name = f"model.layers.{self.layer_idx}.self_attn.o_proj"
324
+ if truncation_ranks.get(layer_name, None) is not None:
325
+ print(f"Using ASVDLinear for {layer_name}")
326
+ self.o_proj = ASVDLinear(
327
+ self.num_heads * self.head_dim, self.hidden_size, truncation_ranks[layer_name], bias=False
328
+ )
329
+ else:
330
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
331
+
332
+ self.rotary_emb = Qwen2RotaryEmbedding(
333
+ self.head_dim,
334
+ max_position_embeddings=self.max_position_embeddings,
335
+ base=self.rope_theta,
336
+ )
337
+
338
+ def forward(
339
+ self,
340
+ hidden_states: torch.Tensor,
341
+ attention_mask: Optional[torch.Tensor] = None,
342
+ position_ids: Optional[torch.LongTensor] = None,
343
+ past_key_value: Optional[Cache] = None,
344
+ output_attentions: bool = False,
345
+ use_cache: bool = False,
346
+ cache_position: Optional[torch.LongTensor] = None,
347
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
348
+ bsz, q_len, _ = hidden_states.size()
349
+
350
+ qkv_states = self.qkv_proj(hidden_states)
351
+ qkv_states = qkv_states.view(
352
+ bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim
353
+ ).transpose(1, 2)
354
+ query_states, key_states, value_states = torch.split(
355
+ qkv_states, [self.num_heads, self.num_heads + self.num_key_value_heads], dim=1
356
+ )
357
+
358
+ kv_seq_len = key_states.shape[-2]
359
+ if past_key_value is not None:
360
+ if self.layer_idx is None:
361
+ raise ValueError(
362
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
363
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
364
+ "with a layer index."
365
+ )
366
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
367
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
368
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
369
+
370
+ if past_key_value is not None:
371
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
372
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
373
+
374
+ # repeat k/v heads if n_kv_heads < n_heads
375
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
376
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
377
+
378
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
379
+
380
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
381
+ raise ValueError(
382
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
383
+ f" {attn_weights.size()}"
384
+ )
385
+
386
+ if attention_mask is not None: # no matter the length, we just slice it
387
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
388
+ attn_weights = attn_weights + causal_mask
389
+
390
+ # upcast attention to fp32
391
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
392
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
393
+ attn_output = torch.matmul(attn_weights, value_states)
394
+
395
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
396
+ raise ValueError(
397
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
398
+ f" {attn_output.size()}"
399
+ )
400
+
401
+ attn_output = attn_output.transpose(1, 2).contiguous()
402
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
403
+
404
+ attn_output = self.o_proj(attn_output)
405
+
406
+ if not output_attentions:
407
+ attn_weights = None
408
+
409
+ return attn_output, attn_weights, past_key_value
410
+
411
+
412
+ class Qwen2FlashAttention2(Qwen2Attention):
413
+ """
414
+ Qwen2 flash attention module, following Qwen2 attention module. This module inherits from `Qwen2Attention`
415
+ as the weights of the module stays untouched. The only required change would be on the forward pass
416
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
417
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
418
+ config.max_window_layers layers.
419
+ """
420
+
421
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
422
+ def __init__(self, *args, **kwargs):
423
+ super().__init__(*args, **kwargs)
424
+
425
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
426
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
427
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
428
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
429
+
430
+ def forward(
431
+ self,
432
+ hidden_states: torch.Tensor,
433
+ attention_mask: Optional[torch.Tensor] = None,
434
+ position_ids: Optional[torch.LongTensor] = None,
435
+ past_key_value: Optional[Cache] = None,
436
+ output_attentions: bool = False,
437
+ use_cache: bool = False,
438
+ cache_position: Optional[torch.LongTensor] = None,
439
+ ):
440
+ bsz, q_len, _ = hidden_states.size()
441
+
442
+ query_states = self.q_proj(hidden_states)
443
+ key_states = self.k_proj(hidden_states)
444
+ value_states = self.v_proj(hidden_states)
445
+
446
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
447
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
448
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
449
+
450
+ kv_seq_len = key_states.shape[-2]
451
+ if past_key_value is not None:
452
+ if self.layer_idx is None:
453
+ raise ValueError(
454
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
455
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
456
+ "with a layer index."
457
+ )
458
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
459
+
460
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
461
+ rotary_seq_len = (
462
+ max(kv_seq_len, position_ids[:, -1].max().item() + 1) if position_ids is not None else kv_seq_len
463
+ )
464
+
465
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
466
+
467
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
468
+
469
+ if past_key_value is not None:
470
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
471
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
472
+ if (
473
+ getattr(self.config, "sliding_window", None) is not None
474
+ and kv_seq_len > self.config.sliding_window
475
+ and cache_has_contents
476
+ ):
477
+ slicing_tokens = 1 - self.config.sliding_window
478
+
479
+ past_key = past_key_value[self.layer_idx][0]
480
+ past_value = past_key_value[self.layer_idx][1]
481
+
482
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
483
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
484
+
485
+ if past_key.shape[-2] != self.config.sliding_window - 1:
486
+ raise ValueError(
487
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
488
+ f" {past_key.shape}"
489
+ )
490
+
491
+ if attention_mask is not None:
492
+ attention_mask = attention_mask[:, slicing_tokens:]
493
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
494
+
495
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
496
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
497
+
498
+ # repeat k/v heads if n_kv_heads < n_heads
499
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
500
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
501
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
502
+
503
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
504
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
505
+ # cast them back in float16 just to be sure everything works as expected.
506
+ input_dtype = query_states.dtype
507
+ if input_dtype == torch.float32:
508
+ if torch.is_autocast_enabled():
509
+ target_dtype = torch.get_autocast_gpu_dtype()
510
+ # Handle the case where the model is quantized
511
+ elif hasattr(self.config, "_pre_quantization_dtype"):
512
+ target_dtype = self.config._pre_quantization_dtype
513
+ else:
514
+ target_dtype = self.q_proj.weight.dtype
515
+
516
+ logger.warning_once(
517
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
518
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
519
+ f" {target_dtype}."
520
+ )
521
+
522
+ query_states = query_states.to(target_dtype)
523
+ key_states = key_states.to(target_dtype)
524
+ value_states = value_states.to(target_dtype)
525
+
526
+ # Reashape to the expected shape for Flash Attention
527
+ query_states = query_states.transpose(1, 2)
528
+ key_states = key_states.transpose(1, 2)
529
+ value_states = value_states.transpose(1, 2)
530
+
531
+ if (
532
+ self.config.use_sliding_window
533
+ and getattr(self.config, "sliding_window", None) is not None
534
+ and self.layer_idx >= self.config.max_window_layers
535
+ ):
536
+ sliding_window = self.config.sliding_window
537
+ else:
538
+ sliding_window = None
539
+
540
+ attn_output = _flash_attention_forward(
541
+ query_states,
542
+ key_states,
543
+ value_states,
544
+ attention_mask,
545
+ q_len,
546
+ position_ids=position_ids,
547
+ dropout=dropout_rate,
548
+ sliding_window=sliding_window,
549
+ is_causal=self.is_causal,
550
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
551
+ )
552
+
553
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
554
+ attn_output = self.o_proj(attn_output)
555
+
556
+ if not output_attentions:
557
+ attn_weights = None
558
+
559
+ return attn_output, attn_weights, past_key_value
560
+
561
+
562
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralSdpaAttention with Mixtral->Qwen2
563
+ class Qwen2SdpaAttention(Qwen2Attention):
564
+ """
565
+ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
566
+ `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
567
+ SDPA API.
568
+ """
569
+
570
+ # Adapted from Qwen2Attention.forward
571
+ def forward(
572
+ self,
573
+ hidden_states: torch.Tensor,
574
+ attention_mask: Optional[torch.Tensor] = None,
575
+ position_ids: Optional[torch.LongTensor] = None,
576
+ past_key_value: Optional[Cache] = None,
577
+ output_attentions: bool = False,
578
+ use_cache: bool = False,
579
+ cache_position: Optional[torch.LongTensor] = None,
580
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
581
+ if output_attentions:
582
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
583
+ logger.warning_once(
584
+ "Qwen2Model is using Qwen2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
585
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
586
+ )
587
+ return super().forward(
588
+ hidden_states=hidden_states,
589
+ attention_mask=attention_mask,
590
+ position_ids=position_ids,
591
+ past_key_value=past_key_value,
592
+ output_attentions=output_attentions,
593
+ use_cache=use_cache,
594
+ )
595
+
596
+ bsz, q_len, _ = hidden_states.size()
597
+
598
+ qkv_states = self.qkv_proj(hidden_states)
599
+
600
+ qkv_states = qkv_states.view(
601
+ bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim
602
+ ).transpose(1, 2)
603
+ query_states, key_states, value_states = torch.split(
604
+ qkv_states, [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=1
605
+ )
606
+
607
+ kv_seq_len = key_states.shape[-2]
608
+ if past_key_value is not None:
609
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
610
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
611
+
612
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
613
+
614
+ if past_key_value is not None:
615
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
616
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
617
+
618
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
619
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
620
+
621
+ causal_mask = attention_mask
622
+ if attention_mask is not None: # no matter the length, we just slice it
623
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
624
+
625
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
626
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
627
+ if query_states.device.type == "cuda" and attention_mask is not None:
628
+ query_states = query_states.contiguous()
629
+ key_states = key_states.contiguous()
630
+ value_states = value_states.contiguous()
631
+
632
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
633
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
634
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
635
+ is_causal = True if causal_mask is None and q_len > 1 else False
636
+
637
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
638
+ query_states,
639
+ key_states,
640
+ value_states,
641
+ attn_mask=causal_mask,
642
+ dropout_p=self.attention_dropout if self.training else 0.0,
643
+ is_causal=is_causal,
644
+ )
645
+
646
+ attn_output = attn_output.transpose(1, 2).contiguous()
647
+ # attn_output = attn_output.view(bsz, q_len, self.hidden_size)
648
+ attn_output = attn_output.view(bsz, q_len, -1)
649
+
650
+ attn_output = self.o_proj(attn_output)
651
+
652
+ return attn_output, None, past_key_value
653
+
654
+
655
+ QWEN2_ATTENTION_CLASSES = {
656
+ "eager": Qwen2Attention,
657
+ "flash_attention_2": Qwen2FlashAttention2,
658
+ "sdpa": Qwen2SdpaAttention,
659
+ }
660
+
661
+
662
+ class Qwen2DecoderLayer(nn.Module):
663
+ def __init__(self, config: Qwen2Config, layer_idx: int):
664
+ super().__init__()
665
+ self.hidden_size = config.ori_hidden_size
666
+
667
+ if config.sliding_window and config._attn_implementation != "flash_attention_2":
668
+ logger.warning_once(
669
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
670
+ "unexpected results may be encountered."
671
+ )
672
+ self.self_attn = QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
673
+
674
+ self.mlp = Qwen2MLP(config, layer_idx)
675
+ self.input_layernorm = Qwen2RMSNorm(config.ori_hidden_size, eps=config.rms_norm_eps)
676
+ self.post_attention_layernorm = Qwen2RMSNorm(config.ori_hidden_size, eps=config.rms_norm_eps)
677
+
678
+ def forward(
679
+ self,
680
+ hidden_states: torch.Tensor,
681
+ attention_mask: Optional[torch.Tensor] = None,
682
+ position_ids: Optional[torch.LongTensor] = None,
683
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
684
+ output_attentions: Optional[bool] = False,
685
+ use_cache: Optional[bool] = False,
686
+ cache_position: Optional[torch.LongTensor] = None,
687
+ **kwargs,
688
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
689
+ """
690
+ Args:
691
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
692
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
693
+ `(batch, sequence_length)` where padding elements are indicated by 0.
694
+ output_attentions (`bool`, *optional*):
695
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
696
+ returned tensors for more detail.
697
+ use_cache (`bool`, *optional*):
698
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
699
+ (see `past_key_values`).
700
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
701
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
702
+ Indices depicting the position of the input sequence tokens in the sequence.
703
+ kwargs (`dict`, *optional*):
704
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
705
+ into the model
706
+ """
707
+
708
+ residual = hidden_states
709
+
710
+ hidden_states = self.input_layernorm(hidden_states)
711
+
712
+ # Self Attention
713
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
714
+ hidden_states=hidden_states,
715
+ attention_mask=attention_mask,
716
+ position_ids=position_ids,
717
+ past_key_value=past_key_value,
718
+ output_attentions=output_attentions,
719
+ use_cache=use_cache,
720
+ cache_position=cache_position,
721
+ )
722
+ hidden_states = residual + hidden_states
723
+
724
+ # Fully Connected
725
+ residual = hidden_states
726
+ hidden_states = self.post_attention_layernorm(hidden_states)
727
+ hidden_states = self.mlp(hidden_states)
728
+ hidden_states = residual + hidden_states
729
+
730
+ outputs = (hidden_states,)
731
+
732
+ if output_attentions:
733
+ outputs += (self_attn_weights,)
734
+
735
+ if use_cache:
736
+ outputs += (present_key_value,)
737
+
738
+ return outputs
739
+
740
+
741
+ QWEN2_START_DOCSTRING = r"""
742
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
743
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
744
+ etc.)
745
+
746
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
747
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
748
+ and behavior.
749
+
750
+ Parameters:
751
+ config ([`Qwen2Config`]):
752
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
753
+ load the weights associated with the model, only the configuration. Check out the
754
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
755
+ """
756
+
757
+
758
+ @add_start_docstrings(
759
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
760
+ QWEN2_START_DOCSTRING,
761
+ )
762
+ class Qwen2PreTrainedModel(PreTrainedModel):
763
+ config_class = Qwen2Config
764
+ base_model_prefix = "model"
765
+ supports_gradient_checkpointing = True
766
+ _no_split_modules = ["Qwen2DecoderLayer"]
767
+ _skip_keys_device_placement = "past_key_values"
768
+ _supports_flash_attn_2 = True
769
+ _supports_sdpa = True
770
+ _supports_cache_class = True
771
+
772
+ def _init_weights(self, module):
773
+ std = self.config.initializer_range
774
+ if isinstance(module, nn.Linear):
775
+ module.weight.data.normal_(mean=0.0, std=std)
776
+ if module.bias is not None:
777
+ module.bias.data.zero_()
778
+ elif isinstance(module, nn.Embedding):
779
+ module.weight.data.normal_(mean=0.0, std=std)
780
+ if module.padding_idx is not None:
781
+ module.weight.data[module.padding_idx].zero_()
782
+
783
+
784
+ QWEN2_INPUTS_DOCSTRING = r"""
785
+ Args:
786
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
787
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
788
+ it.
789
+
790
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
791
+ [`PreTrainedTokenizer.__call__`] for details.
792
+
793
+ [What are input IDs?](../glossary#input-ids)
794
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
795
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
796
+
797
+ - 1 for tokens that are **not masked**,
798
+ - 0 for tokens that are **masked**.
799
+
800
+ [What are attention masks?](../glossary#attention-mask)
801
+
802
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
803
+ [`PreTrainedTokenizer.__call__`] for details.
804
+
805
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
806
+ `past_key_values`).
807
+
808
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
809
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
810
+ information on the default strategy.
811
+
812
+ - 1 indicates the head is **not masked**,
813
+ - 0 indicates the head is **masked**.
814
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
815
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
816
+ config.n_positions - 1]`.
817
+
818
+ [What are position IDs?](../glossary#position-ids)
819
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
820
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
821
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
822
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
823
+
824
+ Two formats are allowed:
825
+ - a [`~cache_utils.Cache`] instance;
826
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
827
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
828
+ cache format.
829
+
830
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
831
+ legacy cache format will be returned.
832
+
833
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
834
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
835
+ of shape `(batch_size, sequence_length)`.
836
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
837
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
838
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
839
+ model's internal embedding lookup matrix.
840
+ use_cache (`bool`, *optional*):
841
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
842
+ `past_key_values`).
843
+ output_attentions (`bool`, *optional*):
844
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
845
+ tensors for more detail.
846
+ output_hidden_states (`bool`, *optional*):
847
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
848
+ more detail.
849
+ return_dict (`bool`, *optional*):
850
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
851
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
852
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
853
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
854
+ the complete sequence length.
855
+ """
856
+
857
+
858
+ @add_start_docstrings(
859
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
860
+ QWEN2_START_DOCSTRING,
861
+ )
862
+ class Qwen2Model(Qwen2PreTrainedModel):
863
+ """
864
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
865
+
866
+ Args:
867
+ config: Qwen2Config
868
+ """
869
+
870
+ def __init__(self, config: Qwen2Config):
871
+ super().__init__(config)
872
+ self.padding_idx = config.pad_token_id
873
+ self.vocab_size = config.vocab_size
874
+
875
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.ori_hidden_size, self.padding_idx)
876
+ self.layers = nn.ModuleList(
877
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
878
+ )
879
+ self._attn_implementation = config._attn_implementation
880
+ self.norm = Qwen2RMSNorm(config.ori_hidden_size, eps=config.rms_norm_eps)
881
+
882
+ self.gradient_checkpointing = False
883
+ # Initialize weights and apply final processing
884
+ self.post_init()
885
+
886
+ def get_input_embeddings(self):
887
+ return self.embed_tokens
888
+
889
+ def set_input_embeddings(self, value):
890
+ self.embed_tokens = value
891
+
892
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
893
+ def forward(
894
+ self,
895
+ input_ids: torch.LongTensor = None,
896
+ attention_mask: Optional[torch.Tensor] = None,
897
+ position_ids: Optional[torch.LongTensor] = None,
898
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
899
+ inputs_embeds: Optional[torch.FloatTensor] = None,
900
+ use_cache: Optional[bool] = None,
901
+ output_attentions: Optional[bool] = None,
902
+ output_hidden_states: Optional[bool] = None,
903
+ return_dict: Optional[bool] = None,
904
+ cache_position: Optional[torch.LongTensor] = None,
905
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
906
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
907
+ output_hidden_states = (
908
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
909
+ )
910
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
911
+
912
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
913
+
914
+ if (input_ids is None) ^ (inputs_embeds is not None):
915
+ raise ValueError(
916
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
917
+ )
918
+
919
+ if self.gradient_checkpointing and self.training:
920
+ if use_cache:
921
+ logger.warning_once(
922
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
923
+ )
924
+ use_cache = False
925
+
926
+ use_legacy_cache = False
927
+ if use_cache and not isinstance(past_key_values, Cache) and not self.training:
928
+ use_legacy_cache = True
929
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
930
+ logger.warning_once(
931
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
932
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
933
+ )
934
+
935
+ if inputs_embeds is None:
936
+ inputs_embeds = self.embed_tokens(input_ids)
937
+
938
+ if cache_position is None:
939
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
940
+ cache_position = torch.arange(
941
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
942
+ )
943
+ if position_ids is None:
944
+ position_ids = cache_position.unsqueeze(0)
945
+
946
+ causal_mask = self._update_causal_mask(
947
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
948
+ )
949
+
950
+ hidden_states = inputs_embeds
951
+
952
+ # decoder layers
953
+ all_hidden_states = () if output_hidden_states else None
954
+ all_self_attns = () if output_attentions else None
955
+ next_decoder_cache = None
956
+
957
+ for decoder_layer in self.layers:
958
+ if output_hidden_states:
959
+ all_hidden_states += (hidden_states,)
960
+
961
+ if self.gradient_checkpointing and self.training:
962
+ layer_outputs = self._gradient_checkpointing_func(
963
+ decoder_layer.__call__,
964
+ hidden_states,
965
+ causal_mask,
966
+ position_ids,
967
+ past_key_values,
968
+ output_attentions,
969
+ use_cache,
970
+ cache_position,
971
+ )
972
+ else:
973
+ layer_outputs = decoder_layer(
974
+ hidden_states,
975
+ attention_mask=causal_mask,
976
+ position_ids=position_ids,
977
+ past_key_value=past_key_values,
978
+ output_attentions=output_attentions,
979
+ use_cache=use_cache,
980
+ cache_position=cache_position,
981
+ )
982
+
983
+ hidden_states = layer_outputs[0]
984
+
985
+ if use_cache:
986
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
987
+
988
+ if output_attentions:
989
+ all_self_attns += (layer_outputs[1],)
990
+
991
+ hidden_states = self.norm(hidden_states)
992
+
993
+ # add hidden states from the last decoder layer
994
+ if output_hidden_states:
995
+ all_hidden_states += (hidden_states,)
996
+
997
+ next_cache = None
998
+ if use_cache:
999
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1000
+
1001
+ if not return_dict:
1002
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1003
+ return BaseModelOutputWithPast(
1004
+ last_hidden_state=hidden_states,
1005
+ past_key_values=next_cache,
1006
+ hidden_states=all_hidden_states,
1007
+ attentions=all_self_attns,
1008
+ )
1009
+
1010
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
1011
+ def _update_causal_mask(
1012
+ self,
1013
+ attention_mask: torch.Tensor,
1014
+ input_tensor: torch.Tensor,
1015
+ cache_position: torch.Tensor,
1016
+ past_key_values: Cache,
1017
+ output_attentions: bool,
1018
+ ):
1019
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1020
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1021
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1022
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1023
+
1024
+ if self.config._attn_implementation == "flash_attention_2":
1025
+ if attention_mask is not None and 0.0 in attention_mask:
1026
+ return attention_mask
1027
+ return None
1028
+
1029
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1030
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1031
+ # to infer the attention mask.
1032
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1033
+ using_static_cache = isinstance(past_key_values, StaticCache)
1034
+
1035
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1036
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1037
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1038
+ attention_mask,
1039
+ inputs_embeds=input_tensor,
1040
+ past_key_values_length=past_seen_tokens,
1041
+ is_training=self.training,
1042
+ ):
1043
+ return None
1044
+
1045
+ dtype, device = input_tensor.dtype, input_tensor.device
1046
+ min_dtype = torch.finfo(dtype).min
1047
+ sequence_length = input_tensor.shape[1]
1048
+ if using_static_cache:
1049
+ target_length = past_key_values.get_max_length()
1050
+ else:
1051
+ target_length = (
1052
+ attention_mask.shape[-1]
1053
+ if isinstance(attention_mask, torch.Tensor)
1054
+ else past_seen_tokens + sequence_length + 1
1055
+ )
1056
+
1057
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1058
+ causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1059
+ attention_mask,
1060
+ sequence_length=sequence_length,
1061
+ target_length=target_length,
1062
+ dtype=dtype,
1063
+ device=device,
1064
+ min_dtype=min_dtype,
1065
+ cache_position=cache_position,
1066
+ batch_size=input_tensor.shape[0],
1067
+ )
1068
+
1069
+ if (
1070
+ self.config._attn_implementation == "sdpa"
1071
+ and attention_mask is not None
1072
+ and attention_mask.device.type == "cuda"
1073
+ and not output_attentions
1074
+ ):
1075
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1076
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1077
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1078
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1079
+
1080
+ return causal_mask
1081
+
1082
+
1083
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel):
1084
+ _tied_weights_keys = ["lm_head.weight"]
1085
+
1086
+ def __init__(self, config):
1087
+ super().__init__(config)
1088
+ self.model = Qwen2Model(config)
1089
+ self.vocab_size = config.vocab_size
1090
+ self.lm_head = nn.Linear(config.ori_hidden_size, config.vocab_size, bias=False)
1091
+
1092
+ # Initialize weights and apply final processing
1093
+ self.post_init()
1094
+
1095
+ def get_input_embeddings(self):
1096
+ return self.model.embed_tokens
1097
+
1098
+ def set_input_embeddings(self, value):
1099
+ self.model.embed_tokens = value
1100
+
1101
+ def get_output_embeddings(self):
1102
+ return self.lm_head
1103
+
1104
+ def set_output_embeddings(self, new_embeddings):
1105
+ self.lm_head = new_embeddings
1106
+
1107
+ def set_decoder(self, decoder):
1108
+ self.model = decoder
1109
+
1110
+ def get_decoder(self):
1111
+ return self.model
1112
+
1113
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1114
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1115
+ def forward(
1116
+ self,
1117
+ input_ids: torch.LongTensor = None,
1118
+ attention_mask: Optional[torch.Tensor] = None,
1119
+ position_ids: Optional[torch.LongTensor] = None,
1120
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1121
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1122
+ labels: Optional[torch.LongTensor] = None,
1123
+ use_cache: Optional[bool] = None,
1124
+ output_attentions: Optional[bool] = None,
1125
+ output_hidden_states: Optional[bool] = None,
1126
+ return_dict: Optional[bool] = None,
1127
+ cache_position: Optional[torch.LongTensor] = None,
1128
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1129
+ r"""
1130
+ Args:
1131
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1132
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1133
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1134
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1135
+
1136
+ Returns:
1137
+
1138
+ Example:
1139
+
1140
+ ```python
1141
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
1142
+
1143
+ >>> model = Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1144
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1145
+
1146
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1147
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1148
+
1149
+ >>> # Generate
1150
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1151
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1152
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1153
+ ```"""
1154
+
1155
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1156
+ output_hidden_states = (
1157
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1158
+ )
1159
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1160
+
1161
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1162
+ outputs = self.model(
1163
+ input_ids=input_ids,
1164
+ attention_mask=attention_mask,
1165
+ position_ids=position_ids,
1166
+ past_key_values=past_key_values,
1167
+ inputs_embeds=inputs_embeds,
1168
+ use_cache=use_cache,
1169
+ output_attentions=output_attentions,
1170
+ output_hidden_states=output_hidden_states,
1171
+ return_dict=return_dict,
1172
+ cache_position=cache_position,
1173
+ )
1174
+
1175
+ hidden_states = outputs[0]
1176
+ logits = self.lm_head(hidden_states)
1177
+ logits = logits.float()
1178
+
1179
+ loss = None
1180
+ if labels is not None:
1181
+ # Shift so that tokens < n predict n
1182
+ shift_logits = logits[..., :-1, :].contiguous()
1183
+ shift_labels = labels[..., 1:].contiguous()
1184
+ # Flatten the tokens
1185
+ loss_fct = CrossEntropyLoss()
1186
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1187
+ shift_labels = shift_labels.view(-1)
1188
+ # Enable model parallelism
1189
+ shift_labels = shift_labels.to(shift_logits.device)
1190
+ loss = loss_fct(shift_logits, shift_labels)
1191
+
1192
+ if not return_dict:
1193
+ output = (logits,) + outputs[1:]
1194
+ return (loss,) + output if loss is not None else output
1195
+
1196
+ return CausalLMOutputWithPast(
1197
+ loss=loss,
1198
+ logits=logits,
1199
+ past_key_values=outputs.past_key_values,
1200
+ hidden_states=outputs.hidden_states,
1201
+ attentions=outputs.attentions,
1202
+ )
1203
+
1204
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.prepare_inputs_for_generation
1205
+ def prepare_inputs_for_generation(
1206
+ self,
1207
+ input_ids,
1208
+ past_key_values=None,
1209
+ attention_mask=None,
1210
+ inputs_embeds=None,
1211
+ cache_position=None,
1212
+ position_ids=None,
1213
+ use_cache=True,
1214
+ **kwargs,
1215
+ ):
1216
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1217
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1218
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1219
+ if past_key_values is not None:
1220
+ if inputs_embeds is not None: # Exception 1
1221
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1222
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1223
+ input_ids = input_ids[:, cache_position]
1224
+
1225
+ if attention_mask is not None and position_ids is None:
1226
+ # create position_ids on the fly for batch generation
1227
+ position_ids = attention_mask.long().cumsum(-1) - 1
1228
+ position_ids.masked_fill_(attention_mask == 0, 1)
1229
+ if past_key_values:
1230
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1231
+
1232
+ # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1233
+ position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1234
+
1235
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1236
+ if inputs_embeds is not None and cache_position[0] == 0:
1237
+ model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
1238
+ else:
1239
+ # The clone here is for the same reason as for `position_ids`.
1240
+ model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
1241
+
1242
+ if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1243
+ if model_inputs["inputs_embeds"] is not None:
1244
+ batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
1245
+ device = model_inputs["inputs_embeds"].device
1246
+ else:
1247
+ batch_size, sequence_length = model_inputs["input_ids"].shape
1248
+ device = model_inputs["input_ids"].device
1249
+
1250
+ dtype = self.lm_head.weight.dtype
1251
+ min_dtype = torch.finfo(dtype).min
1252
+
1253
+ attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1254
+ attention_mask,
1255
+ sequence_length=sequence_length,
1256
+ target_length=past_key_values.get_max_length(),
1257
+ dtype=dtype,
1258
+ device=device,
1259
+ min_dtype=min_dtype,
1260
+ cache_position=cache_position,
1261
+ batch_size=batch_size,
1262
+ )
1263
+
1264
+ model_inputs.update(
1265
+ {
1266
+ "position_ids": position_ids,
1267
+ "cache_position": cache_position,
1268
+ "past_key_values": past_key_values,
1269
+ "use_cache": use_cache,
1270
+ "attention_mask": attention_mask,
1271
+ }
1272
+ )
1273
+ return model_inputs
1274
+
1275
+
1276
+ @add_start_docstrings(
1277
+ """
1278
+ The Qwen2 Model transformer with a sequence classification head on top (linear layer).
1279
+
1280
+ [`Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1281
+ (e.g. GPT-2) do.
1282
+
1283
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1284
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1285
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1286
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1287
+ each row of the batch).
1288
+ """,
1289
+ QWEN2_START_DOCSTRING,
1290
+ )
1291
+ class Qwen2ForSequenceClassification(Qwen2PreTrainedModel):
1292
+ def __init__(self, config):
1293
+ super().__init__(config)
1294
+ self.num_labels = config.num_labels
1295
+ self.model = Qwen2Model(config)
1296
+ self.score = nn.Linear(config.ori_hidden_size, self.num_labels, bias=False)
1297
+
1298
+ # Initialize weights and apply final processing
1299
+ self.post_init()
1300
+
1301
+ def get_input_embeddings(self):
1302
+ return self.model.embed_tokens
1303
+
1304
+ def set_input_embeddings(self, value):
1305
+ self.model.embed_tokens = value
1306
+
1307
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1308
+ def forward(
1309
+ self,
1310
+ input_ids: torch.LongTensor = None,
1311
+ attention_mask: Optional[torch.Tensor] = None,
1312
+ position_ids: Optional[torch.LongTensor] = None,
1313
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1314
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1315
+ labels: Optional[torch.LongTensor] = None,
1316
+ use_cache: Optional[bool] = None,
1317
+ output_attentions: Optional[bool] = None,
1318
+ output_hidden_states: Optional[bool] = None,
1319
+ return_dict: Optional[bool] = None,
1320
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1321
+ r"""
1322
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1323
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1324
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1325
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1326
+ """
1327
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1328
+
1329
+ transformer_outputs = self.model(
1330
+ input_ids,
1331
+ attention_mask=attention_mask,
1332
+ position_ids=position_ids,
1333
+ past_key_values=past_key_values,
1334
+ inputs_embeds=inputs_embeds,
1335
+ use_cache=use_cache,
1336
+ output_attentions=output_attentions,
1337
+ output_hidden_states=output_hidden_states,
1338
+ return_dict=return_dict,
1339
+ )
1340
+ hidden_states = transformer_outputs[0]
1341
+ logits = self.score(hidden_states)
1342
+
1343
+ if input_ids is not None:
1344
+ batch_size = input_ids.shape[0]
1345
+ else:
1346
+ batch_size = inputs_embeds.shape[0]
1347
+
1348
+ if self.config.pad_token_id is None and batch_size != 1:
1349
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1350
+ if self.config.pad_token_id is None:
1351
+ sequence_lengths = -1
1352
+ else:
1353
+ if input_ids is not None:
1354
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1355
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1356
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1357
+ sequence_lengths = sequence_lengths.to(logits.device)
1358
+ else:
1359
+ sequence_lengths = -1
1360
+
1361
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1362
+
1363
+ loss = None
1364
+ if labels is not None:
1365
+ labels = labels.to(logits.device)
1366
+ if self.config.problem_type is None:
1367
+ if self.num_labels == 1:
1368
+ self.config.problem_type = "regression"
1369
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1370
+ self.config.problem_type = "single_label_classification"
1371
+ else:
1372
+ self.config.problem_type = "multi_label_classification"
1373
+
1374
+ if self.config.problem_type == "regression":
1375
+ loss_fct = MSELoss()
1376
+ if self.num_labels == 1:
1377
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1378
+ else:
1379
+ loss = loss_fct(pooled_logits, labels)
1380
+ elif self.config.problem_type == "single_label_classification":
1381
+ loss_fct = CrossEntropyLoss()
1382
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1383
+ elif self.config.problem_type == "multi_label_classification":
1384
+ loss_fct = BCEWithLogitsLoss()
1385
+ loss = loss_fct(pooled_logits, labels)
1386
+ if not return_dict:
1387
+ output = (pooled_logits,) + transformer_outputs[1:]
1388
+ return ((loss,) + output) if loss is not None else output
1389
+
1390
+ return SequenceClassifierOutputWithPast(
1391
+ loss=loss,
1392
+ logits=pooled_logits,
1393
+ past_key_values=transformer_outputs.past_key_values,
1394
+ hidden_states=transformer_outputs.hidden_states,
1395
+ attentions=transformer_outputs.attentions,
1396
+ )
1397
+
1398
+
1399
+ @add_start_docstrings(
1400
+ """
1401
+ The Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1402
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1403
+ """,
1404
+ QWEN2_START_DOCSTRING,
1405
+ )
1406
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->Qwen2, LLAMA->QWEN2
1407
+ class Qwen2ForTokenClassification(Qwen2PreTrainedModel):
1408
+ def __init__(self, config):
1409
+ super().__init__(config)
1410
+ self.num_labels = config.num_labels
1411
+ self.model = Qwen2Model(config)
1412
+ if getattr(config, "classifier_dropout", None) is not None:
1413
+ classifier_dropout = config.classifier_dropout
1414
+ elif getattr(config, "hidden_dropout", None) is not None:
1415
+ classifier_dropout = config.hidden_dropout
1416
+ else:
1417
+ classifier_dropout = 0.1
1418
+ self.dropout = nn.Dropout(classifier_dropout)
1419
+ self.score = nn.Linear(config.ori_hidden_size, config.num_labels)
1420
+
1421
+ # Initialize weights and apply final processing
1422
+ self.post_init()
1423
+
1424
+ def get_input_embeddings(self):
1425
+ return self.model.embed_tokens
1426
+
1427
+ def set_input_embeddings(self, value):
1428
+ self.model.embed_tokens = value
1429
+
1430
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
1431
+ def forward(
1432
+ self,
1433
+ input_ids: Optional[torch.LongTensor] = None,
1434
+ attention_mask: Optional[torch.Tensor] = None,
1435
+ position_ids: Optional[torch.LongTensor] = None,
1436
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1437
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1438
+ labels: Optional[torch.LongTensor] = None,
1439
+ use_cache: Optional[bool] = None,
1440
+ output_attentions: Optional[bool] = None,
1441
+ output_hidden_states: Optional[bool] = None,
1442
+ return_dict: Optional[bool] = None,
1443
+ ) -> Union[Tuple, TokenClassifierOutput]:
1444
+ r"""
1445
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1446
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1447
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1448
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1449
+ """
1450
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1451
+
1452
+ outputs = self.model(
1453
+ input_ids,
1454
+ attention_mask=attention_mask,
1455
+ position_ids=position_ids,
1456
+ past_key_values=past_key_values,
1457
+ inputs_embeds=inputs_embeds,
1458
+ use_cache=use_cache,
1459
+ output_attentions=output_attentions,
1460
+ output_hidden_states=output_hidden_states,
1461
+ return_dict=return_dict,
1462
+ )
1463
+ sequence_output = outputs[0]
1464
+ sequence_output = self.dropout(sequence_output)
1465
+ logits = self.score(sequence_output)
1466
+
1467
+ loss = None
1468
+ if labels is not None:
1469
+ loss_fct = CrossEntropyLoss()
1470
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1471
+
1472
+ if not return_dict:
1473
+ output = (logits,) + outputs[2:]
1474
+ return ((loss,) + output) if loss is not None else output
1475
+
1476
+ return TokenClassifierOutput(
1477
+ loss=loss,
1478
+ logits=logits,
1479
+ hidden_states=outputs.hidden_states,
1480
+ attentions=outputs.attentions,
1481
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "eos_token": {
7
+ "content": "<|im_end|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "pad_token": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ }
20
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "106152": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "106153": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "106154": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ }
28
+ },
29
+ "additional_special_tokens": [
30
+ "<|im_start|>",
31
+ "<|im_end|>"
32
+ ],
33
+ "bos_token": null,
34
+ "chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
35
+ "clean_up_tokenization_spaces": false,
36
+ "eos_token": "<|im_end|>",
37
+ "errors": "replace",
38
+ "max_length": 1024,
39
+ "model_max_length": 131072,
40
+ "pad_token": "<|endoftext|>",
41
+ "split_special_tokens": false,
42
+ "stride": 0,
43
+ "tokenizer_class": "Qwen2Tokenizer",
44
+ "truncation_side": "right",
45
+ "truncation_strategy": "longest_first",
46
+ "unk_token": null
47
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff