SmerkyG commited on
Commit
c0ba740
·
verified ·
1 Parent(s): 5c3c7ce

Upload folder using huggingface_hub

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