SmerkyG commited on
Commit
3d4280c
·
verified ·
1 Parent(s): 81d50ad

Add files using upload-large-folder tool

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