SmerkyG commited on
Commit
b0fcd94
1 Parent(s): f06a9c0

Upload folder using huggingface_hub

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