SmerkyG commited on
Commit
89858fa
·
verified ·
1 Parent(s): 2747e19

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "RWKV7Qwen3ForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_rwkv7qwen3.RWKV7Qwen3Config",
7
+ "AutoModelForCausalLM": "modeling_rwkv7qwen3.RWKV7Qwen3ForCausalLM"
8
+ },
9
+ "attention_bias": false,
10
+ "attention_dropout": 0.0,
11
+ "attention_output_bias": false,
12
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151645,
14
+ "head_dim": 128,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 4096,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 12288,
19
+ "max_position_embeddings": 32768,
20
+ "max_window_layers": 36,
21
+ "model_type": "rwkv7qwen3",
22
+ "num_attention_heads": 32,
23
+ "first_attention_layer": 0,
24
+ "attention_striping": 5,
25
+ "num_hidden_layers": 36,
26
+ "num_key_value_heads": 8,
27
+ "use_k_first": 1,
28
+ "v_first_pre_gqa": 1,
29
+ "rms_norm_eps": 1e-06,
30
+ "rope_theta": 1000000.0,
31
+ "sliding_window": null,
32
+ "tie_word_embeddings": false,
33
+ "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.51.0",
35
+ "use_cache": true,
36
+ "use_rope": true,
37
+ "use_sliding_window": false,
38
+ "vocab_size": 151936
39
+ }
configuration_rwkv7qwen3.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """RWKV7Qwen3 model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig, layer_type_validation
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 RWKV7Qwen3Config(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`RWKV7Qwen3Model`]. It is used to instantiate a
28
+ RWKV7Qwen3 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
+ Qwen3-7B-beta [Qwen/Qwen3-7B-beta](https://huggingface.co/Qwen/Qwen3-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 RWKV7Qwen3 model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`RWKV7Qwen3Model`]
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
+ lora_rank_decay (`int`, *optional*):
56
+ The rank of the lora used to generate decay.
57
+ lora_rank_iclr (`int`, *optional*):
58
+ The rank of the lora used to generate the in-context learning rate.
59
+ lora_rank_value_residual_mix (`int`, *optional*):
60
+ The rank of the lora used to generate the value residual mix amount.
61
+ lora_rank_value_gate (`int`, *optional*):
62
+ The rank of the lora used to generate the gate.
63
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
64
+ The non-linear activation function (function or string) in the decoder.
65
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
66
+ The maximum sequence length that this model might ever be used with.
67
+ initializer_range (`float`, *optional*, defaults to 0.02):
68
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
69
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
70
+ The epsilon used by the rms normalization layers.
71
+ use_cache (`bool`, *optional*, defaults to `True`):
72
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
73
+ relevant if `config.is_decoder=True`.
74
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
75
+ Whether the model's input and output word embeddings should be tied.
76
+ rope_theta (`float`, *optional*, defaults to 10000.0):
77
+ The base period of the RoPE embeddings.
78
+ rope_scaling (`Dict`, *optional*):
79
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
80
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
81
+ accordingly.
82
+ Expected contents:
83
+ `rope_type` (`str`):
84
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
85
+ 'llama3'], with 'default' being the original RoPE implementation.
86
+ `factor` (`float`, *optional*):
87
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
88
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
89
+ original maximum pre-trained length.
90
+ `original_max_position_embeddings` (`int`, *optional*):
91
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
92
+ pretraining.
93
+ `attention_factor` (`float`, *optional*):
94
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
95
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
96
+ `factor` field to infer the suggested value.
97
+ `beta_fast` (`float`, *optional*):
98
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
99
+ ramp function. If unspecified, it defaults to 32.
100
+ `beta_slow` (`float`, *optional*):
101
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
102
+ ramp function. If unspecified, it defaults to 1.
103
+ `short_factor` (`List[float]`, *optional*):
104
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
105
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
106
+ size divided by the number of attention heads divided by 2
107
+ `long_factor` (`List[float]`, *optional*):
108
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
109
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
110
+ size divided by the number of attention heads divided by 2
111
+ `low_freq_factor` (`float`, *optional*):
112
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
113
+ `high_freq_factor` (`float`, *optional*):
114
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
115
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
116
+ Whether to use sliding window attention.
117
+ sliding_window (`int`, *optional*, defaults to 4096):
118
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
119
+ max_window_layers (`int`, *optional*, defaults to 28):
120
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
121
+ attention_dropout (`float`, *optional*, defaults to 0.0):
122
+ The dropout ratio for the attention probabilities.
123
+
124
+ ```python
125
+ >>> from transformers import RWKV7Qwen3Model, RWKV7Qwen3Config
126
+
127
+ >>> # Initializing a RWKV7Qwen3 style configuration
128
+ >>> configuration = RWKV7Qwen3Config()
129
+
130
+ >>> # Initializing a model from the RWKV7Qwen3-7B style configuration
131
+ >>> model = RWKV7Qwen3Model(configuration)
132
+
133
+ >>> # Accessing the model configuration
134
+ >>> configuration = model.config
135
+ ```"""
136
+
137
+ model_type = "rwkv7qwen3"
138
+ keys_to_ignore_at_inference = ["past_key_values"]
139
+
140
+ def __init__(
141
+ self,
142
+ vocab_size=151936,
143
+ hidden_size=4096,
144
+ intermediate_size=22016,
145
+ num_hidden_layers=32,
146
+ num_attention_heads=32,
147
+ num_key_value_heads=32,
148
+ lora_rank_tokenshift=None,
149
+ lora_rank_decay=None,
150
+ lora_rank_iclr=None,
151
+ lora_rank_value_residual_mix=None,
152
+ lora_rank_gate=None,
153
+ hidden_act="silu",
154
+ max_position_embeddings=32768,
155
+ initializer_range=0.02,
156
+ rms_norm_eps=1e-6,
157
+ use_cache=True,
158
+ tie_word_embeddings=False,
159
+ use_rope=False,
160
+ rope_theta=10000.0,
161
+ rope_scaling=None,
162
+ use_sliding_window=False,
163
+ sliding_window=4096,
164
+ max_window_layers=28,
165
+ first_attention_layer=9999,
166
+ first_post_attention_layer=9999,
167
+ attention_striping=1,
168
+ last_striping_layer=99999,
169
+ layer_types=None,
170
+ attention_dropout=0.0,
171
+ attention_bias=True,
172
+ attention_output_bias=False,
173
+ gate_rank_type=2,
174
+ balance_state=True,
175
+ groupnorm_att=False,
176
+ use_tokenshift=False,
177
+ partial_posemb=1.0,
178
+ use_k_first=False,
179
+ v_first_pre_gqa=False,
180
+ **kwargs,
181
+ ):
182
+ self.vocab_size = vocab_size
183
+ self.max_position_embeddings = max_position_embeddings
184
+ self.hidden_size = hidden_size
185
+ self.intermediate_size = intermediate_size
186
+ self.num_hidden_layers = num_hidden_layers
187
+ self.num_attention_heads = num_attention_heads
188
+ self.use_sliding_window = use_sliding_window
189
+ self.sliding_window = sliding_window if use_sliding_window else None
190
+ self.max_window_layers = max_window_layers
191
+ self.first_attention_layer = first_attention_layer
192
+ self.first_post_attention_layer = first_post_attention_layer
193
+ self.attention_striping = attention_striping
194
+ self.last_striping_layer = last_striping_layer
195
+
196
+ # for backward compatibility
197
+ if num_key_value_heads is None:
198
+ num_key_value_heads = num_attention_heads
199
+
200
+ self.num_key_value_heads = num_key_value_heads
201
+ self.lora_rank_tokenshift = lora_rank_tokenshift
202
+ self.lora_rank_decay = lora_rank_decay
203
+ self.lora_rank_iclr = lora_rank_iclr
204
+ self.lora_rank_value_residual_mix = lora_rank_value_residual_mix
205
+ self.lora_rank_gate = lora_rank_gate
206
+ self.hidden_act = hidden_act
207
+ self.initializer_range = initializer_range
208
+ self.rms_norm_eps = rms_norm_eps
209
+ self.use_cache = use_cache
210
+ self.use_rope = use_rope
211
+ self.rope_theta = rope_theta
212
+ self.rope_scaling = rope_scaling
213
+ self.attention_dropout = attention_dropout
214
+ # Validate the correctness of rotary position embeddings parameters
215
+ # BC: if there is a 'type' field, move it to 'rope_type'.
216
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
217
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
218
+ rope_config_validation(self)
219
+
220
+ self.layer_types = layer_types
221
+ if self.layer_types is None:
222
+ self.layer_types = [
223
+ "sliding_attention"
224
+ if self.sliding_window is not None and i >= self.max_window_layers
225
+ else "full_attention"
226
+ for i in range(self.num_hidden_layers)
227
+ ]
228
+ layer_type_validation(self.layer_types)
229
+
230
+ self.attention_bias = attention_bias
231
+ self.attention_output_bias = attention_output_bias
232
+ self.gate_rank_type = gate_rank_type
233
+ self.balance_state = balance_state
234
+ self.groupnorm_att = groupnorm_att
235
+ self.use_tokenshift = use_tokenshift
236
+ self.partial_posemb = partial_posemb
237
+ self.use_k_first = use_k_first
238
+ self.v_first_pre_gqa = v_first_pre_gqa
239
+
240
+ super().__init__(
241
+ tie_word_embeddings=tie_word_embeddings,
242
+ **kwargs,
243
+ )
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.51.0"
13
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bcfdd123db6ffb0d4641f7d6d94702fea097182d9ca828df8ba0f0b42d1b0043
3
+ size 16775521208
modeling_rwkv7qwen3.py ADDED
The diff for this file is too large to render. See raw diff
 
modeling_rwkv7qwen3_new.py ADDED
@@ -0,0 +1,1359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 RWKV7Qwen3 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, SlidingWindowCache
33
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
34
+ from transformers.generation import GenerationMixin
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ QuestionAnsweringModelOutput,
39
+ SequenceClassifierOutputWithPast,
40
+ TokenClassifierOutput,
41
+ )
42
+ from transformers.modeling_utils import PreTrainedModel
43
+ from transformers.utils import (
44
+ add_code_sample_docstrings,
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ is_flash_attn_2_available,
48
+ is_flash_attn_greater_or_equal_2_10,
49
+ logging,
50
+ replace_return_docstrings,
51
+ )
52
+ from .configuration_rwkv7qwen3 import RWKV7Qwen3Config
53
+
54
+ from transformers.models.qwen3.modeling_qwen3 import Qwen3DecoderLayer, Qwen3MLP, Qwen3RMSNorm, Qwen3Attention
55
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CHECKPOINT_FOR_DOC = "recursal/QRWKV7-7B-Instruct-Preview-v0.1"
60
+ _CONFIG_FOR_DOC = "RWKV7QwenConfig"
61
+
62
+ class RWKV7State(Cache):
63
+ def __init__(self) -> None:
64
+ super().__init__()
65
+ self._seen_tokens = 0 # Used in `generate` to keep tally of how many tokens the cache has seen
66
+ self.layer_kv_states: List[torch.Tensor] = []
67
+ self.layer_shift_states: List[torch.Tensor] = []
68
+
69
+ def __getitem__(self, layer_idx: int) -> Tuple[torch.Tensor, torch.Tensor]:
70
+ """
71
+ Support for backwards-compatible `past_key_value` indexing, e.g. `past_key_value[0][0].shape[2]` to get the
72
+ sequence length.
73
+ """
74
+ if layer_idx < len(self):
75
+ return (self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx])
76
+ else:
77
+ raise KeyError(f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}")
78
+
79
+ def __iter__(self):
80
+ """
81
+ Support for backwards-compatible `past_key_value` iteration, e.g. `for x in past_key_value:` to iterate over
82
+ keys and values
83
+ """
84
+ for layer_idx in range(len(self)):
85
+ yield (self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx])
86
+
87
+ def __len__(self):
88
+ """
89
+ Support for backwards-compatible `past_key_value` length, e.g. `len(past_key_value)`. This value corresponds
90
+ to the number of layers in the model.
91
+ """
92
+ return len(self.layer_kv_states)
93
+
94
+ def get_usable_length(self, new_seq_length: int, layer_idx: Optional[int] = 0) -> int:
95
+ """Given the sequence length of the new inputs, returns the usable length of the cache."""
96
+ # Linear Attention variants do not have a maximum length
97
+ return new_seq_length
98
+
99
+ def reorder_cache(self, beam_idx: torch.LongTensor):
100
+ """Reorders the cache for beam search, given the selected beam indices."""
101
+ raise NotImplementedError('Cannot reorder Linear Attention state')
102
+
103
+ def get_seq_length(self, layer_idx: int = 0) -> int:
104
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
105
+ return self._seen_tokens
106
+
107
+ def get_max_cache_shape(self) -> Optional[int]:
108
+ """Returns the maximum sequence length of the cache object. DynamicCache does not have a maximum length."""
109
+ return None
110
+
111
+ def get_max_length(self) -> Optional[int]:
112
+ """
113
+ Returns the maximum sequence length of the cached states. DynamicCache does not have a maximum length.
114
+ """
115
+ return None
116
+
117
+ def crop(self, max_length: int):
118
+ # can't implement this for linear attention variants
119
+ return
120
+
121
+ @torch.no_grad
122
+ def update(
123
+ self,
124
+ kv_state: torch.Tensor,
125
+ shift_state: torch.Tensor,
126
+ layer_idx: int,
127
+ token_count: int = 0,
128
+ is_attention_layer: bool = True,
129
+ cache_kwargs: Optional[Dict[str, Any]] = None,
130
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
131
+ # Update the number of seen tokens
132
+ if layer_idx == 0:
133
+ if is_attention_layer:
134
+ token_count = kv_state.size(-2)
135
+ self._seen_tokens += token_count
136
+
137
+ # Update the cache
138
+ if kv_state is not None:
139
+ # There may be skipped layers, fill them with empty lists
140
+ if layer_idx >= len(self.layer_kv_states):
141
+ for _ in range(len(self.layer_kv_states), layer_idx):
142
+ if is_attention_layer:
143
+ self.layer_kv_states.append(torch.tensor([])) # acts as key_cache
144
+ self.layer_shift_states.append(torch.tensor([])) # acts as value_cache
145
+ else:
146
+ self.layer_kv_states.append(torch.zeros_like(kv_state).requires_grad_(False))
147
+ self.layer_shift_states.append(torch.zeros_like(shift_state).requires_grad_(False))
148
+ self.layer_kv_states.append(kv_state) # acts as key_cache
149
+ self.layer_shift_states.append(shift_state) # acts as value_cache
150
+ else:
151
+ if is_attention_layer:
152
+ self.layer_kv_states[layer_idx] = torch.cat([self.layer_kv_states[layer_idx], kv_state], dim=-2) # acts as key_cache
153
+ self.layer_shift_states[layer_idx] = torch.cat([self.layer_shift_states[layer_idx], shift_state], dim=-2) # acts as value_cache
154
+ else:
155
+ self.layer_kv_states[layer_idx].copy_(kv_state)
156
+ self.layer_shift_states[layer_idx].copy_(shift_state)
157
+
158
+ return self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx]
159
+
160
+ try:
161
+ from fla.ops.rwkv7.chunk import chunk_rwkv7
162
+ from fla.ops.rwkv7.fused_recurrent import fused_recurrent_rwkv7
163
+ except ImportError:
164
+ print("Required module is not installed. Please install it using the following commands:")
165
+ print("pip install --no-use-pep517 flash-linear-attention")
166
+ print("Additionally, ensure you have at least version 2.2.0 of Triton installed:")
167
+ print("pip install triton>=2.2.0")
168
+
169
+ class Qwen3RotaryEmbedding(nn.Module):
170
+ def __init__(self, config: RWKV7Qwen3Config, device=None):
171
+ super().__init__()
172
+ # BC: "rope_type" was originally "type"
173
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
174
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
175
+ else:
176
+ self.rope_type = "default"
177
+ self.max_seq_len_cached = config.max_position_embeddings
178
+ self.original_max_seq_len = config.max_position_embeddings
179
+
180
+ self.config = config
181
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
182
+
183
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
184
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
185
+ self.original_inv_freq = self.inv_freq
186
+
187
+ def _dynamic_frequency_update(self, position_ids, device):
188
+ """
189
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
190
+ 1 - growing beyond the cached sequence length (allow scaling)
191
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
192
+ """
193
+ seq_len = torch.max(position_ids) + 1
194
+ if seq_len > self.max_seq_len_cached: # growth
195
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
196
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
197
+ self.max_seq_len_cached = seq_len
198
+
199
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
200
+ # This .to() is needed if the model has been moved to a device after being initialized (because
201
+ # the buffer is automatically moved, but not the original copy)
202
+ self.original_inv_freq = self.original_inv_freq.to(device)
203
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
204
+ self.max_seq_len_cached = self.original_max_seq_len
205
+
206
+ @torch.no_grad()
207
+ def forward(self, x, position_ids):
208
+ if "dynamic" in self.rope_type:
209
+ self._dynamic_frequency_update(position_ids, device=x.device)
210
+
211
+ # Core RoPE block
212
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
213
+ position_ids_expanded = position_ids[:, None, :].float()
214
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
215
+ device_type = x.device.type
216
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
217
+ with torch.autocast(device_type=device_type, enabled=False):
218
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
219
+ emb = torch.cat((freqs, freqs), dim=-1)
220
+ cos = emb.cos()
221
+ sin = emb.sin()
222
+
223
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
224
+ cos = cos * self.attention_scaling
225
+ sin = sin * self.attention_scaling
226
+
227
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
228
+
229
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen3
230
+ class Qwen3RMSNorm(nn.Module):
231
+ def __init__(self, hidden_size, eps=1e-6):
232
+ """
233
+ Qwen3RMSNorm is equivalent to T5LayerNorm
234
+ """
235
+ super().__init__()
236
+ self.weight = nn.Parameter(torch.ones(hidden_size))
237
+ self.variance_epsilon = eps
238
+
239
+ def forward(self, hidden_states):
240
+ input_dtype = hidden_states.dtype
241
+ hidden_states = hidden_states.to(torch.float32)
242
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
243
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
244
+ return self.weight * hidden_states.to(input_dtype)
245
+
246
+ def extra_repr(self):
247
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
248
+
249
+ def generate_rotary_embedding(max_seqlen:int, dim:int, theta:float = 10000.0, scale:float = 1):
250
+ #inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float).to(device) / dim))
251
+
252
+ angular_velocity = theta ** -(torch.arange(0, dim, 2, dtype=torch.float) / dim) / scale # frequencies from 1.0 ... 1/theta
253
+ angles = torch.outer(torch.arange(max_seqlen), angular_velocity)
254
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
255
+ emb = torch.cat((angles, angles), dim=-1)
256
+ return torch.stack([emb.cos(), emb.sin()], dim=0)
257
+ #return torch.polar(torch.ones_like(angles), angles)
258
+
259
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
260
+ def rotate_half(x):
261
+ """Rotates half the hidden dims of the input."""
262
+ x1 = x[..., : x.shape[-1] // 2]
263
+ x2 = x[..., x.shape[-1] // 2 :]
264
+ return torch.cat((-x2, x1), dim=-1)
265
+
266
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
267
+ """Applies Rotary Position Embedding to the query and key tensors.
268
+
269
+ Args:
270
+ q (`torch.Tensor`): The query tensor.
271
+ k (`torch.Tensor`): The key tensor.
272
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
273
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
274
+ position_ids (`torch.Tensor`, *optional*):
275
+ Deprecated and unused.
276
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
277
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
278
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
279
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
280
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
281
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
282
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
283
+ Returns:
284
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
285
+ """
286
+ cos = cos.unsqueeze(unsqueeze_dim)
287
+ sin = sin.unsqueeze(unsqueeze_dim)
288
+ q_embed = (q * cos) + (rotate_half(q) * sin)
289
+ k_embed = (k * cos) + (rotate_half(k) * sin)
290
+ return q_embed, k_embed
291
+
292
+ from typing import Callable, Optional, Tuple, Union
293
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
294
+ from transformers.processing_utils import Unpack
295
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
296
+
297
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
298
+ """
299
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
300
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
301
+ """
302
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
303
+ if n_rep == 1:
304
+ return hidden_states
305
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
306
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
307
+
308
+ def eager_attention_forward(
309
+ module: nn.Module,
310
+ query: torch.Tensor,
311
+ key: torch.Tensor,
312
+ value: torch.Tensor,
313
+ attention_mask: Optional[torch.Tensor],
314
+ scaling: float,
315
+ dropout: float = 0.0,
316
+ **kwargs,
317
+ ):
318
+ key_states = repeat_kv(key, module.num_key_value_groups)
319
+ value_states = repeat_kv(value, module.num_key_value_groups)
320
+
321
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
322
+ if attention_mask is not None:
323
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
324
+ attn_weights = attn_weights + causal_mask
325
+
326
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
327
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
328
+ attn_output = torch.matmul(attn_weights, value_states)
329
+ attn_output = attn_output.transpose(1, 2).contiguous()
330
+
331
+ return attn_output, attn_weights
332
+
333
+ class Qwen3NewAttention(nn.Module):
334
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
335
+
336
+ def __init__(self, config: RWKV7Qwen3Config, layer_idx: int):
337
+ super().__init__()
338
+ self.config = config
339
+ self.layer_idx = layer_idx
340
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
341
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
342
+ self.scaling = self.head_dim**-0.5
343
+ self.attention_dropout = config.attention_dropout
344
+ self.is_causal = True
345
+
346
+ self.q_proj = nn.Linear(
347
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
348
+ )
349
+ self.k_proj = nn.Linear(
350
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
351
+ )
352
+ self.v_proj = nn.Linear(
353
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
354
+ )
355
+ self.o_proj = nn.Linear(
356
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
357
+ )
358
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
359
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
360
+ self.sliding_window = config.sliding_window
361
+ if not (
362
+ self.config.use_sliding_window
363
+ and getattr(self.config, "sliding_window", None) is not None
364
+ and self.layer_idx >= self.config.max_window_layers
365
+ ):
366
+ self.sliding_window = None
367
+
368
+ def forward(
369
+ self,
370
+ hidden_states: torch.Tensor,
371
+ stopped_residual: torch.Tensor,
372
+ v_first: Optional[torch.Tensor] = None,
373
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
374
+ attention_mask: Optional[torch.Tensor] = None,
375
+ past_key_value: Optional[Cache] = None,
376
+ cache_position: Optional[torch.LongTensor] = None,
377
+ **kwargs: Unpack[FlashAttentionKwargs],
378
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
379
+ input_shape = hidden_states.shape[:-1]
380
+ hidden_shape = (*input_shape, -1, self.head_dim)
381
+
382
+ xk = xv = stopped_residual
383
+
384
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
385
+ key_states = self.k_norm(self.k_proj(xk).view(hidden_shape)).transpose(1, 2)
386
+ value_states = self.v_proj(xv).view(hidden_shape).transpose(1, 2)
387
+
388
+ cos, sin = position_embeddings
389
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
390
+
391
+ if past_key_value is not None:
392
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
393
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
394
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
395
+
396
+ attention_interface: Callable = eager_attention_forward
397
+ if self.config._attn_implementation != "eager":
398
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
399
+ logger.warning_once(
400
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
401
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
402
+ )
403
+ else:
404
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
405
+
406
+ attn_output, attn_weights = attention_interface(
407
+ self,
408
+ query_states,
409
+ key_states,
410
+ value_states,
411
+ attention_mask,
412
+ dropout=0.0 if not self.training else self.attention_dropout,
413
+ scaling=self.scaling,
414
+ sliding_window=self.sliding_window, # diff with Llama
415
+ **kwargs,
416
+ )
417
+
418
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
419
+ attn_output = self.o_proj(attn_output)
420
+ return attn_output, attn_weights
421
+
422
+ class RWKV7Attention(nn.Module):
423
+ def __init__(self, config, layer_idx: Optional[int] = None):
424
+ super().__init__()
425
+ self.config = config
426
+ self.layer_idx = layer_idx
427
+ C = self.hidden_size = config.hidden_size
428
+ H = self.num_heads = config.num_attention_heads
429
+ N = self.head_dim = getattr(config, 'head_dim', self.hidden_size // self.num_heads)
430
+ self.num_key_value_heads = config.num_key_value_heads
431
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
432
+ self.attention_dropout = config.attention_dropout
433
+
434
+ if self.hidden_size % self.num_heads != 0:
435
+ raise ValueError(
436
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
437
+ f" and `num_heads`: {self.num_heads})."
438
+ )
439
+ self.q_proj = nn.Linear(
440
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
441
+ )
442
+ self.k_proj = nn.Linear(
443
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
444
+ )
445
+ self.v_proj = nn.Linear(
446
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
447
+ )
448
+ self.o_proj = nn.Linear(
449
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
450
+ )
451
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
452
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
453
+ self.sliding_window = config.sliding_window
454
+ if not (
455
+ self.config.use_sliding_window
456
+ and getattr(self.config, "sliding_window", None) is not None
457
+ and self.layer_idx >= self.config.max_window_layers
458
+ ):
459
+ self.sliding_window = None
460
+
461
+ calc_lora_rank = lambda exponent, multiplier: max(1, round(self.hidden_size ** exponent * multiplier / 32)) * 32
462
+ lora_rank_decay = config.lora_rank_decay or calc_lora_rank(0.5, 1.8)
463
+ lora_rank_iclr = config.lora_rank_iclr or calc_lora_rank(0.5, 1.8)
464
+ lora_rank_value_residual_mix = config.lora_rank_value_residual_mix or calc_lora_rank(0.5, 1.3)
465
+ lora_rank_gate = config.lora_rank_gate or calc_lora_rank(0.8, 0.6)
466
+
467
+ # self.x_r = nn.Parameter(torch.empty(1,1,C))
468
+ # self.x_w = nn.Parameter(torch.empty(1,1,C))
469
+ # self.x_k = nn.Parameter(torch.empty(1,1,C))
470
+ # self.x_v = nn.Parameter(torch.empty(1,1,C))
471
+ # self.x_a = nn.Parameter(torch.empty(1,1,C))
472
+ # self.x_g = nn.Parameter(torch.empty(1,1,C))
473
+
474
+ self.w0 = nn.Parameter(torch.empty(1,1,H*N))
475
+ self.w1 = nn.Parameter(torch.empty(C, lora_rank_decay))
476
+ self.w2 = nn.Parameter(torch.empty(lora_rank_decay, H*N))
477
+
478
+ self.a0 = nn.Parameter(torch.empty(1,1,H*N))
479
+ self.a1 = nn.Parameter(torch.empty(C, lora_rank_iclr))
480
+ self.a2 = nn.Parameter(torch.empty(lora_rank_iclr, H*N))
481
+
482
+ #if layer_idx > 0:
483
+ self.v0 = nn.Parameter(torch.empty(1,1,H*N))
484
+ self.v1 = nn.Parameter(torch.empty(C, lora_rank_value_residual_mix))
485
+ self.v2 = nn.Parameter(torch.empty(lora_rank_value_residual_mix, H*N))
486
+
487
+ if config.gate_rank_type == 1:
488
+ self.gate = nn.Linear(C, H*N, bias=False)
489
+ elif config.gate_rank_type == 2:
490
+ self.g1 = nn.Parameter(torch.empty(C, lora_rank_gate))
491
+ self.g2 = nn.Parameter(torch.empty(lora_rank_gate, H*N))
492
+
493
+ self.k_k = nn.Parameter(torch.empty(1,1,H*N))
494
+ self.k_a = nn.Parameter(torch.empty(1,1,H*N))
495
+ self.r_k = nn.Parameter(torch.empty(H,N))
496
+
497
+ if self.config.groupnorm_att:
498
+ self.ln_x = nn.GroupNorm(H, C, eps=self.head_dim * 1e-5)
499
+
500
+ def forward(
501
+ self,
502
+ hidden_states: torch.Tensor,
503
+ stopped_residual: torch.Tensor,
504
+ v_first: Optional[torch.Tensor] = None,
505
+ attention_mask: Optional[torch.Tensor] = None,
506
+ position_ids: Optional[torch.LongTensor] = None,
507
+ past_key_value: Optional[RWKV7State] = None,
508
+ output_attentions: bool = False,
509
+ use_cache: bool = False,
510
+ cache_position: Optional[torch.LongTensor] = None,
511
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
512
+ **kwargs,
513
+ ):
514
+ if attention_mask is not None:
515
+ assert len(attention_mask.shape) == 2, (
516
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
517
+ "for padding purposes (0 indicating padding). "
518
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
519
+ )
520
+
521
+ output_shift_state = hidden_states[:, -1:].detach().clone()
522
+
523
+ x = hidden_states
524
+
525
+ B, T, C = hidden_states.shape
526
+ H = self.num_heads
527
+ N = self.head_dim
528
+ q_len = T
529
+
530
+ if use_cache and past_key_value is not None and len(past_key_value) > self.layer_idx:
531
+ input_vk_state, input_shift_state = past_key_value[self.layer_idx]
532
+ else:
533
+ input_vk_state, input_shift_state = torch.zeros(B,H,N,N, dtype=torch.float32,device=x.device), torch.zeros_like(x[:, -1:])
534
+
535
+ xr = xw = xk = xv = xa = xg = x
536
+
537
+ r = self.q_norm(self.q_proj(xr).view(B,T,-1,N))
538
+ w_lora_result = self.w0 + (torch.tanh(xw @ self.w1) @ self.w2).float()
539
+ k = self.k_norm(self.k_proj(xk).view(B,T,-1,N))
540
+ v = self.v_proj(xv)
541
+ a = torch.sigmoid(self.a0 + (xa @ self.a1) @ self.a2)
542
+ if self.config.gate_rank_type == 1:
543
+ g = torch.sigmoid(self.gate(xg))
544
+ elif self.config.gate_rank_type == 2:
545
+ g = torch.sigmoid(xg @ self.g1) @ self.g2
546
+
547
+ if position_embeddings is not None:
548
+ cos, sin = position_embeddings
549
+ r, k = apply_rotary_pos_emb(r, k, cos, sin, unsqueeze_dim=2)
550
+
551
+ # repeat k/v heads if n_kv_heads < n_heads
552
+ k = k.view(B, T, -1, 1, self.head_dim).expand(-1, -1, -1, self.num_key_value_groups, -1).reshape(B, T, -1)
553
+ v = v.view(B, T, -1, 1, self.head_dim).expand(-1, -1, -1, self.num_key_value_groups, -1).reshape(B, T, -1)
554
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
555
+
556
+ kk = (k).view(B,T,H,-1).float()
557
+ kk = (kk / (torch.norm(kk, dim=-1, keepdim=True) + 1e-12)).view(B,T,-1).to(k.dtype)
558
+
559
+ if self.layer_idx == 0: v_first = v
560
+ else: v = v + (v_first - v) * torch.sigmoid(self.v0 + (xv @ self.v1) @ self.v2)
561
+
562
+ # dealing with left-padding
563
+ if attention_mask is not None:
564
+ v = v * attention_mask[:, -v.shape[-2]:, None]
565
+
566
+ log_w = -math.exp(-0.5) * torch.sigmoid(w_lora_result.float())
567
+ w = log_w.exp()
568
+
569
+ if self.config.balance_state:
570
+ k = k * (1-w+a)
571
+
572
+ r,log_w,k,v,kk,a = [i.view(B,T,self.num_heads,-1) for i in [r,log_w,k,v,kk,a]]
573
+ if self.training:
574
+ x, output_vk_state = chunk_rwkv7(r, log_w, k, v, -kk, kk*a, initial_state=input_vk_state, output_final_state=use_cache)
575
+ else:
576
+ # if T == 1:
577
+ # output_vk_state = input_vk_state
578
+ # for t in range(T):
579
+ # r_, w_, k_, v_, kk_, a_ = r[:,t], w[:,t], k[:,t], v[:,t], kk[:,t], a[:,t]
580
+ # vk = v_.view(B,H,N,1) @ k_.view(B,H,1,N)
581
+ # ab = (-kk_).view(B,H,N,1) @ (kk_*a_).view(B,H,1,N)
582
+ # output_vk_state = output_vk_state * w_.view(B,H,1,N) + output_vk_state @ ab.float() + vk.float()
583
+ # x[:,t] = (output_vk_state.to(dtype=x.dtype) @ r_.view(B,H,N,1)).view(B,H*N)
584
+ # # FIXME - support fast triton kernel for non-training pre-fill with state in and out
585
+ # else:
586
+ x, output_vk_state = fused_recurrent_rwkv7(r, log_w, k, v, -kk, kk*a, initial_state=input_vk_state, output_final_state=use_cache)
587
+
588
+ if self.config.groupnorm_att:
589
+ x = torch.nn.functional.group_norm(x.view(B*T,H*N).float(), num_groups=H, weight=self.ln_x.weight.float(), bias=self.ln_x.bias.float(), eps = self.ln_x.eps).view(B,T,H*N).to(x.dtype)
590
+ else:
591
+ x = x.view(B,T,H*N).to(x.dtype) * N ** -0.5
592
+
593
+ x = self.o_proj(x * g)
594
+
595
+ if past_key_value is not None:
596
+ past_key_value.update(output_vk_state, output_shift_state, self.layer_idx, q_len, self.layer_idx >= self.config.num_hidden_layers - self.config.num_attention_layers)
597
+
598
+ return x, v_first
599
+
600
+ class RWKV7Qwen3DecoderLayer(nn.Module):
601
+ def __init__(self, config: RWKV7Qwen3Config, layer_idx: int):
602
+ nn.Module.__init__(self)
603
+ self.hidden_size = config.hidden_size
604
+ self.layer_idx = layer_idx
605
+
606
+ if layer_idx >= config.num_hidden_layers - config.num_attention_layers:
607
+ self.self_attn = Qwen3NewAttention(config=config, layer_idx=layer_idx)
608
+ else:
609
+ self.self_attn = RWKV7Attention(config, layer_idx)
610
+
611
+ self.mlp = Qwen3MLP(config)
612
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
613
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
614
+
615
+ def forward(
616
+ self,
617
+ hidden_states: torch.Tensor,
618
+ stopped_residual: torch.Tensor,
619
+ v_first: Optional[torch.Tensor],
620
+ attention_mask: Optional[torch.Tensor] = None,
621
+ position_ids: Optional[torch.LongTensor] = None,
622
+ past_key_value: Optional[Cache] = None,
623
+ output_attentions: Optional[bool] = False,
624
+ use_cache: Optional[bool] = False,
625
+ cache_position: Optional[torch.LongTensor] = None,
626
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
627
+ **kwargs,
628
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
629
+ residual = hidden_states
630
+
631
+ hidden_states = self.input_layernorm(hidden_states)
632
+
633
+ # Self Attention
634
+ hidden_states, v_first = self.self_attn(
635
+ hidden_states=hidden_states,
636
+ stopped_residual=stopped_residual,
637
+ v_first=v_first,
638
+ attention_mask=attention_mask,
639
+ position_ids=position_ids,
640
+ past_key_value=past_key_value,
641
+ output_attentions=output_attentions,
642
+ use_cache=use_cache,
643
+ cache_position=cache_position,
644
+ position_embeddings=position_embeddings,
645
+ #is_causal=True,
646
+ )
647
+ hidden_states = residual + hidden_states
648
+
649
+ # Fully Connected
650
+ residual = hidden_states
651
+ hidden_states = self.post_attention_layernorm(hidden_states)
652
+ hidden_states = self.mlp(hidden_states)
653
+ hidden_states = residual + hidden_states
654
+
655
+ outputs = (hidden_states, v_first,)
656
+
657
+ if output_attentions:
658
+ outputs += (self_attn_weights,)
659
+
660
+ return outputs
661
+
662
+
663
+
664
+ RWKV7QWEN3_START_DOCSTRING = r"""
665
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
666
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
667
+ etc.)
668
+
669
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
670
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
671
+ and behavior.
672
+
673
+ Parameters:
674
+ config ([`RWKV7Qwen3Config`]):
675
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
676
+ load the weights associated with the model, only the configuration. Check out the
677
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
678
+ """
679
+
680
+
681
+ @add_start_docstrings(
682
+ "The bare Qwen3 Model outputting raw hidden-states without any specific head on top.",
683
+ RWKV7QWEN3_START_DOCSTRING,
684
+ )
685
+ class RWKV7Qwen3PreTrainedModel(PreTrainedModel):
686
+ config_class = RWKV7Qwen3Config
687
+ base_model_prefix = "model"
688
+ supports_gradient_checkpointing = True
689
+ _no_split_modules = ["RWKV7Qwen3DecoderLayer"]
690
+ _skip_keys_device_placement = "past_key_values"
691
+ _supports_flash_attn_2 = True
692
+ _supports_sdpa = True
693
+ _supports_cache_class = True
694
+ _supports_quantized_cache = True
695
+ _supports_static_cache = True
696
+
697
+ def _init_weights(self, module):
698
+ std = self.config.initializer_range
699
+ if isinstance(module, nn.Linear):
700
+ module.weight.data.normal_(mean=0.0, std=std)
701
+ if module.bias is not None:
702
+ module.bias.data.zero_()
703
+ elif isinstance(module, nn.Embedding):
704
+ module.weight.data.normal_(mean=0.0, std=std)
705
+ if module.padding_idx is not None:
706
+ module.weight.data[module.padding_idx].zero_()
707
+
708
+
709
+ RWKV7QWEN3_INPUTS_DOCSTRING = r"""
710
+ Args:
711
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
712
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
713
+ it.
714
+
715
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
716
+ [`PreTrainedTokenizer.__call__`] for details.
717
+
718
+ [What are input IDs?](../glossary#input-ids)
719
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
720
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
721
+
722
+ - 1 for tokens that are **not masked**,
723
+ - 0 for tokens that are **masked**.
724
+
725
+ [What are attention masks?](../glossary#attention-mask)
726
+
727
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
728
+ [`PreTrainedTokenizer.__call__`] for details.
729
+
730
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
731
+ `past_key_values`).
732
+
733
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
734
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
735
+ information on the default strategy.
736
+
737
+ - 1 indicates the head is **not masked**,
738
+ - 0 indicates the head is **masked**.
739
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
740
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
741
+ config.n_positions - 1]`.
742
+
743
+ [What are position IDs?](../glossary#position-ids)
744
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
745
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
746
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
747
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
748
+
749
+ Two formats are allowed:
750
+ - a [`~cache_utils.Cache`] instance, see our
751
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
752
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
753
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
754
+ cache format.
755
+
756
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
757
+ legacy cache format will be returned.
758
+
759
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
760
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
761
+ of shape `(batch_size, sequence_length)`.
762
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
763
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
764
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
765
+ model's internal embedding lookup matrix.
766
+ use_cache (`bool`, *optional*):
767
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
768
+ `past_key_values`).
769
+ output_attentions (`bool`, *optional*):
770
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
771
+ tensors for more detail.
772
+ output_hidden_states (`bool`, *optional*):
773
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
774
+ more detail.
775
+ return_dict (`bool`, *optional*):
776
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
777
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
778
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
779
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
780
+ the complete sequence length.
781
+ """
782
+
783
+ @add_start_docstrings(
784
+ "The bare RWKV7Qwen3 Model outputting raw hidden-states without any specific head on top.",
785
+ RWKV7QWEN3_START_DOCSTRING,
786
+ )
787
+ class RWKV7Qwen3Model(RWKV7Qwen3PreTrainedModel):
788
+ """
789
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen3DecoderLayer`]
790
+
791
+ Args:
792
+ config: RWKV7Qwen3Config
793
+ """
794
+
795
+ def __init__(self, config: RWKV7Qwen3Config):
796
+ super().__init__(config)
797
+ self.padding_idx = config.pad_token_id
798
+ self.vocab_size = config.vocab_size
799
+
800
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
801
+ self.layers = nn.ModuleList(
802
+ [RWKV7Qwen3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
803
+ )
804
+ self._attn_implementation = config._attn_implementation
805
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
806
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
807
+
808
+ self.gradient_checkpointing = False
809
+ # Initialize weights and apply final processing
810
+ self.post_init()
811
+
812
+ def get_input_embeddings(self):
813
+ return self.embed_tokens
814
+
815
+ def set_input_embeddings(self, value):
816
+ self.embed_tokens = value
817
+
818
+ @add_start_docstrings_to_model_forward(RWKV7QWEN3_INPUTS_DOCSTRING)
819
+ def forward(
820
+ self,
821
+ input_ids: torch.LongTensor = None,
822
+ attention_mask: Optional[torch.Tensor] = None,
823
+ position_ids: Optional[torch.LongTensor] = None,
824
+ past_key_values: Optional[Cache] = None,
825
+ inputs_embeds: Optional[torch.FloatTensor] = None,
826
+ use_cache: Optional[bool] = None,
827
+ output_attentions: Optional[bool] = None,
828
+ output_hidden_states: Optional[bool] = None,
829
+ return_dict: Optional[bool] = None,
830
+ cache_position: Optional[torch.LongTensor] = None,
831
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
832
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
833
+ output_hidden_states = (
834
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
835
+ )
836
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
837
+
838
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
839
+
840
+ if (input_ids is None) ^ (inputs_embeds is not None):
841
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
842
+
843
+ if self.gradient_checkpointing and self.training and use_cache:
844
+ logger.warning_once(
845
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
846
+ )
847
+ use_cache = False
848
+
849
+ if inputs_embeds is None:
850
+ inputs_embeds = self.embed_tokens(input_ids)
851
+
852
+ if use_cache and not isinstance(past_key_values, RWKV7State):
853
+ past_key_values = RWKV7State()
854
+
855
+ #if cache_position is None:
856
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
857
+ cache_position = torch.arange(
858
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
859
+ )
860
+
861
+ if position_ids is None:
862
+ position_ids = cache_position.unsqueeze(0)
863
+
864
+ # if self.config.num_attention_layers > 0:
865
+ # causal_mask = self._update_causal_mask(
866
+ # attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
867
+ # )
868
+ # else:
869
+ causal_mask = None
870
+
871
+ hidden_states = inputs_embeds
872
+
873
+ # create position embeddings to be shared across the decoder layers
874
+ if self.config.use_rope:
875
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
876
+ else:
877
+ position_embeddings = None
878
+
879
+ # decoder layers
880
+ all_hidden_states = () if output_hidden_states else None
881
+ all_self_attns = () if output_attentions else None
882
+ next_decoder_cache = None
883
+ v_first = None
884
+
885
+ for decoder_layer in self.layers:
886
+ if decoder_layer.layer_idx <= self.config.num_hidden_layers - self.config.num_attention_layers:
887
+ stopped_residual = hidden_states
888
+ if output_hidden_states:
889
+ all_hidden_states += (hidden_states,)
890
+
891
+ if self.gradient_checkpointing and self.training:
892
+ layer_outputs = self._gradient_checkpointing_func(
893
+ decoder_layer.__call__,
894
+ hidden_states,
895
+ stopped_residual,
896
+ causal_mask,
897
+ position_ids,
898
+ past_key_values,
899
+ output_attentions,
900
+ use_cache,
901
+ cache_position,
902
+ position_embeddings,
903
+ v_first,
904
+ )
905
+ else:
906
+ layer_outputs = decoder_layer(
907
+ hidden_states,
908
+ stopped_residual=stopped_residual,
909
+ attention_mask=causal_mask,
910
+ position_ids=position_ids,
911
+ past_key_value=past_key_values,
912
+ output_attentions=output_attentions,
913
+ use_cache=use_cache,
914
+ cache_position=cache_position,
915
+ position_embeddings=position_embeddings,
916
+ v_first=v_first,
917
+ )
918
+
919
+ hidden_states = layer_outputs[0]
920
+ v_first = layer_outputs[1]
921
+
922
+ if output_attentions:
923
+ all_self_attns += (layer_outputs[2],)
924
+
925
+ hidden_states = self.norm(hidden_states)
926
+
927
+ # add hidden states from the last decoder layer
928
+ if output_hidden_states:
929
+ all_hidden_states += (hidden_states,)
930
+
931
+ #if return_legacy_cache:
932
+ # next_cache = next_cache.to_legacy_cache()
933
+
934
+ if not return_dict:
935
+ return tuple(v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None)
936
+ return BaseModelOutputWithPast(
937
+ last_hidden_state=hidden_states,
938
+ past_key_values=past_key_values,
939
+ hidden_states=all_hidden_states,
940
+ attentions=all_self_attns,
941
+ )
942
+
943
+ class RWKV7Qwen3ForCausalLM(RWKV7Qwen3PreTrainedModel, GenerationMixin):
944
+ _tied_weights_keys = ["lm_head.weight"]
945
+
946
+ def __init__(self, config):
947
+ super().__init__(config)
948
+ self.model = RWKV7Qwen3Model(config)
949
+ self.vocab_size = config.vocab_size
950
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
951
+
952
+ # Initialize weights and apply final processing
953
+ self.post_init()
954
+
955
+ def get_input_embeddings(self):
956
+ return self.model.embed_tokens
957
+
958
+ def set_input_embeddings(self, value):
959
+ self.model.embed_tokens = value
960
+
961
+ def get_output_embeddings(self):
962
+ return self.lm_head
963
+
964
+ def set_output_embeddings(self, new_embeddings):
965
+ self.lm_head = new_embeddings
966
+
967
+ def set_decoder(self, decoder):
968
+ self.model = decoder
969
+
970
+ def get_decoder(self):
971
+ return self.model
972
+
973
+ @add_start_docstrings_to_model_forward(RWKV7QWEN3_INPUTS_DOCSTRING)
974
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
975
+ def forward(
976
+ self,
977
+ input_ids: torch.LongTensor = None,
978
+ attention_mask: Optional[torch.Tensor] = None,
979
+ position_ids: Optional[torch.LongTensor] = None,
980
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
981
+ inputs_embeds: Optional[torch.FloatTensor] = None,
982
+ labels: Optional[torch.LongTensor] = None,
983
+ use_cache: Optional[bool] = None,
984
+ output_attentions: Optional[bool] = None,
985
+ output_hidden_states: Optional[bool] = None,
986
+ return_dict: Optional[bool] = None,
987
+ cache_position: Optional[torch.LongTensor] = None,
988
+ num_logits_to_keep: int = 0,
989
+ **loss_kwargs,
990
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
991
+ r"""
992
+ Args:
993
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
994
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
995
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
996
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
997
+
998
+ num_logits_to_keep (`int`, *optional*):
999
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1000
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1001
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1002
+
1003
+ Returns:
1004
+
1005
+ Example:
1006
+
1007
+ ```python
1008
+ >>> from transformers import AutoTokenizer, RWKV7Qwen3ForCausalLM
1009
+
1010
+ >>> model = RWKV7Qwen3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1011
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1012
+
1013
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1014
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1015
+
1016
+ >>> # Generate
1017
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1018
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1019
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1020
+ ```"""
1021
+
1022
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1023
+ output_hidden_states = (
1024
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1025
+ )
1026
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1027
+
1028
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1029
+ outputs = self.model(
1030
+ input_ids=input_ids,
1031
+ attention_mask=attention_mask,
1032
+ position_ids=position_ids,
1033
+ past_key_values=past_key_values,
1034
+ inputs_embeds=inputs_embeds,
1035
+ use_cache=use_cache,
1036
+ output_attentions=output_attentions,
1037
+ output_hidden_states=output_hidden_states,
1038
+ return_dict=return_dict,
1039
+ cache_position=cache_position,
1040
+ )
1041
+
1042
+ hidden_states = outputs[0]
1043
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1044
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1045
+
1046
+ loss = None
1047
+ if labels is not None:
1048
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
1049
+
1050
+ if not return_dict:
1051
+ output = (logits,) + outputs[1:]
1052
+ return (loss,) + output if loss is not None else output
1053
+
1054
+ return CausalLMOutputWithPast(
1055
+ loss=loss,
1056
+ logits=logits,
1057
+ past_key_values=outputs.past_key_values,
1058
+ hidden_states=outputs.hidden_states,
1059
+ attentions=outputs.attentions,
1060
+ )
1061
+
1062
+ @add_start_docstrings(
1063
+ """
1064
+ The RWKV7Qwen3 Model transformer with a sequence classification head on top (linear layer).
1065
+
1066
+ [`RWKV7Qwen3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1067
+ (e.g. GPT-2) do.
1068
+
1069
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1070
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1071
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1072
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1073
+ each row of the batch).
1074
+ """,
1075
+ RWKV7QWEN3_START_DOCSTRING,
1076
+ )
1077
+ class RWKV7Qwen3ForSequenceClassification(RWKV7Qwen3PreTrainedModel):
1078
+ def __init__(self, config):
1079
+ super().__init__(config)
1080
+ self.num_labels = config.num_labels
1081
+ self.model = RWKV7Qwen3Model(config)
1082
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1083
+
1084
+ # Initialize weights and apply final processing
1085
+ self.post_init()
1086
+
1087
+ def get_input_embeddings(self):
1088
+ return self.model.embed_tokens
1089
+
1090
+ def set_input_embeddings(self, value):
1091
+ self.model.embed_tokens = value
1092
+
1093
+ @add_start_docstrings_to_model_forward(RWKV7QWEN3_INPUTS_DOCSTRING)
1094
+ def forward(
1095
+ self,
1096
+ input_ids: torch.LongTensor = None,
1097
+ attention_mask: Optional[torch.Tensor] = None,
1098
+ position_ids: Optional[torch.LongTensor] = None,
1099
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1100
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1101
+ labels: Optional[torch.LongTensor] = None,
1102
+ use_cache: Optional[bool] = None,
1103
+ output_attentions: Optional[bool] = None,
1104
+ output_hidden_states: Optional[bool] = None,
1105
+ return_dict: Optional[bool] = None,
1106
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1107
+ r"""
1108
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1109
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1110
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1111
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1112
+ """
1113
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1114
+
1115
+ transformer_outputs = self.model(
1116
+ input_ids,
1117
+ attention_mask=attention_mask,
1118
+ position_ids=position_ids,
1119
+ past_key_values=past_key_values,
1120
+ inputs_embeds=inputs_embeds,
1121
+ use_cache=use_cache,
1122
+ output_attentions=output_attentions,
1123
+ output_hidden_states=output_hidden_states,
1124
+ return_dict=return_dict,
1125
+ )
1126
+ hidden_states = transformer_outputs[0]
1127
+ logits = self.score(hidden_states)
1128
+
1129
+ if input_ids is not None:
1130
+ batch_size = input_ids.shape[0]
1131
+ else:
1132
+ batch_size = inputs_embeds.shape[0]
1133
+
1134
+ if self.config.pad_token_id is None and batch_size != 1:
1135
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1136
+ if self.config.pad_token_id is None:
1137
+ sequence_lengths = -1
1138
+ else:
1139
+ if input_ids is not None:
1140
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1141
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1142
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1143
+ sequence_lengths = sequence_lengths.to(logits.device)
1144
+ else:
1145
+ sequence_lengths = -1
1146
+
1147
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1148
+
1149
+ loss = None
1150
+ if labels is not None:
1151
+ labels = labels.to(logits.device)
1152
+ if self.config.problem_type is None:
1153
+ if self.num_labels == 1:
1154
+ self.config.problem_type = "regression"
1155
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1156
+ self.config.problem_type = "single_label_classification"
1157
+ else:
1158
+ self.config.problem_type = "multi_label_classification"
1159
+
1160
+ if self.config.problem_type == "regression":
1161
+ loss_fct = MSELoss()
1162
+ if self.num_labels == 1:
1163
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1164
+ else:
1165
+ loss = loss_fct(pooled_logits, labels)
1166
+ elif self.config.problem_type == "single_label_classification":
1167
+ loss_fct = CrossEntropyLoss()
1168
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1169
+ elif self.config.problem_type == "multi_label_classification":
1170
+ loss_fct = BCEWithLogitsLoss()
1171
+ loss = loss_fct(pooled_logits, labels)
1172
+ if not return_dict:
1173
+ output = (pooled_logits,) + transformer_outputs[1:]
1174
+ return ((loss,) + output) if loss is not None else output
1175
+
1176
+ return SequenceClassifierOutputWithPast(
1177
+ loss=loss,
1178
+ logits=pooled_logits,
1179
+ past_key_values=transformer_outputs.past_key_values,
1180
+ hidden_states=transformer_outputs.hidden_states,
1181
+ attentions=transformer_outputs.attentions,
1182
+ )
1183
+
1184
+
1185
+ @add_start_docstrings(
1186
+ """
1187
+ The RWKV7Qwen3 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1188
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1189
+ """,
1190
+ RWKV7QWEN3_START_DOCSTRING,
1191
+ )
1192
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->RWKV7Qwen3, LLAMA->RWKV7Qwen3
1193
+ class RWKV7Qwen3ForTokenClassification(RWKV7Qwen3PreTrainedModel):
1194
+ def __init__(self, config):
1195
+ super().__init__(config)
1196
+ self.num_labels = config.num_labels
1197
+ self.model = RWKV7Qwen3Model(config)
1198
+ if getattr(config, "classifier_dropout", None) is not None:
1199
+ classifier_dropout = config.classifier_dropout
1200
+ elif getattr(config, "hidden_dropout", None) is not None:
1201
+ classifier_dropout = config.hidden_dropout
1202
+ else:
1203
+ classifier_dropout = 0.1
1204
+ self.dropout = nn.Dropout(classifier_dropout)
1205
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1206
+
1207
+ # Initialize weights and apply final processing
1208
+ self.post_init()
1209
+
1210
+ def get_input_embeddings(self):
1211
+ return self.model.embed_tokens
1212
+
1213
+ def set_input_embeddings(self, value):
1214
+ self.model.embed_tokens = value
1215
+
1216
+ @add_start_docstrings_to_model_forward(RWKV7QWEN3_INPUTS_DOCSTRING)
1217
+ @add_code_sample_docstrings(
1218
+ checkpoint=_CHECKPOINT_FOR_DOC,
1219
+ output_type=TokenClassifierOutput,
1220
+ config_class=_CONFIG_FOR_DOC,
1221
+ )
1222
+ def forward(
1223
+ self,
1224
+ input_ids: Optional[torch.LongTensor] = None,
1225
+ attention_mask: Optional[torch.Tensor] = None,
1226
+ position_ids: Optional[torch.LongTensor] = None,
1227
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1228
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1229
+ labels: Optional[torch.LongTensor] = None,
1230
+ use_cache: Optional[bool] = None,
1231
+ output_attentions: Optional[bool] = None,
1232
+ output_hidden_states: Optional[bool] = None,
1233
+ return_dict: Optional[bool] = None,
1234
+ ) -> Union[Tuple, TokenClassifierOutput]:
1235
+ r"""
1236
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1237
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1238
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1239
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1240
+ """
1241
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1242
+
1243
+ outputs = self.model(
1244
+ input_ids,
1245
+ attention_mask=attention_mask,
1246
+ position_ids=position_ids,
1247
+ past_key_values=past_key_values,
1248
+ inputs_embeds=inputs_embeds,
1249
+ use_cache=use_cache,
1250
+ output_attentions=output_attentions,
1251
+ output_hidden_states=output_hidden_states,
1252
+ return_dict=return_dict,
1253
+ )
1254
+ sequence_output = outputs[0]
1255
+ sequence_output = self.dropout(sequence_output)
1256
+ logits = self.score(sequence_output)
1257
+
1258
+ loss = None
1259
+ if labels is not None:
1260
+ loss = self.loss_function(logits, labels, self.config)
1261
+
1262
+ if not return_dict:
1263
+ output = (logits,) + outputs[2:]
1264
+ return ((loss,) + output) if loss is not None else output
1265
+
1266
+ return TokenClassifierOutput(
1267
+ loss=loss,
1268
+ logits=logits,
1269
+ hidden_states=outputs.hidden_states,
1270
+ attentions=outputs.attentions,
1271
+ )
1272
+
1273
+
1274
+ @add_start_docstrings(
1275
+ """
1276
+ The RWKV7Qwen3 Model transformer with a span classification head on top for extractive question-answering tasks like
1277
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1278
+ """,
1279
+ RWKV7QWEN3_START_DOCSTRING,
1280
+ )
1281
+ # Copied from transformers.models.mistral.modeling_mistral.MistralForQuestionAnswering with Mistral->RWKV7Qwen3, MISTRAL->RWKV7Qwen3
1282
+ class RWKV7Qwen3ForQuestionAnswering(RWKV7Qwen3PreTrainedModel):
1283
+ base_model_prefix = "model"
1284
+
1285
+ # Copied from models.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->RWKV7Qwen3
1286
+ def __init__(self, config):
1287
+ super().__init__(config)
1288
+ self.model = RWKV7Qwen3Model(config)
1289
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1290
+
1291
+ # Initialize weights and apply final processing
1292
+ self.post_init()
1293
+
1294
+ def get_input_embeddings(self):
1295
+ return self.model.embed_tokens
1296
+
1297
+ def set_input_embeddings(self, value):
1298
+ self.model.embed_tokens = value
1299
+
1300
+ @add_start_docstrings_to_model_forward(RWKV7QWEN3_INPUTS_DOCSTRING)
1301
+ def forward(
1302
+ self,
1303
+ input_ids: Optional[torch.LongTensor] = None,
1304
+ attention_mask: Optional[torch.FloatTensor] = None,
1305
+ position_ids: Optional[torch.LongTensor] = None,
1306
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1307
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1308
+ start_positions: Optional[torch.LongTensor] = None,
1309
+ end_positions: Optional[torch.LongTensor] = None,
1310
+ output_attentions: Optional[bool] = None,
1311
+ output_hidden_states: Optional[bool] = None,
1312
+ return_dict: Optional[bool] = None,
1313
+ **kwargs,
1314
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1315
+ r"""
1316
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1317
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1318
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1319
+ are not taken into account for computing the loss.
1320
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1321
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1322
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1323
+ are not taken into account for computing the loss.
1324
+ """
1325
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1326
+
1327
+ outputs = self.model(
1328
+ input_ids,
1329
+ attention_mask=attention_mask,
1330
+ position_ids=position_ids,
1331
+ past_key_values=past_key_values,
1332
+ inputs_embeds=inputs_embeds,
1333
+ output_attentions=output_attentions,
1334
+ output_hidden_states=output_hidden_states,
1335
+ return_dict=return_dict,
1336
+ )
1337
+
1338
+ sequence_output = outputs[0]
1339
+
1340
+ logits = self.qa_outputs(sequence_output)
1341
+ start_logits, end_logits = logits.split(1, dim=-1)
1342
+ start_logits = start_logits.squeeze(-1).contiguous()
1343
+ end_logits = end_logits.squeeze(-1).contiguous()
1344
+
1345
+ loss = None
1346
+ if start_positions is not None and end_positions is not None:
1347
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1348
+
1349
+ if not return_dict:
1350
+ output = (start_logits, end_logits) + outputs[2:]
1351
+ return ((loss,) + output) if loss is not None else output
1352
+
1353
+ return QuestionAnsweringModelOutput(
1354
+ loss=loss,
1355
+ start_logits=start_logits,
1356
+ end_logits=end_logits,
1357
+ hidden_states=outputs.hidden_states,
1358
+ attentions=outputs.attentions,
1359
+ )
tokenization_rwkv7qwen3.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from transformers.models.qwen3.tokenization_qwen3 import Qwen3Tokenizer
2
+
3
+ class RWKV6Qwen3Tokenizer(Qwen3Tokenizer):
4
+ pass
tokenization_rwkv7qwen3_fast.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from transformers.models.qwen2.tokenization_qwen3_fast import Qwen3TokenizerFast
2
+
3
+ class RWKV6Qwen3TokenizerFast(Qwen3TokenizerFast):
4
+ pass
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\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 {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set content = message.content %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is defined and message.reasoning_content is not none %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in message.content %}\n {%- set content = message.content.split('</think>')[-1].lstrip('\\n') %}\n {%- set reasoning_content = message.content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first 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 {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
231
+ "clean_up_tokenization_spaces": false,
232
+ "eos_token": "<|im_end|>",
233
+ "errors": "replace",
234
+ "model_max_length": 131072,
235
+ "pad_token": "<|endoftext|>",
236
+ "split_special_tokens": false,
237
+ "tokenizer_class": "Qwen2Tokenizer",
238
+ "unk_token": null
239
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff