vermouthdky commited on
Commit
d954ef7
·
verified ·
1 Parent(s): 35f90e5

Upload folder using huggingface_hub

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