harrisonvanderbyl commited on
Commit
0746d13
·
verified ·
1 Parent(s): 3466c95

Upload 10 files

Browse files
README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: transformers
4
+ ---
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "RWKV6Qwen2ForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_rwkv6qwen2.RWKV6Qwen2Config",
7
+ "AutoModelForCausalLM": "modeling_rwkv6qwen2.RWKV6Qwen2ForCausalLM"
8
+ },
9
+ "attention_bias": true,
10
+ "attention_dropout": 0.0,
11
+ "attention_output_bias": false,
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151643,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 5120,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 27648,
18
+ "lora_rank_decay": 128,
19
+ "max_position_embeddings": 131072,
20
+ "max_window_layers": 64,
21
+ "model_type": "rwkv6qwen2",
22
+ "num_attention_heads": 40,
23
+ "num_hidden_layers": 64,
24
+ "num_key_value_heads": 8,
25
+ "rms_norm_eps": 1e-05,
26
+ "rope_theta": 1000000.0,
27
+ "sliding_window": 131072,
28
+ "tie_word_embeddings": false,
29
+ "torch_dtype": "bfloat16",
30
+ "transformers_version": "4.43.1",
31
+ "use_cache": true,
32
+ "use_sliding_window": false,
33
+ "vocab_size": 152064
34
+ }
configuration_rwkv6qwen2.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """RWKV6Qwen2 model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.modeling_rope_utils import rope_config_validation
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class RWKV6Qwen2Config(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`RWKV6Qwen2Model`]. It is used to instantiate a
28
+ RWKV6Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of
30
+ Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 151936):
38
+ Vocabulary size of the RWKV6Qwen2 model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`RWKV6Qwen2Model`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 22016):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 32):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
58
+ The maximum sequence length that this model might ever be used with.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
65
+ relevant if `config.is_decoder=True`.
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
+ Whether the model's input and output word embeddings should be tied.
68
+ rope_theta (`float`, *optional*, defaults to 10000.0):
69
+ The base period of the RoPE embeddings.
70
+ rope_scaling (`Dict`, *optional*):
71
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
72
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
73
+ accordingly.
74
+ Expected contents:
75
+ `rope_type` (`str`):
76
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
77
+ 'llama3'], with 'default' being the original RoPE implementation.
78
+ `factor` (`float`, *optional*):
79
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
80
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
81
+ original maximum pre-trained length.
82
+ `original_max_position_embeddings` (`int`, *optional*):
83
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
84
+ pretraining.
85
+ `attention_factor` (`float`, *optional*):
86
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
87
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
88
+ `factor` field to infer the suggested value.
89
+ `beta_fast` (`float`, *optional*):
90
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
91
+ ramp function. If unspecified, it defaults to 32.
92
+ `beta_slow` (`float`, *optional*):
93
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
94
+ ramp function. If unspecified, it defaults to 1.
95
+ `short_factor` (`List[float]`, *optional*):
96
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
97
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
+ size divided by the number of attention heads divided by 2
99
+ `long_factor` (`List[float]`, *optional*):
100
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
101
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
+ size divided by the number of attention heads divided by 2
103
+ `low_freq_factor` (`float`, *optional*):
104
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
105
+ `high_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
107
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
108
+ Whether to use sliding window attention.
109
+ sliding_window (`int`, *optional*, defaults to 4096):
110
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
111
+ max_window_layers (`int`, *optional*, defaults to 28):
112
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
113
+ attention_dropout (`float`, *optional*, defaults to 0.0):
114
+ The dropout ratio for the attention probabilities.
115
+
116
+ ```python
117
+ >>> from transformers import RWKV6Qwen2Model, RWKV6Qwen2Config
118
+
119
+ >>> # Initializing a RWKV6Qwen2 style configuration
120
+ >>> configuration = RWKV6Qwen2Config()
121
+
122
+ >>> # Initializing a model from the RWKV6Qwen2-7B style configuration
123
+ >>> model = RWKV6Qwen2Model(configuration)
124
+
125
+ >>> # Accessing the model configuration
126
+ >>> configuration = model.config
127
+ ```"""
128
+
129
+ model_type = "rwkv6qwen2"
130
+ keys_to_ignore_at_inference = ["past_key_values"]
131
+
132
+ def __init__(
133
+ self,
134
+ vocab_size=151936,
135
+ hidden_size=4096,
136
+ intermediate_size=22016,
137
+ num_hidden_layers=32,
138
+ num_attention_heads=32,
139
+ num_key_value_heads=32,
140
+ lora_rank_decay=None,
141
+ hidden_act="silu",
142
+ max_position_embeddings=32768,
143
+ initializer_range=0.02,
144
+ rms_norm_eps=1e-6,
145
+ use_cache=True,
146
+ tie_word_embeddings=False,
147
+ rope_theta=10000.0,
148
+ rope_scaling=None,
149
+ use_sliding_window=False,
150
+ sliding_window=4096,
151
+ max_window_layers=28,
152
+ attention_dropout=0.0,
153
+ attention_bias=True,
154
+ attention_output_bias=False,
155
+ **kwargs,
156
+ ):
157
+ self.vocab_size = vocab_size
158
+ self.max_position_embeddings = max_position_embeddings
159
+ self.hidden_size = hidden_size
160
+ self.intermediate_size = intermediate_size
161
+ self.num_hidden_layers = num_hidden_layers
162
+ self.num_attention_heads = num_attention_heads
163
+ self.use_sliding_window = use_sliding_window
164
+ self.sliding_window = sliding_window if use_sliding_window else None
165
+ self.max_window_layers = max_window_layers
166
+
167
+ # for backward compatibility
168
+ if num_key_value_heads is None:
169
+ num_key_value_heads = num_attention_heads
170
+
171
+ self.num_key_value_heads = num_key_value_heads
172
+ self.lora_rank_decay = lora_rank_decay
173
+ self.hidden_act = hidden_act
174
+ self.initializer_range = initializer_range
175
+ self.rms_norm_eps = rms_norm_eps
176
+ self.use_cache = use_cache
177
+ self.rope_theta = rope_theta
178
+ self.rope_scaling = rope_scaling
179
+ self.attention_dropout = attention_dropout
180
+ # Validate the correctness of rotary position embeddings parameters
181
+ # BC: if there is a 'type' field, move it to 'rope_type'.
182
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
183
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
184
+ rope_config_validation(self)
185
+
186
+ self.attention_bias = attention_bias
187
+ self.attention_output_bias = attention_output_bias
188
+
189
+ super().__init__(
190
+ tie_word_embeddings=tie_word_embeddings,
191
+ **kwargs,
192
+ )
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "pad_token_id": 151643,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 151645,
7
+ 151643
8
+ ],
9
+ "repetition_penalty": 1.05,
10
+ "temperature": 0.7,
11
+ "top_p": 0.8,
12
+ "top_k": 20,
13
+ "transformers_version": "4.37.0"
14
+ }
gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
modeling_rwkv6qwen2.py ADDED
@@ -0,0 +1,1255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 RWKV6Qwen2 model."""
21
+
22
+ import math
23
+ import inspect
24
+ from typing import List, Optional, Tuple, Union, Dict, Any
25
+
26
+ import torch
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ import torch.nn.functional as F
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.cache_utils import Cache, StaticCache, DynamicCache
33
+ from transformers.generation import GenerationMixin
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.utils import (
43
+ add_code_sample_docstrings,
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_2_available,
47
+ is_flash_attn_greater_or_equal_2_10,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from .configuration_rwkv6qwen2 import RWKV6Qwen2Config
52
+
53
+ from transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer, Qwen2MLP, Qwen2RMSNorm, repeat_kv
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ _CHECKPOINT_FOR_DOC = "RWKV/RWKV6Qwen2-7B"
59
+ _CONFIG_FOR_DOC = "RWKV6Qwen2Config"
60
+
61
+ class RWKV6State(Cache):
62
+ def __init__(self) -> None:
63
+ super().__init__()
64
+ self._seen_tokens = 0 # Used in `generate` to keep tally of how many tokens the cache has seen
65
+ self.layer_kv_states: List[torch.Tensor] = []
66
+ self.layer_shift_states: List[torch.Tensor] = []
67
+
68
+ def __getitem__(self, layer_idx: int) -> Tuple[torch.Tensor, torch.Tensor]:
69
+ """
70
+ Support for backwards-compatible `past_key_value` indexing, e.g. `past_key_value[0][0].shape[2]` to get the
71
+ sequence length.
72
+ """
73
+ if layer_idx < len(self):
74
+ return (self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx])
75
+ else:
76
+ raise KeyError(f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}")
77
+
78
+ def __iter__(self):
79
+ """
80
+ Support for backwards-compatible `past_key_value` iteration, e.g. `for x in past_key_value:` to iterate over
81
+ keys and values
82
+ """
83
+ for layer_idx in range(len(self)):
84
+ yield (self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx])
85
+
86
+ def __len__(self):
87
+ """
88
+ Support for backwards-compatible `past_key_value` length, e.g. `len(past_key_value)`. This value corresponds
89
+ to the number of layers in the model.
90
+ """
91
+ return len(self.layer_kv_states)
92
+
93
+ def get_usable_length(self, new_seq_length: int, layer_idx: Optional[int] = 0) -> int:
94
+ """Given the sequence length of the new inputs, returns the usable length of the cache."""
95
+ # Linear Attention variants do not have a maximum length
96
+ return new_seq_length
97
+
98
+ def reorder_cache(self, beam_idx: torch.LongTensor):
99
+ """Reorders the cache for beam search, given the selected beam indices."""
100
+ raise NotImplementedError('Cannot reorder Linear Attention state')
101
+
102
+ def get_seq_length(self, layer_idx: int = 0) -> int:
103
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
104
+ return self._seen_tokens
105
+
106
+ def get_max_cache_shape(self) -> Optional[int]:
107
+ """Returns the maximum sequence length of the cache object. DynamicCache does not have a maximum length."""
108
+ return None
109
+
110
+ def get_max_length(self) -> Optional[int]:
111
+ """
112
+ Returns the maximum sequence length of the cached states. DynamicCache does not have a maximum length.
113
+ """
114
+ return None
115
+
116
+ # def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
117
+ # """Converts the `DynamicCache` instance into the its equivalent in the legacy cache format. Used for
118
+ # backward compatibility."""
119
+ # legacy_cache = ()
120
+ # for layer_idx in range(len(self)):
121
+ # legacy_cache += ((self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx]),)
122
+ # return legacy_cache
123
+
124
+ # @classmethod
125
+ # #@deprecate_kwarg("num_hidden_layers", version="4.47.0")
126
+ # def from_legacy_cache(
127
+ # cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor, torch.FloatTensor]]] = None, num_hidden_layers: int | None = None
128
+ # ) -> "RWKV6State":
129
+ # """Converts a cache in the legacy cache format into an equivalent `DynamicCache`. Used for
130
+ # backward compatibility."""
131
+ # cache = cls()
132
+ # if past_key_values is not None:
133
+ # for layer_idx in range(len(past_key_values)):
134
+ # layer_kv_state, layer_shift_state = past_key_values[layer_idx]
135
+ # cache.update(layer_kv_state, layer_shift_state, layer_idx)
136
+ # return cache
137
+
138
+ def crop(self, max_length: int):
139
+ # can't implement this for linear attention variants
140
+ return
141
+
142
+ @torch.no_grad
143
+ def update(
144
+ self,
145
+ kv_state: torch.Tensor,
146
+ shift_state: torch.Tensor,
147
+ token_count: int,
148
+ layer_idx: int,
149
+ cache_kwargs: Optional[Dict[str, Any]] = None,
150
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
151
+ # Update the number of seen tokens
152
+ if layer_idx == 0:
153
+ self._seen_tokens += token_count
154
+
155
+ # Update the cache
156
+ # There may be skipped layers, fill them with empty lists
157
+ for _ in range(len(self.layer_kv_states), layer_idx + 1):
158
+ self.layer_kv_states.append(torch.zeros_like(kv_state).requires_grad_(False))
159
+ self.layer_shift_states.append(torch.zeros_like(shift_state).requires_grad_(False))
160
+ self.layer_kv_states[layer_idx].copy_(kv_state)
161
+ self.layer_shift_states[layer_idx].copy_(shift_state)
162
+
163
+ return self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx]
164
+
165
+ # @deprecate_kwarg("num_hidden_layers", version="4.47.0")
166
+ # def batch_split(
167
+ # self, full_batch_size: int, split_size: int, num_hidden_layers: int = None
168
+ # ) -> List["DynamicCache"]:
169
+ # """Split the current instance into a list of `DynamicCache` by the batch size. This will be used by
170
+ # `_split_model_inputs()` in `generation.utils`"""
171
+ # out = []
172
+ # for i in range(0, full_batch_size, split_size):
173
+ # current_split = DynamicCache()
174
+ # current_split._seen_tokens = self._seen_tokens
175
+ # current_split.key_cache = [tensor[i : i + split_size] for tensor in self.key_cache]
176
+ # current_split.value_cache = [tensor[i : i + split_size] for tensor in self.value_cache]
177
+ # out.append(current_split)
178
+ # return out
179
+
180
+ # @classmethod
181
+ # @deprecate_kwarg("num_hidden_layers", version="4.47.0")
182
+ # def from_batch_splits(cls, splits: List["DynamicCache"], num_hidden_layers: int = None) -> "DynamicCache":
183
+ # """This is the opposite of the above `batch_split()` method. This will be used by `stack_model_outputs` in
184
+ # `generation.utils`"""
185
+ # cache = cls()
186
+ # for idx in range(len(splits[0])):
187
+ # key_cache = [current.key_cache[idx] for current in splits if current.key_cache[idx] != []]
188
+ # value_cache = [current.key_cache[idx] for current in splits if current.key_cache[idx] != []]
189
+ # if key_cache != []:
190
+ # layer_keys = torch.cat(key_cache, dim=0)
191
+ # layer_values = torch.cat(value_cache, dim=0)
192
+ # cache.update(layer_keys, layer_values, idx)
193
+ # return cache
194
+
195
+ # def batch_repeat_interleave(self, repeats: int):
196
+ # """Repeat the cache `repeats` times in the batch dimension. Used in contrastive search."""
197
+ # for layer_idx in range(len(self)):
198
+ # self.key_cache[layer_idx] = self.key_cache[layer_idx].repeat_interleave(repeats, dim=0)
199
+ # self.value_cache[layer_idx] = self.value_cache[layer_idx].repeat_interleave(repeats, dim=0)
200
+
201
+ # def batch_select_indices(self, indices: torch.Tensor):
202
+ # """Only keep the `indices` in the batch dimension of the cache. Used in contrastive search."""
203
+ # for layer_idx in range(len(self)):
204
+ # self.key_cache[layer_idx] = self.key_cache[layer_idx][indices, ...]
205
+ # self.value_cache[layer_idx] = self.value_cache[layer_idx][indices, ...]
206
+
207
+ try:
208
+ #from fla.ops.gla.chunk import chunk_gla
209
+ from fla.ops.gla.fused_recurrent import fused_recurrent_gla
210
+ except ImportError:
211
+ print("Required module is not installed. Please install it using the following commands:")
212
+ print("pip install -U git+https://github.com/fla-org/flash-linear-attention")
213
+ print("Additionally, ensure you have at least version 2.2.0 of Triton installed:")
214
+ print("pip install triton>=2.2.0")
215
+
216
+ class RWKV6Attention(nn.Module):
217
+ def __init__(self, config, layer_idx: Optional[int] = None):
218
+ super().__init__()
219
+ self.config = config
220
+ self.layer_idx = layer_idx
221
+ if layer_idx is None:
222
+ logger.warning_once(
223
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
224
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
225
+ "when creating this class."
226
+ )
227
+
228
+ self.hidden_size = config.hidden_size
229
+ self.num_heads = config.num_attention_heads
230
+ self.head_dim = getattr(config, 'head_dim', self.hidden_size // self.num_heads)
231
+ self.num_key_value_heads = config.num_key_value_heads
232
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
233
+ self.attention_dropout = config.attention_dropout
234
+
235
+ if self.hidden_size % self.num_heads != 0:
236
+ raise ValueError(
237
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
238
+ f" and `num_heads`: {self.num_heads})."
239
+ )
240
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
241
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
242
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
243
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=getattr(config, 'attention_output_bias', config.attention_bias))
244
+
245
+ self.gate = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
246
+ nn.init.zeros_(self.gate.weight)
247
+
248
+ n_layer = self.config.num_hidden_layers
249
+ n_embd = self.hidden_size
250
+ dim_att = self.num_heads * self.head_dim
251
+ layer_id = self.layer_idx
252
+
253
+ with torch.no_grad():
254
+ ratio_0_to_1 = layer_id / (n_layer - 1) # 0 to 1
255
+ ratio_1_to_almost0 = 1.0 - (layer_id / n_layer) # 1 to ~0
256
+ ddd = torch.ones(1, 1, n_embd)
257
+ for i in range(n_embd):
258
+ ddd[0, 0, i] = i / n_embd
259
+
260
+ ddd = torch.zeros(1, 1, n_embd)
261
+ self.time_maa_x = nn.Parameter(1.0 - torch.pow(ddd, ratio_1_to_almost0))
262
+ self.time_maa_r = nn.Parameter(torch.zeros_like(ddd))
263
+ self.time_maa_k = nn.Parameter(torch.zeros_like(ddd))
264
+ self.time_maa_v = nn.Parameter(torch.zeros_like(ddd))
265
+ self.time_maa_w = nn.Parameter(torch.zeros_like(ddd))
266
+ self.time_maa_g = nn.Parameter(torch.zeros_like(ddd))
267
+
268
+ lora_rank_decay = config.lora_rank_decay or (32 if n_embd < 4096 else 64)
269
+ self.time_maa_w2 = nn.Parameter(torch.zeros(5, lora_rank_decay, n_embd).uniform_(-0.01, 0.01))
270
+ self.time_maa_w1 = nn.Parameter(torch.zeros(n_embd, lora_rank_decay*self.time_maa_w2.size(0)))
271
+
272
+ # RWKV-6
273
+ decay_speed = torch.ones(dim_att)
274
+ for n in range(dim_att):
275
+ decay_speed[n] = -6 + 5 * (n / (dim_att - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
276
+ self.time_decay = nn.Parameter(decay_speed.reshape(1,1,dim_att))
277
+ D_DECAY_LORA = 64 if n_embd < 4096 else 128
278
+ self.time_decay_w1 = nn.Parameter(torch.zeros(n_embd, D_DECAY_LORA))
279
+ self.time_decay_w2 = nn.Parameter(torch.zeros(D_DECAY_LORA, dim_att).uniform_(-0.01, 0.01))
280
+
281
+ def forward(
282
+ self,
283
+ hidden_states: torch.Tensor,
284
+ attention_mask: Optional[torch.Tensor] = None,
285
+ position_ids: Optional[torch.LongTensor] = None,
286
+ past_key_values: Optional[RWKV6State] = None,
287
+ output_attentions: bool = False,
288
+ use_cache: bool = False,
289
+ cache_position: Optional[torch.LongTensor] = None,
290
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
291
+ ):
292
+ output_shift_state = hidden_states[:, -1:].detach().clone()
293
+
294
+ bsz, q_len, hidden_dim = hidden_states.size()
295
+ H = self.num_heads
296
+
297
+ x = hidden_states
298
+
299
+ if use_cache and past_key_values is not None and len(past_key_values) > self.layer_idx:
300
+ input_kv_state, input_shift_state = past_key_values[self.layer_idx]
301
+ xprev = torch.cat([input_shift_state, x[:, :-1]], dim=1)
302
+ else:
303
+ input_kv_state = None
304
+ xprev = F.pad(x, (0, 0, 1, -1))
305
+
306
+ dxprev = xprev - x
307
+
308
+ xxx = x + dxprev * self.time_maa_x
309
+ xxx = torch.tanh(xxx @ self.time_maa_w1).view(bsz*q_len, self.time_maa_w2.size(0), -1).transpose(0, 1)
310
+ xxx = torch.bmm(xxx, self.time_maa_w2).view(self.time_maa_w2.size(0), bsz, q_len, hidden_dim)
311
+
312
+ mr, mk, mv, mw, mg = xxx.unbind(dim=0)
313
+ xr = x + dxprev * (self.time_maa_r + mr)
314
+ xk = x + dxprev * (self.time_maa_k + mk)
315
+ xv = x + dxprev * (self.time_maa_v + mv)
316
+ xw = x + dxprev * (self.time_maa_w + mw)
317
+ xg = x + dxprev * (self.time_maa_g + mg)
318
+
319
+ query_states = self.q_proj(xr)
320
+ key_states = self.k_proj(xk)
321
+ value_states = self.v_proj(xv)
322
+ decay_states = (self.time_decay + torch.tanh(xw @ self.time_decay_w1) @ self.time_decay_w2).to(query_states.dtype)
323
+ gate_states = F.sigmoid(self.gate(xg))
324
+
325
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
326
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
327
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
328
+ decay_states = decay_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
329
+
330
+ # repeat k/v heads if n_kv_heads < n_heads
331
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
332
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
333
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
334
+
335
+ decay_states_log = -decay_states.float().exp()
336
+ decay_states_log = decay_states_log.clamp(-5) # FIXME - is this necessary?
337
+ key_states = (key_states * (1 - decay_states_log.exp())).to(key_states.dtype)
338
+
339
+ # dealing with left-padding
340
+ if attention_mask is not None:
341
+ value_states = value_states * attention_mask[:, None, -value_states.shape[-2]:, None]
342
+
343
+ query_states = query_states.to(value_states.dtype)
344
+ key_states = key_states.to(value_states.dtype)
345
+
346
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
347
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
348
+ # cast them back in float16 just to be sure everything works as expected.
349
+ input_dtype = query_states.dtype
350
+ if input_dtype == torch.float32:
351
+ if torch.is_autocast_enabled():
352
+ target_dtype = torch.get_autocast_gpu_dtype()
353
+ # Handle the case where the model is quantized
354
+ elif hasattr(self.config, "_pre_quantization_dtype"):
355
+ target_dtype = self.config._pre_quantization_dtype
356
+ else:
357
+ target_dtype = self.q_proj.weight.dtype
358
+
359
+ logger.warning_once(
360
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
361
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
362
+ f" {target_dtype}."
363
+ )
364
+
365
+ query_states = query_states.to(target_dtype)
366
+ key_states = key_states.to(target_dtype)
367
+ value_states = value_states.to(target_dtype)
368
+
369
+ attn_weights = torch.empty(0, device=x.device)
370
+
371
+ scale = query_states.shape[-1] ** -0.5
372
+ output_final_state = not self.training and use_cache and past_key_values is not None
373
+ #attn_output, output_kv_state = ChunkGLAFunction.apply(query_states, key_states, value_states, decay_states_log.float(), scale, input_kv_state, output_final_state)
374
+ #attn_output, output_kv_state = chunk_gla(query_states, key_states, value_states, decay_states_log, scale, input_kv_state, output_final_state)
375
+ attn_output, output_kv_state = fused_recurrent_gla(query_states, key_states, value_states, decay_states_log, None, scale, input_kv_state, output_final_state)
376
+
377
+ if output_final_state:
378
+ past_key_values.update(output_kv_state, output_shift_state, q_len, self.layer_idx)
379
+
380
+ attn_output = attn_output.transpose(1, 2).contiguous()
381
+ attn_output = attn_output.view(bsz, q_len, -1)
382
+ attn_output = self.o_proj(attn_output * gate_states)
383
+
384
+ return attn_output, attn_weights
385
+
386
+ class RWKV6Qwen2DecoderLayer(Qwen2DecoderLayer):
387
+ def __init__(self, config: RWKV6Qwen2Config, layer_idx: int):
388
+ nn.Module.__init__(self)
389
+ self.hidden_size = config.hidden_size
390
+
391
+ self.self_attn = RWKV6Attention(config, layer_idx) #QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
392
+
393
+ self.mlp = Qwen2MLP(config)
394
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
395
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
396
+
397
+ def forward(
398
+ self,
399
+ hidden_states: torch.Tensor,
400
+ attention_mask: Optional[torch.Tensor] = None,
401
+ position_ids: Optional[torch.LongTensor] = None,
402
+ past_key_values: Optional[Cache] = None,
403
+ output_attentions: Optional[bool] = False,
404
+ use_cache: Optional[bool] = False,
405
+ cache_position: Optional[torch.LongTensor] = None,
406
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
407
+ **kwargs,
408
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
409
+ residual = hidden_states
410
+
411
+ hidden_states = self.input_layernorm(hidden_states)
412
+
413
+ # Self Attention
414
+ hidden_states, self_attn_weights = self.self_attn(
415
+ hidden_states=hidden_states,
416
+ attention_mask=attention_mask,
417
+ position_ids=position_ids,
418
+ past_key_values=past_key_values,
419
+ output_attentions=output_attentions,
420
+ use_cache=use_cache,
421
+ cache_position=cache_position,
422
+ position_embeddings=position_embeddings,
423
+ **kwargs,
424
+ )
425
+ hidden_states = residual + hidden_states
426
+
427
+ # Fully Connected
428
+ residual = hidden_states
429
+ hidden_states = self.post_attention_layernorm(hidden_states)
430
+ hidden_states = self.mlp(hidden_states)
431
+ hidden_states = residual + hidden_states
432
+
433
+ outputs = (hidden_states,)
434
+ if output_attentions:
435
+ outputs += (self_attn_weights,)
436
+
437
+ return outputs
438
+
439
+ RWKV6QWEN2_START_DOCSTRING = r"""
440
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
441
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
442
+ etc.)
443
+
444
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
445
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
446
+ and behavior.
447
+
448
+ Parameters:
449
+ config ([`RWKV6Qwen2Config`]):
450
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
451
+ load the weights associated with the model, only the configuration. Check out the
452
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
453
+ """
454
+
455
+
456
+ @add_start_docstrings(
457
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
458
+ RWKV6QWEN2_START_DOCSTRING,
459
+ )
460
+ class RWKV6Qwen2PreTrainedModel(PreTrainedModel):
461
+ config_class = RWKV6Qwen2Config
462
+ base_model_prefix = "model"
463
+ supports_gradient_checkpointing = True
464
+ _no_split_modules = ["RWKV6Qwen2DecoderLayer"]
465
+ _skip_keys_device_placement = "past_key_values"
466
+ _supports_flash_attn_2 = True
467
+ _supports_sdpa = True
468
+ _supports_cache_class = True
469
+ _supports_quantized_cache = True
470
+ _supports_static_cache = True
471
+
472
+ def _init_weights(self, module):
473
+ std = self.config.initializer_range
474
+ if isinstance(module, nn.Linear):
475
+ module.weight.data.normal_(mean=0.0, std=std)
476
+ if module.bias is not None:
477
+ module.bias.data.zero_()
478
+ elif isinstance(module, nn.Embedding):
479
+ module.weight.data.normal_(mean=0.0, std=std)
480
+ if module.padding_idx is not None:
481
+ module.weight.data[module.padding_idx].zero_()
482
+
483
+
484
+ RWKV6QWEN2_INPUTS_DOCSTRING = r"""
485
+ Args:
486
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
487
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
488
+ it.
489
+
490
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
491
+ [`PreTrainedTokenizer.__call__`] for details.
492
+
493
+ [What are input IDs?](../glossary#input-ids)
494
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
495
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
496
+
497
+ - 1 for tokens that are **not masked**,
498
+ - 0 for tokens that are **masked**.
499
+
500
+ [What are attention masks?](../glossary#attention-mask)
501
+
502
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
503
+ [`PreTrainedTokenizer.__call__`] for details.
504
+
505
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
506
+ `past_key_values`).
507
+
508
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
509
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
510
+ information on the default strategy.
511
+
512
+ - 1 indicates the head is **not masked**,
513
+ - 0 indicates the head is **masked**.
514
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
515
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
516
+ config.n_positions - 1]`.
517
+
518
+ [What are position IDs?](../glossary#position-ids)
519
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
520
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
521
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
522
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
523
+
524
+ Two formats are allowed:
525
+ - a [`~cache_utils.Cache`] instance, see our
526
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
527
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
528
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
529
+ cache format.
530
+
531
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
532
+ legacy cache format will be returned.
533
+
534
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
535
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
536
+ of shape `(batch_size, sequence_length)`.
537
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
538
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
539
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
540
+ model's internal embedding lookup matrix.
541
+ use_cache (`bool`, *optional*):
542
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
543
+ `past_key_values`).
544
+ output_attentions (`bool`, *optional*):
545
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
546
+ tensors for more detail.
547
+ output_hidden_states (`bool`, *optional*):
548
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
549
+ more detail.
550
+ return_dict (`bool`, *optional*):
551
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
552
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
553
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
554
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
555
+ the complete sequence length.
556
+ """
557
+
558
+ @add_start_docstrings(
559
+ "The bare RWKV6Qwen2 Model outputting raw hidden-states without any specific head on top.",
560
+ RWKV6QWEN2_START_DOCSTRING,
561
+ )
562
+ class RWKV6Qwen2Model(RWKV6Qwen2PreTrainedModel):
563
+ """
564
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
565
+
566
+ Args:
567
+ config: RWKV6Qwen2Config
568
+ """
569
+
570
+ def __init__(self, config: RWKV6Qwen2Config):
571
+ super().__init__(config)
572
+ self.padding_idx = config.pad_token_id
573
+ self.vocab_size = config.vocab_size
574
+
575
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
576
+ self.layers = nn.ModuleList(
577
+ [RWKV6Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
578
+ )
579
+ self._attn_implementation = config._attn_implementation
580
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
581
+ #self.rotary_emb = Qwen2RotaryEmbedding(config=config)
582
+
583
+ self.gradient_checkpointing = False
584
+ # Initialize weights and apply final processing
585
+ self.post_init()
586
+
587
+ def get_input_embeddings(self):
588
+ return self.embed_tokens
589
+
590
+ def set_input_embeddings(self, value):
591
+ self.embed_tokens = value
592
+
593
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
594
+ def forward(
595
+ self,
596
+ input_ids: torch.LongTensor = None,
597
+ attention_mask: Optional[torch.Tensor] = None,
598
+ position_ids: Optional[torch.LongTensor] = None,
599
+ past_key_values: Optional[Cache] = None,
600
+ inputs_embeds: Optional[torch.FloatTensor] = None,
601
+ use_cache: Optional[bool] = None,
602
+ output_attentions: Optional[bool] = None,
603
+ output_hidden_states: Optional[bool] = None,
604
+ return_dict: Optional[bool] = None,
605
+ cache_position: Optional[torch.LongTensor] = None,
606
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
607
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
608
+ output_hidden_states = (
609
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
610
+ )
611
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
612
+
613
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
614
+
615
+ if (input_ids is None) ^ (inputs_embeds is not None):
616
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
617
+
618
+ if self.gradient_checkpointing and self.training:
619
+ if use_cache:
620
+ logger.warning_once(
621
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
622
+ )
623
+ use_cache = False
624
+
625
+ # kept for BC (non `Cache` `past_key_values` inputs)
626
+ #return_legacy_cache = False
627
+ if use_cache and not isinstance(past_key_values, RWKV6State):
628
+ #return_legacy_cache = True
629
+ past_key_values = RWKV6State()
630
+ # if past_key_values is None:
631
+ # past_key_values = DynamicCache()
632
+ # else:
633
+ # past_key_values = DynamicCache.from_legacy_cache(past_key_values)
634
+ # logger.warning_once(
635
+ # "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
636
+ # "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
637
+ # "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
638
+ # )
639
+
640
+ if inputs_embeds is None:
641
+ inputs_embeds = self.embed_tokens(input_ids)
642
+
643
+ # if cache_position is None:
644
+ # past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
645
+ # cache_position = torch.arange(
646
+ # past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
647
+ # )
648
+ # if position_ids is None:
649
+ # position_ids = cache_position.unsqueeze(0)
650
+
651
+ # causal_mask = self._update_causal_mask(
652
+ # attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
653
+ # )
654
+
655
+ causal_mask = None
656
+
657
+ hidden_states = inputs_embeds
658
+
659
+ # create position embeddings to be shared across the decoder layers
660
+ position_embeddings = None #self.rotary_emb(hidden_states, position_ids)
661
+
662
+ # decoder layers
663
+ all_hidden_states = () if output_hidden_states else None
664
+ all_self_attns = () if output_attentions else None
665
+ next_decoder_cache = None
666
+
667
+ for decoder_layer in self.layers:
668
+ if output_hidden_states:
669
+ all_hidden_states += (hidden_states,)
670
+
671
+ if self.gradient_checkpointing and self.training:
672
+ layer_outputs = self._gradient_checkpointing_func(
673
+ decoder_layer.__call__,
674
+ hidden_states,
675
+ causal_mask,
676
+ position_ids,
677
+ past_key_values,
678
+ output_attentions,
679
+ use_cache,
680
+ cache_position,
681
+ position_embeddings,
682
+ )
683
+ else:
684
+ layer_outputs = decoder_layer(
685
+ hidden_states,
686
+ attention_mask=attention_mask,
687
+ position_ids=position_ids,
688
+ past_key_values=past_key_values,
689
+ output_attentions=output_attentions,
690
+ use_cache=use_cache,
691
+ cache_position=cache_position,
692
+ position_embeddings=position_embeddings,
693
+ )
694
+
695
+ hidden_states = layer_outputs[0]
696
+
697
+ if output_attentions:
698
+ all_self_attns += (layer_outputs[1],)
699
+
700
+ hidden_states = self.norm(hidden_states)
701
+
702
+ # add hidden states from the last decoder layer
703
+ if output_hidden_states:
704
+ all_hidden_states += (hidden_states,)
705
+
706
+ #if return_legacy_cache:
707
+ # next_cache = next_cache.to_legacy_cache()
708
+
709
+ if not return_dict:
710
+ return tuple(v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None)
711
+ return BaseModelOutputWithPast(
712
+ last_hidden_state=hidden_states,
713
+ past_key_values=past_key_values,
714
+ hidden_states=all_hidden_states,
715
+ attentions=all_self_attns,
716
+ )
717
+
718
+ class RWKV6Qwen2ForCausalLM(RWKV6Qwen2PreTrainedModel, GenerationMixin):
719
+ _tied_weights_keys = ["lm_head.weight"]
720
+
721
+ def __init__(self, config):
722
+ super().__init__(config)
723
+ self.model = RWKV6Qwen2Model(config)
724
+ self.vocab_size = config.vocab_size
725
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
726
+
727
+ # Initialize weights and apply final processing
728
+ self.post_init()
729
+
730
+ def get_input_embeddings(self):
731
+ return self.model.embed_tokens
732
+
733
+ def set_input_embeddings(self, value):
734
+ self.model.embed_tokens = value
735
+
736
+ def get_output_embeddings(self):
737
+ return self.lm_head
738
+
739
+ def set_output_embeddings(self, new_embeddings):
740
+ self.lm_head = new_embeddings
741
+
742
+ def set_decoder(self, decoder):
743
+ self.model = decoder
744
+
745
+ def get_decoder(self):
746
+ return self.model
747
+
748
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
749
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
750
+ def forward(
751
+ self,
752
+ input_ids: torch.LongTensor = None,
753
+ attention_mask: Optional[torch.Tensor] = None,
754
+ position_ids: Optional[torch.LongTensor] = None,
755
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
756
+ inputs_embeds: Optional[torch.FloatTensor] = None,
757
+ labels: Optional[torch.LongTensor] = None,
758
+ use_cache: Optional[bool] = None,
759
+ output_attentions: Optional[bool] = None,
760
+ output_hidden_states: Optional[bool] = None,
761
+ return_dict: Optional[bool] = None,
762
+ cache_position: Optional[torch.LongTensor] = None,
763
+ num_logits_to_keep: int = 0,
764
+ **loss_kwargs,
765
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
766
+ r"""
767
+ Args:
768
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
769
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
770
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
771
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
772
+
773
+ num_logits_to_keep (`int`, *optional*):
774
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
775
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
776
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
777
+
778
+ Returns:
779
+
780
+ Example:
781
+
782
+ ```python
783
+ >>> from transformers import AutoTokenizer, RWKV6Qwen2ForCausalLM
784
+
785
+ >>> model = RWKV6Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
786
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
787
+
788
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
789
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
790
+
791
+ >>> # Generate
792
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
793
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
794
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
795
+ ```"""
796
+
797
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
798
+ output_hidden_states = (
799
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
800
+ )
801
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
802
+
803
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
804
+ outputs = self.model(
805
+ input_ids=input_ids,
806
+ attention_mask=attention_mask,
807
+ position_ids=position_ids,
808
+ past_key_values=past_key_values,
809
+ inputs_embeds=inputs_embeds,
810
+ use_cache=use_cache,
811
+ output_attentions=output_attentions,
812
+ output_hidden_states=output_hidden_states,
813
+ return_dict=return_dict,
814
+ cache_position=cache_position,
815
+ )
816
+
817
+ hidden_states = outputs[0]
818
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
819
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
820
+
821
+ loss = None
822
+ if labels is not None:
823
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
824
+
825
+ if not return_dict:
826
+ output = (logits,) + outputs[1:]
827
+ return (loss,) + output if loss is not None else output
828
+
829
+ return CausalLMOutputWithPast(
830
+ loss=loss,
831
+ logits=logits,
832
+ past_key_values=outputs.past_key_values,
833
+ hidden_states=outputs.hidden_states,
834
+ attentions=outputs.attentions,
835
+ )
836
+
837
+ # def prepare_inputs_for_generation(
838
+ # self,
839
+ # input_ids: torch.LongTensor,
840
+ # past_key_values: Optional[Cache] = None,
841
+ # attention_mask: Optional[torch.LongTensor] = None,
842
+ # inputs_embeds: Optional[torch.FloatTensor] = None,
843
+ # cache_position: Optional[torch.LongTensor] = None,
844
+ # **kwargs,
845
+ # ):
846
+ # """
847
+ # Prepare the model inputs for generation. In includes operations like computing the 4D attention mask or
848
+ # slicing inputs given the existing cache.
849
+
850
+ # See the forward pass in the model documentation for expected arguments (different models might have different
851
+ # requirements for e.g. `past_key_values`). This function should work as is for most LLMs.
852
+ # """
853
+
854
+ # # 1. Handle BC:
855
+ # model_inputs = {}
856
+ # # - some models don't have `Cache` support (which implies they don't expect `cache_position` in `forward`)
857
+ # if self._supports_cache_class:
858
+ # model_inputs["cache_position"] = cache_position
859
+ # # - `cache_position` was not a mandatory input in `prepare_inputs_for_generation` for those models, and this
860
+ # # function may be called outside of `generate`. Handle most use cases by creating `cache_position` on the fly
861
+ # # (this alternative is not as robust as calling `generate` and letting it create `cache_position`)
862
+ # elif cache_position is None:
863
+ # past_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
864
+ # cache_position = torch.arange(past_length, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
865
+
866
+ # # 2. Generic cache-dependent input preparation
867
+ # # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
868
+ # # Exception 1: when passing input_embeds, input_ids may be missing entries
869
+ # # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
870
+ # # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case
871
+ # if past_key_values is not None:
872
+ # model_inputs["past_key_values"] = past_key_values
873
+ # if inputs_embeds is not None or cache_position[-1] >= input_ids.shape[1]: # Exception 1 or Exception 3
874
+ # input_ids = input_ids[:, -cache_position.shape[0] :]
875
+ # elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
876
+ # input_ids = input_ids[:, cache_position]
877
+
878
+ # # 3. Prepare base model inputs
879
+ # input_ids_key = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
880
+ # # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
881
+ # if not self.config.is_encoder_decoder:
882
+ # if inputs_embeds is not None and cache_position[0] == 0:
883
+ # model_inputs[input_ids_key] = None
884
+ # model_inputs["inputs_embeds"] = inputs_embeds
885
+ # else:
886
+ # # `clone` calls in this function ensure a consistent stride. See #32227
887
+ # model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)
888
+ # model_inputs["inputs_embeds"] = None
889
+ # else:
890
+ # model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)
891
+
892
+ # # 4. Create missing `position_ids` on the fly
893
+ # if (attention_mask is not None and kwargs.get("position_ids") is None and "position_ids" in set(inspect.signature(self.forward).parameters.keys())):
894
+ # position_ids = attention_mask.long().cumsum(-1) - 1
895
+ # position_ids.masked_fill_(attention_mask == 0, 1)
896
+ # kwargs["position_ids"] = position_ids # placed in kwargs for further processing (see below)
897
+
898
+ # # 5. Slice model inputs if it's an input that should have the same length as `input_ids`
899
+ # for model_input_name in ["position_ids", "token_type_ids"]:
900
+ # model_input = kwargs.get(model_input_name)
901
+ # if model_input is not None:
902
+ # if past_key_values:
903
+ # model_input = model_input[:, -input_ids.shape[1] :]
904
+ # model_input = model_input.clone(memory_format=torch.contiguous_format)
905
+ # model_inputs[model_input_name] = model_input
906
+
907
+ # # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)
908
+ # if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
909
+ # if model_inputs["inputs_embeds"] is not None:
910
+ # batch_size, sequence_length, _ = model_inputs["inputs_embeds"].shape
911
+ # device = model_inputs["inputs_embeds"].device
912
+ # else:
913
+ # batch_size, sequence_length = model_inputs[input_ids_key].shape
914
+ # device = model_inputs[input_ids_key].device
915
+
916
+ # # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create
917
+ # # the 4D causal mask exists, it should be present in the base model (XXXModel class).
918
+ # base_model = getattr(self, self.base_model_prefix, None)
919
+ # if base_model is None:
920
+ # causal_mask_creation_function = getattr(
921
+ # self, "_prepare_4d_causal_attention_mask_with_cache_position", None
922
+ # )
923
+ # else:
924
+ # causal_mask_creation_function = getattr(
925
+ # base_model, "_prepare_4d_causal_attention_mask_with_cache_position", None
926
+ # )
927
+ # if causal_mask_creation_function is None:
928
+ # logger.warning_once(
929
+ # f"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method "
930
+ # "defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're "
931
+ # "writing code, see Llama for an example implementation. If you're a user, please report this "
932
+ # "issue on GitHub."
933
+ # )
934
+ # else:
935
+ # attention_mask = causal_mask_creation_function(
936
+ # attention_mask,
937
+ # sequence_length=sequence_length,
938
+ # target_length=past_key_values.get_max_cache_shape(),
939
+ # dtype=self.dtype,
940
+ # device=device,
941
+ # cache_position=cache_position,
942
+ # batch_size=batch_size,
943
+ # config=self.config,
944
+ # past_key_values=past_key_values,
945
+ # )
946
+ # if attention_mask is not None:
947
+ # model_inputs["attention_mask"] = attention_mask
948
+
949
+ # # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
950
+ # for key, value in kwargs.items():
951
+ # if key not in model_inputs:
952
+ # model_inputs[key] = value
953
+
954
+ # # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)
955
+ # model_inputs.pop("labels", None)
956
+ # return model_inputs
957
+
958
+ @add_start_docstrings(
959
+ """
960
+ The RWKV6Qwen2 Model transformer with a sequence classification head on top (linear layer).
961
+
962
+ [`RWKV6Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
963
+ (e.g. GPT-2) do.
964
+
965
+ Since it does classification on the last token, it requires to know the position of the last token. If a
966
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
967
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
968
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
969
+ each row of the batch).
970
+ """,
971
+ RWKV6QWEN2_START_DOCSTRING,
972
+ )
973
+ class RWKV6Qwen2ForSequenceClassification(RWKV6Qwen2PreTrainedModel):
974
+ def __init__(self, config):
975
+ super().__init__(config)
976
+ self.num_labels = config.num_labels
977
+ self.model = RWKV6Qwen2Model(config)
978
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
979
+
980
+ # Initialize weights and apply final processing
981
+ self.post_init()
982
+
983
+ def get_input_embeddings(self):
984
+ return self.model.embed_tokens
985
+
986
+ def set_input_embeddings(self, value):
987
+ self.model.embed_tokens = value
988
+
989
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
990
+ def forward(
991
+ self,
992
+ input_ids: torch.LongTensor = None,
993
+ attention_mask: Optional[torch.Tensor] = None,
994
+ position_ids: Optional[torch.LongTensor] = None,
995
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
996
+ inputs_embeds: Optional[torch.FloatTensor] = None,
997
+ labels: Optional[torch.LongTensor] = None,
998
+ use_cache: Optional[bool] = None,
999
+ output_attentions: Optional[bool] = None,
1000
+ output_hidden_states: Optional[bool] = None,
1001
+ return_dict: Optional[bool] = None,
1002
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1003
+ r"""
1004
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1005
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1006
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1007
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1008
+ """
1009
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1010
+
1011
+ transformer_outputs = self.model(
1012
+ input_ids,
1013
+ attention_mask=attention_mask,
1014
+ position_ids=position_ids,
1015
+ past_key_values=past_key_values,
1016
+ inputs_embeds=inputs_embeds,
1017
+ use_cache=use_cache,
1018
+ output_attentions=output_attentions,
1019
+ output_hidden_states=output_hidden_states,
1020
+ return_dict=return_dict,
1021
+ )
1022
+ hidden_states = transformer_outputs[0]
1023
+ logits = self.score(hidden_states)
1024
+
1025
+ if input_ids is not None:
1026
+ batch_size = input_ids.shape[0]
1027
+ else:
1028
+ batch_size = inputs_embeds.shape[0]
1029
+
1030
+ if self.config.pad_token_id is None and batch_size != 1:
1031
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1032
+ if self.config.pad_token_id is None:
1033
+ sequence_lengths = -1
1034
+ else:
1035
+ if input_ids is not None:
1036
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1037
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1038
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1039
+ sequence_lengths = sequence_lengths.to(logits.device)
1040
+ else:
1041
+ sequence_lengths = -1
1042
+
1043
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1044
+
1045
+ loss = None
1046
+ if labels is not None:
1047
+ labels = labels.to(logits.device)
1048
+ if self.config.problem_type is None:
1049
+ if self.num_labels == 1:
1050
+ self.config.problem_type = "regression"
1051
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1052
+ self.config.problem_type = "single_label_classification"
1053
+ else:
1054
+ self.config.problem_type = "multi_label_classification"
1055
+
1056
+ if self.config.problem_type == "regression":
1057
+ loss_fct = MSELoss()
1058
+ if self.num_labels == 1:
1059
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1060
+ else:
1061
+ loss = loss_fct(pooled_logits, labels)
1062
+ elif self.config.problem_type == "single_label_classification":
1063
+ loss_fct = CrossEntropyLoss()
1064
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1065
+ elif self.config.problem_type == "multi_label_classification":
1066
+ loss_fct = BCEWithLogitsLoss()
1067
+ loss = loss_fct(pooled_logits, labels)
1068
+ if not return_dict:
1069
+ output = (pooled_logits,) + transformer_outputs[1:]
1070
+ return ((loss,) + output) if loss is not None else output
1071
+
1072
+ return SequenceClassifierOutputWithPast(
1073
+ loss=loss,
1074
+ logits=pooled_logits,
1075
+ past_key_values=transformer_outputs.past_key_values,
1076
+ hidden_states=transformer_outputs.hidden_states,
1077
+ attentions=transformer_outputs.attentions,
1078
+ )
1079
+
1080
+
1081
+ @add_start_docstrings(
1082
+ """
1083
+ The RWKV6Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1084
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1085
+ """,
1086
+ RWKV6QWEN2_START_DOCSTRING,
1087
+ )
1088
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->RWKV6Qwen2, LLAMA->RWKV6QWEN2
1089
+ class RWKV6Qwen2ForTokenClassification(RWKV6Qwen2PreTrainedModel):
1090
+ def __init__(self, config):
1091
+ super().__init__(config)
1092
+ self.num_labels = config.num_labels
1093
+ self.model = RWKV6Qwen2Model(config)
1094
+ if getattr(config, "classifier_dropout", None) is not None:
1095
+ classifier_dropout = config.classifier_dropout
1096
+ elif getattr(config, "hidden_dropout", None) is not None:
1097
+ classifier_dropout = config.hidden_dropout
1098
+ else:
1099
+ classifier_dropout = 0.1
1100
+ self.dropout = nn.Dropout(classifier_dropout)
1101
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1102
+
1103
+ # Initialize weights and apply final processing
1104
+ self.post_init()
1105
+
1106
+ def get_input_embeddings(self):
1107
+ return self.model.embed_tokens
1108
+
1109
+ def set_input_embeddings(self, value):
1110
+ self.model.embed_tokens = value
1111
+
1112
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
1113
+ @add_code_sample_docstrings(
1114
+ checkpoint=_CHECKPOINT_FOR_DOC,
1115
+ output_type=TokenClassifierOutput,
1116
+ config_class=_CONFIG_FOR_DOC,
1117
+ )
1118
+ def forward(
1119
+ self,
1120
+ input_ids: Optional[torch.LongTensor] = None,
1121
+ attention_mask: Optional[torch.Tensor] = None,
1122
+ position_ids: Optional[torch.LongTensor] = None,
1123
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1124
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1125
+ labels: Optional[torch.LongTensor] = None,
1126
+ use_cache: Optional[bool] = None,
1127
+ output_attentions: Optional[bool] = None,
1128
+ output_hidden_states: Optional[bool] = None,
1129
+ return_dict: Optional[bool] = None,
1130
+ ) -> Union[Tuple, TokenClassifierOutput]:
1131
+ r"""
1132
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1133
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1134
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1135
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1136
+ """
1137
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1138
+
1139
+ outputs = self.model(
1140
+ input_ids,
1141
+ attention_mask=attention_mask,
1142
+ position_ids=position_ids,
1143
+ past_key_values=past_key_values,
1144
+ inputs_embeds=inputs_embeds,
1145
+ use_cache=use_cache,
1146
+ output_attentions=output_attentions,
1147
+ output_hidden_states=output_hidden_states,
1148
+ return_dict=return_dict,
1149
+ )
1150
+ sequence_output = outputs[0]
1151
+ sequence_output = self.dropout(sequence_output)
1152
+ logits = self.score(sequence_output)
1153
+
1154
+ loss = None
1155
+ if labels is not None:
1156
+ loss = self.loss_function(logits, labels, self.config)
1157
+
1158
+ if not return_dict:
1159
+ output = (logits,) + outputs[2:]
1160
+ return ((loss,) + output) if loss is not None else output
1161
+
1162
+ return TokenClassifierOutput(
1163
+ loss=loss,
1164
+ logits=logits,
1165
+ hidden_states=outputs.hidden_states,
1166
+ attentions=outputs.attentions,
1167
+ )
1168
+
1169
+
1170
+ @add_start_docstrings(
1171
+ """
1172
+ The RWKV6Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
1173
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1174
+ """,
1175
+ RWKV6QWEN2_START_DOCSTRING,
1176
+ )
1177
+ # Copied from transformers.models.mistral.modeling_mistral.MistralForQuestionAnswering with Mistral->RWKV6Qwen2, MISTRAL->RWKV6QWEN2
1178
+ class RWKV6Qwen2ForQuestionAnswering(RWKV6Qwen2PreTrainedModel):
1179
+ base_model_prefix = "model"
1180
+
1181
+ # Copied from models.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->RWKV6Qwen2
1182
+ def __init__(self, config):
1183
+ super().__init__(config)
1184
+ self.model = RWKV6Qwen2Model(config)
1185
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1186
+
1187
+ # Initialize weights and apply final processing
1188
+ self.post_init()
1189
+
1190
+ def get_input_embeddings(self):
1191
+ return self.model.embed_tokens
1192
+
1193
+ def set_input_embeddings(self, value):
1194
+ self.model.embed_tokens = value
1195
+
1196
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
1197
+ def forward(
1198
+ self,
1199
+ input_ids: Optional[torch.LongTensor] = None,
1200
+ attention_mask: Optional[torch.FloatTensor] = None,
1201
+ position_ids: Optional[torch.LongTensor] = None,
1202
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1203
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1204
+ start_positions: Optional[torch.LongTensor] = None,
1205
+ end_positions: Optional[torch.LongTensor] = None,
1206
+ output_attentions: Optional[bool] = None,
1207
+ output_hidden_states: Optional[bool] = None,
1208
+ return_dict: Optional[bool] = None,
1209
+ **kwargs,
1210
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1211
+ r"""
1212
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1213
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1214
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1215
+ are not taken into account for computing the loss.
1216
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1217
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1218
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1219
+ are not taken into account for computing the loss.
1220
+ """
1221
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1222
+
1223
+ outputs = self.model(
1224
+ input_ids,
1225
+ attention_mask=attention_mask,
1226
+ position_ids=position_ids,
1227
+ past_key_values=past_key_values,
1228
+ inputs_embeds=inputs_embeds,
1229
+ output_attentions=output_attentions,
1230
+ output_hidden_states=output_hidden_states,
1231
+ return_dict=return_dict,
1232
+ )
1233
+
1234
+ sequence_output = outputs[0]
1235
+
1236
+ logits = self.qa_outputs(sequence_output)
1237
+ start_logits, end_logits = logits.split(1, dim=-1)
1238
+ start_logits = start_logits.squeeze(-1).contiguous()
1239
+ end_logits = end_logits.squeeze(-1).contiguous()
1240
+
1241
+ loss = None
1242
+ if start_positions is not None and end_positions is not None:
1243
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1244
+
1245
+ if not return_dict:
1246
+ output = (start_logits, end_logits) + outputs[2:]
1247
+ return ((loss,) + output) if loss is not None else output
1248
+
1249
+ return QuestionAnsweringModelOutput(
1250
+ loss=loss,
1251
+ start_logits=start_logits,
1252
+ end_logits=end_logits,
1253
+ hidden_states=outputs.hidden_states,
1254
+ attentions=outputs.attentions,
1255
+ )
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are a helpful assistant.' }}\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\\nYou are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
199
+ "clean_up_tokenization_spaces": false,
200
+ "eos_token": "<|im_end|>",
201
+ "errors": "replace",
202
+ "model_max_length": 131072,
203
+ "pad_token": "<|endoftext|>",
204
+ "split_special_tokens": false,
205
+ "tokenizer_class": "Qwen2Tokenizer",
206
+ "unk_token": null
207
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff