Erin Ho commited on
Commit
e440269
·
1 Parent(s): 4240d46

upload model

Browse files

Signed-off-by: Erin Ho <14718778+hchings@users.noreply.github.com>

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