SmerkyG commited on
Commit
259fc0e
·
verified ·
1 Parent(s): 0867e6b

Upload folder using huggingface_hub

Browse files
Files changed (43) hide show
  1. config.json +33 -0
  2. configuration_rwkv7qwen2.py +208 -0
  3. generation_config.json +7 -0
  4. merges.txt +0 -0
  5. model-00001-of-00032.safetensors +3 -0
  6. model-00002-of-00032.safetensors +3 -0
  7. model-00003-of-00032.safetensors +3 -0
  8. model-00004-of-00032.safetensors +3 -0
  9. model-00005-of-00032.safetensors +3 -0
  10. model-00006-of-00032.safetensors +3 -0
  11. model-00007-of-00032.safetensors +3 -0
  12. model-00008-of-00032.safetensors +3 -0
  13. model-00009-of-00032.safetensors +3 -0
  14. model-00010-of-00032.safetensors +3 -0
  15. model-00011-of-00032.safetensors +3 -0
  16. model-00012-of-00032.safetensors +3 -0
  17. model-00013-of-00032.safetensors +3 -0
  18. model-00014-of-00032.safetensors +3 -0
  19. model-00015-of-00032.safetensors +3 -0
  20. model-00016-of-00032.safetensors +3 -0
  21. model-00017-of-00032.safetensors +3 -0
  22. model-00018-of-00032.safetensors +3 -0
  23. model-00019-of-00032.safetensors +3 -0
  24. model-00020-of-00032.safetensors +3 -0
  25. model-00021-of-00032.safetensors +3 -0
  26. model-00022-of-00032.safetensors +3 -0
  27. model-00023-of-00032.safetensors +3 -0
  28. model-00024-of-00032.safetensors +3 -0
  29. model-00025-of-00032.safetensors +3 -0
  30. model-00026-of-00032.safetensors +3 -0
  31. model-00027-of-00032.safetensors +3 -0
  32. model-00028-of-00032.safetensors +3 -0
  33. model-00029-of-00032.safetensors +3 -0
  34. model-00030-of-00032.safetensors +3 -0
  35. model-00031-of-00032.safetensors +3 -0
  36. model-00032-of-00032.safetensors +3 -0
  37. model.safetensors.index.json +0 -0
  38. modeling_rwkv7qwen2.py +1285 -0
  39. tokenization_rwkv7qwen2.py +4 -0
  40. tokenization_rwkv7qwen2_fast.py +4 -0
  41. tokenizer.json +0 -0
  42. tokenizer_config.json +207 -0
  43. vocab.json +0 -0
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "bos_token_id": 151643,
13
+ "eos_token_id": 151643,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 8192,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 29568,
18
+ "max_position_embeddings": 32768,
19
+ "max_window_layers": 70,
20
+ "model_type": "rwkv7qwen2",
21
+ "num_attention_heads": 64,
22
+ "num_hidden_layers": 80,
23
+ "num_key_value_heads": 8,
24
+ "rms_norm_eps": 1e-06,
25
+ "rope_theta": 1000000.0,
26
+ "sliding_window": 131072,
27
+ "tie_word_embeddings": false,
28
+ "torch_dtype": "bfloat16",
29
+ "transformers_version": "4.43.1",
30
+ "use_cache": true,
31
+ "use_sliding_window": false,
32
+ "vocab_size": 152064
33
+ }
configuration_rwkv7qwen2.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ rope_theta=10000.0,
159
+ rope_scaling=None,
160
+ use_sliding_window=False,
161
+ sliding_window=4096,
162
+ max_window_layers=28,
163
+ num_attention_layers=0,
164
+ attention_dropout=0.0,
165
+ attention_bias=True,
166
+ attention_output_bias=False,
167
+ **kwargs,
168
+ ):
169
+ self.vocab_size = vocab_size
170
+ self.max_position_embeddings = max_position_embeddings
171
+ self.hidden_size = hidden_size
172
+ self.intermediate_size = intermediate_size
173
+ self.num_hidden_layers = num_hidden_layers
174
+ self.num_attention_heads = num_attention_heads
175
+ self.use_sliding_window = use_sliding_window
176
+ self.sliding_window = sliding_window if use_sliding_window else None
177
+ self.max_window_layers = max_window_layers
178
+ self.num_attention_layers = num_attention_layers
179
+
180
+ # for backward compatibility
181
+ if num_key_value_heads is None:
182
+ num_key_value_heads = num_attention_heads
183
+
184
+ self.num_key_value_heads = num_key_value_heads
185
+ self.lora_rank_decay = lora_rank_decay
186
+ self.lora_rank_iclr = lora_rank_iclr
187
+ self.lora_rank_value_residual_mix = lora_rank_value_residual_mix
188
+ self.lora_rank_gate = lora_rank_gate
189
+ self.hidden_act = hidden_act
190
+ self.initializer_range = initializer_range
191
+ self.rms_norm_eps = rms_norm_eps
192
+ self.use_cache = use_cache
193
+ self.rope_theta = rope_theta
194
+ self.rope_scaling = rope_scaling
195
+ self.attention_dropout = attention_dropout
196
+ # Validate the correctness of rotary position embeddings parameters
197
+ # BC: if there is a 'type' field, move it to 'rope_type'.
198
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
199
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
200
+ rope_config_validation(self)
201
+
202
+ self.attention_bias = attention_bias
203
+ self.attention_output_bias = attention_output_bias
204
+
205
+ super().__init__(
206
+ tie_word_embeddings=tie_word_embeddings,
207
+ **kwargs,
208
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": false,
4
+ "eos_token_id": 151643,
5
+ "max_new_tokens": 2048,
6
+ "transformers_version": "4.37.0"
7
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7dd2436938c147b57b92f84ed3d359fd2e30e33634d491bba32885cbd332a23f
3
+ size 4630886176
model-00002-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1ff520b5e1b2c7d0470bcc31972bda1f137f8d9414b708d1fdb0de59d9599a5
3
+ size 4561680624
model-00003-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d106fc3d918559722efb39e0e675dcd261c00ebf5dca9e69c31eeb7049a60ead
3
+ size 4904752008
model-00004-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df7bdbdc6e3b9055e8e28e566a5374ad6d79cc3c2c28037802b88190c566cc33
3
+ size 4904752008
model-00005-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:801f04a884247188d0cee0dfb300beaf868674719689979fd8086ce55f7b28f6
3
+ size 4561680664
model-00006-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b5667cc95bf18e20b93d87c4ce8a5ba6d42a9bb9cd4847665e1778adccfa867
3
+ size 4904752096
model-00007-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20a4e65655126230567b00487688f8ea44afd4be1dee2981fa51d9ef7010bcbb
3
+ size 4904752088
model-00008-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1571f3bd942d097dc8c5beced54fc5da91efa848d34f21ce76c4f8367e8782ad
3
+ size 4561680680
model-00009-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3beb5a23fc1964a7139195938d78de48bf654217f8d54d6c1906624ee5ea9278
3
+ size 4904752096
model-00010-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0645ae3d5dcbac2223dcfdc7391d64f3dfcd7e51056b9a1b5eebe7c6af923c5
3
+ size 4904752088
model-00011-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e4ee2eee9b05dbdf6f717ccbe2003c0957fc61b056bf2e440852e4e3b2b43fd
3
+ size 4561680680
model-00012-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f0aa2284731acc691420e87ecb588ffed445637ea9836d69013f97f3109554b
3
+ size 4904752096
model-00013-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4b7ca3c5e02f6acd0394112a16b1cbcba89fa34d750fe0f6f393da82629c060
3
+ size 4904752088
model-00014-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a79e2c01218dc712e2afe09b67bec2ea38f02d956e611baa3c273278e2208282
3
+ size 4561680680
model-00015-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e2dd92406d720fcc02200978bccf4d87d3bc280c390f9d2498cd97511f7e28e
3
+ size 4904752096
model-00016-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f01a2641f29667951093752d16d050c54cd3b3cded0928cf6173acf7aebf90a
3
+ size 4904752088
model-00017-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:906ecef956a7db5779b1a89354d9265d822ab7a4c48823818a0edef5d3778f2a
3
+ size 4561680680
model-00018-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:045f470b4d9db0e299833a630deed0981344d29bb64c6de2135083166f1abb95
3
+ size 4904752096
model-00019-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab5e6c0bafbde65f78946b35f3907bd55d36f6a7a096152d9f047ca772022fe3
3
+ size 4904752088
model-00020-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:afa5c436339d689d8263e54517d6f8723ce20a119885062cf1418c0fa271c7c9
3
+ size 4561680680
model-00021-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a38c4840a3b64bd8579177c37bac3a61150afe2de952bf5bf55674181d1009fd
3
+ size 4904752096
model-00022-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:192e14288758111ade447fa076bad8c03fb5361bf65b23a8244bc135bd8abc60
3
+ size 4904752088
model-00023-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f17aa7923b3d94d8b9143fe48b029fa5c279ceee6a98334cd4819ac001d955e3
3
+ size 4561680680
model-00024-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d245b9574ab49302a56419a79912892df8a1b91a66c84d447de3b3dfc69426d
3
+ size 4904752096
model-00025-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b750cb03bd90f03170e393cf0c47cf9d8cfd2024e5bdc0d617564864b4069bbe
3
+ size 4904752088
model-00026-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93db0b097c76a5f8f7cc9e8883c8f8264740ce1844eb8c79ae361ecf1569fe8b
3
+ size 4561680680
model-00027-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1620c83de77fa5d8658ac3a12b8075c2e6c14f38924cb103a8d074a6907c4a0a
3
+ size 4904752096
model-00028-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24aa2164cb9bf9670d22c30a9a3d4860435971d7b73b19ed1c3948d136c440b8
3
+ size 4904752088
model-00029-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b922d93cc42d6d9d19fdfadd8420d2b115d00a615e429c0e1b20eed09bfa351
3
+ size 4561680680
model-00030-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5deb40484ae1aa6fabd6bc6d757c092c8d61ba4efc107bb4199c0c7cc447f2bd
3
+ size 4904752096
model-00031-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:62e8db8b418827e7f3dbc4e0a34839eaa2b7c60db323e82be0184bfa6b729b6d
3
+ size 2765299056
model-00032-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:100c0e113b5a8898064f001dce0b39e7223cb0dbfd96e9b8cb77001f6fb941eb
3
+ size 2491416704
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_rwkv7qwen2.py ADDED
@@ -0,0 +1,1285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ self.g1 = nn.Parameter(torch.empty(C, lora_rank_gate))
377
+ self.g2 = nn.Parameter(torch.empty(lora_rank_gate, C))
378
+
379
+ self.k_k = nn.Parameter(torch.empty(1,1,C))
380
+ self.k_a = nn.Parameter(torch.empty(1,1,C))
381
+ self.r_k = nn.Parameter(torch.empty(H,N))
382
+
383
+ self.ln_x = nn.GroupNorm(H, C, eps=self.head_dim * 1e-5)
384
+
385
+ def forward(
386
+ self,
387
+ hidden_states: torch.Tensor,
388
+ v_first: Optional[torch.Tensor] = None,
389
+ attention_mask: Optional[torch.Tensor] = None,
390
+ position_ids: Optional[torch.LongTensor] = None,
391
+ past_key_values: Optional[RWKV7State] = None,
392
+ output_attentions: bool = False,
393
+ use_cache: bool = False,
394
+ cache_position: Optional[torch.LongTensor] = None,
395
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
396
+ ):
397
+ if attention_mask is not None:
398
+ assert len(attention_mask.shape) == 2, (
399
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
400
+ "for padding purposes (0 indicating padding). "
401
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
402
+ )
403
+
404
+ output_shift_state = hidden_states[:, -1:].detach().clone()
405
+
406
+ x = hidden_states
407
+
408
+ B, T, C = hidden_states.shape
409
+ H = self.num_heads
410
+ N = self.head_dim
411
+ q_len = T
412
+
413
+ if use_cache and past_key_values is not None and len(past_key_values) > self.layer_idx:
414
+ input_vk_state, input_shift_state = past_key_values[self.layer_idx]
415
+ else:
416
+ input_vk_state, input_shift_state = torch.zeros(B,H,N,N, dtype=torch.float32,device=x.device), torch.zeros_like(x[:, -1:])
417
+
418
+ # NOTE - no need for this without tokenshift
419
+ # if attention_mask is not None:
420
+ # hidden_states = hidden_states.mul(attention_mask[:, -hidden_states.shape[-2]:, None])
421
+
422
+ # shifted = torch.cat([input_shift_state, x[:, :-1]], dim=1)
423
+ # xx = shifted - x
424
+
425
+ # xr = x+xx*self.x_r
426
+ # xw = x+xx*self.x_w
427
+ # xk = x+xx*self.x_k
428
+ # xv = x+xx*self.x_v
429
+ # xa = x+xx*self.x_a
430
+ # xg = x+xx*self.x_g
431
+
432
+ xr = xw = xk = xv = xa = xg = x
433
+
434
+ r = self.q_proj(xr)
435
+ w_lora_result = self.w0 + self.w0 + (torch.tanh(xw @ self.w1) @ self.w2).float()
436
+ k = self.k_proj(xk)
437
+ v = self.v_proj(xv)
438
+ a = torch.sigmoid(self.a0 + (xa @ self.a1) @ self.a2)
439
+ g = torch.sigmoid(xg @ self.g1) @ self.g2
440
+
441
+ if position_embeddings is not None:
442
+ r = r.view(B,T,-1,N)
443
+ k = k.view(B,T,-1,N)
444
+ # r = r.transpose(1,2) # BHTN
445
+ # k = k.transpose(1,2) # B(kvh)TN
446
+ cos, sin = position_embeddings
447
+ # cos, sin = shared.angles.unbind(0)
448
+ r, k = apply_rotary_pos_emb(r, k, cos, sin, unsqueeze_dim=2)
449
+ # r = r.transpose(1,2).view(B,T,-1).to(v.dtype)
450
+ # k = k.transpose(1,2).view(B,T,-1).to(v.dtype)
451
+
452
+ # repeat k/v heads if n_kv_heads < n_heads
453
+ k = k.view(B, T, -1, 1, self.head_dim).expand(-1, -1, -1, self.num_key_value_groups, -1).reshape(B, T, -1)
454
+ v = v.view(B, T, -1, 1, self.head_dim).expand(-1, -1, -1, self.num_key_value_groups, -1).reshape(B, T, -1)
455
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
456
+
457
+ kk = torch.nn.functional.normalize((k * self.k_k).view(B,T,H,-1), dim=-1, p=2.0).view(B,T,-1)
458
+ # k = k * (1 + (a-1) * self.k_a)
459
+ a = 1 + (a-1) * self.k_a
460
+ k = k * a
461
+ if self.layer_idx == 0: v_first = v
462
+ else: v = v + (v_first - v) * torch.sigmoid(self.v0 + (xv @ self.v1) @ self.v2)
463
+
464
+ # dealing with left-padding
465
+ if attention_mask is not None:
466
+ v = v * attention_mask[:, -v.shape[-2]:, None]
467
+
468
+ xx = x
469
+ # if T == 1 or not self.training:
470
+ # w = torch.exp(-0.606531 * torch.sigmoid(w_lora_result)) # 0.606531 = exp(-0.5)
471
+ # output_vk_state = input_vk_state
472
+ # for t in range(T):
473
+ # r_, w_, k_, v_, kk_, a_ = r[:,t], w[:,t], k[:,t], v[:,t], kk[:,t], a[:,t]
474
+ # vk = v_.view(B,H,N,1) @ k_.view(B,H,1,N)
475
+ # ab = (-kk_).view(B,H,N,1) @ (kk_*a_).view(B,H,1,N)
476
+ # output_vk_state = output_vk_state * w_.view(B,H,1,N) + output_vk_state @ ab.float() + vk.float()
477
+ # xx[:,t] = (output_vk_state.to(dtype=x.dtype) @ r_.view(B,H,N,1)).view(B,H*N)
478
+ # # FIXME - support fast triton kernel for non-training pre-fill with state in and out
479
+ # else:
480
+ # FIXME - can simplify to
481
+ # log_w = -math.exp(-0.5) * torch.sigmoid(w_lora_result.float())
482
+ log_neglog_w = - 0.5 - torch.nn.functional.softplus(-w_lora_result)
483
+ log_w = -log_neglog_w.float().exp()
484
+
485
+ 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]]
486
+ if self.training:
487
+ xx, output_vk_state = chunk_rwkv7(r, log_w, k, v, -kk, kk*a, initial_state=input_vk_state, output_final_state=use_cache)
488
+ else:
489
+ xx, output_vk_state = fused_recurrent_rwkv7(r, log_w, k, v, -kk, kk*a, initial_state=input_vk_state, output_final_state=use_cache)
490
+
491
+ xx = torch.nn.functional.group_norm(xx.view(B*T,H*N), num_groups=H, weight=self.ln_x.weight, bias=self.ln_x.bias, eps = self.ln_x.eps).view(B,T,H*N)
492
+ # xx = xx + ((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)
493
+ xx = self.o_proj(xx * g)
494
+
495
+ output_final_state = not self.training and use_cache and past_key_values is not None
496
+ if output_final_state:
497
+ past_key_values.update(output_vk_state, output_shift_state, q_len, self.layer_idx)
498
+
499
+ return xx, v_first
500
+
501
+ class RWKV7Qwen2DecoderLayer(nn.Module):
502
+ def __init__(self, config: RWKV7Qwen2Config, layer_idx: int):
503
+ nn.Module.__init__(self)
504
+ self.hidden_size = config.hidden_size
505
+
506
+ if layer_idx >= config.num_hidden_layers - config.num_attention_layers:
507
+ self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
508
+ else:
509
+ self.self_attn = RWKV7Attention(config, layer_idx)
510
+
511
+ self.mlp = Qwen2MLP(config)
512
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
513
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
514
+
515
+ def forward(
516
+ self,
517
+ hidden_states: torch.Tensor,
518
+ v_first: Optional[torch.Tensor],
519
+ attention_mask: Optional[torch.Tensor] = None,
520
+ position_ids: Optional[torch.LongTensor] = None,
521
+ past_key_values: Optional[Cache] = None,
522
+ output_attentions: Optional[bool] = False,
523
+ use_cache: Optional[bool] = False,
524
+ cache_position: Optional[torch.LongTensor] = None,
525
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
526
+ **kwargs,
527
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
528
+ residual = hidden_states
529
+
530
+ hidden_states = self.input_layernorm(hidden_states)
531
+
532
+ # Self Attention
533
+ hidden_states, v_first = self.self_attn(
534
+ hidden_states=hidden_states,
535
+ v_first=v_first,
536
+ attention_mask=attention_mask,
537
+ position_ids=position_ids,
538
+ past_key_values=past_key_values,
539
+ output_attentions=output_attentions,
540
+ use_cache=use_cache,
541
+ cache_position=cache_position,
542
+ position_embeddings=position_embeddings,
543
+ )
544
+ hidden_states = residual + hidden_states
545
+
546
+ # Fully Connected
547
+ residual = hidden_states
548
+ hidden_states = self.post_attention_layernorm(hidden_states)
549
+ hidden_states = self.mlp(hidden_states)
550
+ hidden_states = residual + hidden_states
551
+
552
+ outputs = (hidden_states, v_first,)
553
+
554
+ if output_attentions:
555
+ outputs += (self_attn_weights,)
556
+
557
+ return outputs
558
+
559
+
560
+
561
+ RWKV7QWEN2_START_DOCSTRING = r"""
562
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
563
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
564
+ etc.)
565
+
566
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
567
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
568
+ and behavior.
569
+
570
+ Parameters:
571
+ config ([`RWKV7Qwen2Config`]):
572
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
573
+ load the weights associated with the model, only the configuration. Check out the
574
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
575
+ """
576
+
577
+
578
+ @add_start_docstrings(
579
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
580
+ RWKV7QWEN2_START_DOCSTRING,
581
+ )
582
+ class RWKV7Qwen2PreTrainedModel(PreTrainedModel):
583
+ config_class = RWKV7Qwen2Config
584
+ base_model_prefix = "model"
585
+ supports_gradient_checkpointing = True
586
+ _no_split_modules = ["RWKV7Qwen2DecoderLayer"]
587
+ _skip_keys_device_placement = "past_key_values"
588
+ _supports_flash_attn_2 = True
589
+ _supports_sdpa = True
590
+ _supports_cache_class = True
591
+ _supports_quantized_cache = True
592
+ _supports_static_cache = True
593
+
594
+ def _init_weights(self, module):
595
+ std = self.config.initializer_range
596
+ if isinstance(module, nn.Linear):
597
+ module.weight.data.normal_(mean=0.0, std=std)
598
+ if module.bias is not None:
599
+ module.bias.data.zero_()
600
+ elif isinstance(module, nn.Embedding):
601
+ module.weight.data.normal_(mean=0.0, std=std)
602
+ if module.padding_idx is not None:
603
+ module.weight.data[module.padding_idx].zero_()
604
+
605
+
606
+ RWKV7QWEN2_INPUTS_DOCSTRING = r"""
607
+ Args:
608
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
609
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
610
+ it.
611
+
612
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
613
+ [`PreTrainedTokenizer.__call__`] for details.
614
+
615
+ [What are input IDs?](../glossary#input-ids)
616
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
617
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
618
+
619
+ - 1 for tokens that are **not masked**,
620
+ - 0 for tokens that are **masked**.
621
+
622
+ [What are attention masks?](../glossary#attention-mask)
623
+
624
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
625
+ [`PreTrainedTokenizer.__call__`] for details.
626
+
627
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
628
+ `past_key_values`).
629
+
630
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
631
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
632
+ information on the default strategy.
633
+
634
+ - 1 indicates the head is **not masked**,
635
+ - 0 indicates the head is **masked**.
636
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
637
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
638
+ config.n_positions - 1]`.
639
+
640
+ [What are position IDs?](../glossary#position-ids)
641
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
642
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
643
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
644
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
645
+
646
+ Two formats are allowed:
647
+ - a [`~cache_utils.Cache`] instance, see our
648
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
649
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
650
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
651
+ cache format.
652
+
653
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
654
+ legacy cache format will be returned.
655
+
656
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
657
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
658
+ of shape `(batch_size, sequence_length)`.
659
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
660
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
661
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
662
+ model's internal embedding lookup matrix.
663
+ use_cache (`bool`, *optional*):
664
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
665
+ `past_key_values`).
666
+ output_attentions (`bool`, *optional*):
667
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
668
+ tensors for more detail.
669
+ output_hidden_states (`bool`, *optional*):
670
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
671
+ more detail.
672
+ return_dict (`bool`, *optional*):
673
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
674
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
675
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
676
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
677
+ the complete sequence length.
678
+ """
679
+
680
+ @add_start_docstrings(
681
+ "The bare RWKV7Qwen2 Model outputting raw hidden-states without any specific head on top.",
682
+ RWKV7QWEN2_START_DOCSTRING,
683
+ )
684
+ class RWKV7Qwen2Model(RWKV7Qwen2PreTrainedModel):
685
+ """
686
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
687
+
688
+ Args:
689
+ config: RWKV7Qwen2Config
690
+ """
691
+
692
+ def __init__(self, config: RWKV7Qwen2Config):
693
+ super().__init__(config)
694
+ self.padding_idx = config.pad_token_id
695
+ self.vocab_size = config.vocab_size
696
+
697
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
698
+ self.layers = nn.ModuleList(
699
+ [RWKV7Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
700
+ )
701
+ self._attn_implementation = config._attn_implementation
702
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
703
+ self.rotary_emb = Qwen2RotaryEmbedding(config=config)
704
+
705
+ self.gradient_checkpointing = False
706
+ # Initialize weights and apply final processing
707
+ self.post_init()
708
+
709
+ def get_input_embeddings(self):
710
+ return self.embed_tokens
711
+
712
+ def set_input_embeddings(self, value):
713
+ self.embed_tokens = value
714
+
715
+ @add_start_docstrings_to_model_forward(RWKV7QWEN2_INPUTS_DOCSTRING)
716
+ def forward(
717
+ self,
718
+ input_ids: torch.LongTensor = None,
719
+ attention_mask: Optional[torch.Tensor] = None,
720
+ position_ids: Optional[torch.LongTensor] = None,
721
+ past_key_values: Optional[Cache] = None,
722
+ inputs_embeds: Optional[torch.FloatTensor] = None,
723
+ use_cache: Optional[bool] = None,
724
+ output_attentions: Optional[bool] = None,
725
+ output_hidden_states: Optional[bool] = None,
726
+ return_dict: Optional[bool] = None,
727
+ cache_position: Optional[torch.LongTensor] = None,
728
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
729
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
730
+ output_hidden_states = (
731
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
732
+ )
733
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
734
+
735
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
736
+
737
+ if (input_ids is None) ^ (inputs_embeds is not None):
738
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
739
+
740
+ if self.gradient_checkpointing and self.training:
741
+ if use_cache:
742
+ logger.warning_once(
743
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
744
+ )
745
+ use_cache = False
746
+
747
+ if inputs_embeds is None:
748
+ inputs_embeds = self.embed_tokens(input_ids)
749
+
750
+ if use_cache and not isinstance(past_key_values, RWKV7State):
751
+ past_key_values = RWKV7State()
752
+
753
+ if cache_position is None:
754
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
755
+ cache_position = torch.arange(
756
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
757
+ )
758
+
759
+ if position_ids is None:
760
+ position_ids = cache_position.unsqueeze(0)
761
+
762
+ # causal_mask = self._update_causal_mask(
763
+ # attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
764
+ # )
765
+
766
+ causal_mask = None
767
+
768
+ hidden_states = inputs_embeds
769
+
770
+ # create position embeddings to be shared across the decoder layers
771
+ #position_embeddings = None
772
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
773
+
774
+ # decoder layers
775
+ all_hidden_states = () if output_hidden_states else None
776
+ all_self_attns = () if output_attentions else None
777
+ next_decoder_cache = None
778
+ v_first = None
779
+
780
+ for decoder_layer in self.layers:
781
+ if output_hidden_states:
782
+ all_hidden_states += (hidden_states,)
783
+
784
+ if self.gradient_checkpointing and self.training:
785
+ layer_outputs = self._gradient_checkpointing_func(
786
+ decoder_layer.__call__,
787
+ hidden_states,
788
+ causal_mask,
789
+ position_ids,
790
+ past_key_values,
791
+ output_attentions,
792
+ use_cache,
793
+ cache_position,
794
+ position_embeddings,
795
+ v_first,
796
+ )
797
+ else:
798
+ layer_outputs = decoder_layer(
799
+ hidden_states,
800
+ attention_mask=attention_mask,
801
+ position_ids=position_ids,
802
+ past_key_values=past_key_values,
803
+ output_attentions=output_attentions,
804
+ use_cache=use_cache,
805
+ cache_position=cache_position,
806
+ position_embeddings=position_embeddings,
807
+ v_first=v_first,
808
+ )
809
+
810
+ hidden_states = layer_outputs[0]
811
+ v_first = layer_outputs[1]
812
+
813
+ if output_attentions:
814
+ all_self_attns += (layer_outputs[2],)
815
+
816
+ hidden_states = self.norm(hidden_states)
817
+
818
+ # add hidden states from the last decoder layer
819
+ if output_hidden_states:
820
+ all_hidden_states += (hidden_states,)
821
+
822
+ #if return_legacy_cache:
823
+ # next_cache = next_cache.to_legacy_cache()
824
+
825
+ if not return_dict:
826
+ return tuple(v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None)
827
+ return BaseModelOutputWithPast(
828
+ last_hidden_state=hidden_states,
829
+ past_key_values=past_key_values,
830
+ hidden_states=all_hidden_states,
831
+ attentions=all_self_attns,
832
+ )
833
+
834
+ class RWKV7Qwen2ForCausalLM(RWKV7Qwen2PreTrainedModel, GenerationMixin):
835
+ _tied_weights_keys = ["lm_head.weight"]
836
+
837
+ def __init__(self, config):
838
+ super().__init__(config)
839
+ self.model = RWKV7Qwen2Model(config)
840
+ self.vocab_size = config.vocab_size
841
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
842
+
843
+ # Initialize weights and apply final processing
844
+ self.post_init()
845
+
846
+ def get_input_embeddings(self):
847
+ return self.model.embed_tokens
848
+
849
+ def set_input_embeddings(self, value):
850
+ self.model.embed_tokens = value
851
+
852
+ def get_output_embeddings(self):
853
+ return self.lm_head
854
+
855
+ def set_output_embeddings(self, new_embeddings):
856
+ self.lm_head = new_embeddings
857
+
858
+ def set_decoder(self, decoder):
859
+ self.model = decoder
860
+
861
+ def get_decoder(self):
862
+ return self.model
863
+
864
+ @add_start_docstrings_to_model_forward(RWKV7QWEN2_INPUTS_DOCSTRING)
865
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
866
+ def forward(
867
+ self,
868
+ input_ids: torch.LongTensor = None,
869
+ attention_mask: Optional[torch.Tensor] = None,
870
+ position_ids: Optional[torch.LongTensor] = None,
871
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
872
+ inputs_embeds: Optional[torch.FloatTensor] = None,
873
+ labels: Optional[torch.LongTensor] = None,
874
+ use_cache: Optional[bool] = None,
875
+ output_attentions: Optional[bool] = None,
876
+ output_hidden_states: Optional[bool] = None,
877
+ return_dict: Optional[bool] = None,
878
+ cache_position: Optional[torch.LongTensor] = None,
879
+ num_logits_to_keep: int = 0,
880
+ **loss_kwargs,
881
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
882
+ r"""
883
+ Args:
884
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
885
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
886
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
887
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
888
+
889
+ num_logits_to_keep (`int`, *optional*):
890
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
891
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
892
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
893
+
894
+ Returns:
895
+
896
+ Example:
897
+
898
+ ```python
899
+ >>> from transformers import AutoTokenizer, RWKV7Qwen2ForCausalLM
900
+
901
+ >>> model = RWKV7Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
902
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
903
+
904
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
905
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
906
+
907
+ >>> # Generate
908
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
909
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
910
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
911
+ ```"""
912
+
913
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
914
+ output_hidden_states = (
915
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
916
+ )
917
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
918
+
919
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
920
+ outputs = self.model(
921
+ input_ids=input_ids,
922
+ attention_mask=attention_mask,
923
+ position_ids=position_ids,
924
+ past_key_values=past_key_values,
925
+ inputs_embeds=inputs_embeds,
926
+ use_cache=use_cache,
927
+ output_attentions=output_attentions,
928
+ output_hidden_states=output_hidden_states,
929
+ return_dict=return_dict,
930
+ cache_position=cache_position,
931
+ )
932
+
933
+ hidden_states = outputs[0]
934
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
935
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
936
+
937
+ loss = None
938
+ if labels is not None:
939
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
940
+
941
+ if not return_dict:
942
+ output = (logits,) + outputs[1:]
943
+ return (loss,) + output if loss is not None else output
944
+
945
+ return CausalLMOutputWithPast(
946
+ loss=loss,
947
+ logits=logits,
948
+ past_key_values=outputs.past_key_values,
949
+ hidden_states=outputs.hidden_states,
950
+ attentions=outputs.attentions,
951
+ )
952
+
953
+ def prepare_inputs_for_generation(
954
+ self,
955
+ input_ids: torch.LongTensor,
956
+ past_key_values: Optional[Cache] = None,
957
+ attention_mask: Optional[torch.LongTensor] = None,
958
+ inputs_embeds: Optional[torch.FloatTensor] = None,
959
+ cache_position: Optional[torch.LongTensor] = None,
960
+ **kwargs,
961
+ ):
962
+ # only last token for `inputs_ids` if the `past_key_values` is not empty.
963
+ if past_key_values is not None and len(past_key_values) > 0:
964
+ input_ids = input_ids[:, -1:]
965
+
966
+ model_inputs = {
967
+ 'past_key_values': past_key_values,
968
+ 'attention_mask': attention_mask,
969
+ 'cache_position': cache_position,
970
+ }
971
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
972
+ if inputs_embeds is not None and past_key_values is None:
973
+ model_inputs['inputs_embeds'] = inputs_embeds
974
+ else:
975
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
976
+ # recompiles graphs as the stride of the inputs is a guard.
977
+ # Ref: https://github.com/huggingface/transformers/pull/29114
978
+ # TODO: use `next_tokens` directly instead.
979
+ model_inputs['input_ids'] = input_ids.contiguous()
980
+
981
+ model_inputs.update(**kwargs)
982
+
983
+ # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)
984
+ model_inputs.pop("labels", None)
985
+
986
+ return model_inputs
987
+
988
+ @add_start_docstrings(
989
+ """
990
+ The RWKV7Qwen2 Model transformer with a sequence classification head on top (linear layer).
991
+
992
+ [`RWKV7Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
993
+ (e.g. GPT-2) do.
994
+
995
+ Since it does classification on the last token, it requires to know the position of the last token. If a
996
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
997
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
998
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
999
+ each row of the batch).
1000
+ """,
1001
+ RWKV7QWEN2_START_DOCSTRING,
1002
+ )
1003
+ class RWKV7Qwen2ForSequenceClassification(RWKV7Qwen2PreTrainedModel):
1004
+ def __init__(self, config):
1005
+ super().__init__(config)
1006
+ self.num_labels = config.num_labels
1007
+ self.model = RWKV7Qwen2Model(config)
1008
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1009
+
1010
+ # Initialize weights and apply final processing
1011
+ self.post_init()
1012
+
1013
+ def get_input_embeddings(self):
1014
+ return self.model.embed_tokens
1015
+
1016
+ def set_input_embeddings(self, value):
1017
+ self.model.embed_tokens = value
1018
+
1019
+ @add_start_docstrings_to_model_forward(RWKV7QWEN2_INPUTS_DOCSTRING)
1020
+ def forward(
1021
+ self,
1022
+ input_ids: torch.LongTensor = None,
1023
+ attention_mask: Optional[torch.Tensor] = None,
1024
+ position_ids: Optional[torch.LongTensor] = None,
1025
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1026
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1027
+ labels: Optional[torch.LongTensor] = None,
1028
+ use_cache: Optional[bool] = None,
1029
+ output_attentions: Optional[bool] = None,
1030
+ output_hidden_states: Optional[bool] = None,
1031
+ return_dict: Optional[bool] = None,
1032
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1033
+ r"""
1034
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1035
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1036
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1037
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1038
+ """
1039
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1040
+
1041
+ transformer_outputs = self.model(
1042
+ input_ids,
1043
+ attention_mask=attention_mask,
1044
+ position_ids=position_ids,
1045
+ past_key_values=past_key_values,
1046
+ inputs_embeds=inputs_embeds,
1047
+ use_cache=use_cache,
1048
+ output_attentions=output_attentions,
1049
+ output_hidden_states=output_hidden_states,
1050
+ return_dict=return_dict,
1051
+ )
1052
+ hidden_states = transformer_outputs[0]
1053
+ logits = self.score(hidden_states)
1054
+
1055
+ if input_ids is not None:
1056
+ batch_size = input_ids.shape[0]
1057
+ else:
1058
+ batch_size = inputs_embeds.shape[0]
1059
+
1060
+ if self.config.pad_token_id is None and batch_size != 1:
1061
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1062
+ if self.config.pad_token_id is None:
1063
+ sequence_lengths = -1
1064
+ else:
1065
+ if input_ids is not None:
1066
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1067
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1068
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1069
+ sequence_lengths = sequence_lengths.to(logits.device)
1070
+ else:
1071
+ sequence_lengths = -1
1072
+
1073
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1074
+
1075
+ loss = None
1076
+ if labels is not None:
1077
+ labels = labels.to(logits.device)
1078
+ if self.config.problem_type is None:
1079
+ if self.num_labels == 1:
1080
+ self.config.problem_type = "regression"
1081
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1082
+ self.config.problem_type = "single_label_classification"
1083
+ else:
1084
+ self.config.problem_type = "multi_label_classification"
1085
+
1086
+ if self.config.problem_type == "regression":
1087
+ loss_fct = MSELoss()
1088
+ if self.num_labels == 1:
1089
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1090
+ else:
1091
+ loss = loss_fct(pooled_logits, labels)
1092
+ elif self.config.problem_type == "single_label_classification":
1093
+ loss_fct = CrossEntropyLoss()
1094
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1095
+ elif self.config.problem_type == "multi_label_classification":
1096
+ loss_fct = BCEWithLogitsLoss()
1097
+ loss = loss_fct(pooled_logits, labels)
1098
+ if not return_dict:
1099
+ output = (pooled_logits,) + transformer_outputs[1:]
1100
+ return ((loss,) + output) if loss is not None else output
1101
+
1102
+ return SequenceClassifierOutputWithPast(
1103
+ loss=loss,
1104
+ logits=pooled_logits,
1105
+ past_key_values=transformer_outputs.past_key_values,
1106
+ hidden_states=transformer_outputs.hidden_states,
1107
+ attentions=transformer_outputs.attentions,
1108
+ )
1109
+
1110
+
1111
+ @add_start_docstrings(
1112
+ """
1113
+ The RWKV7Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1114
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1115
+ """,
1116
+ RWKV7QWEN2_START_DOCSTRING,
1117
+ )
1118
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->RWKV7Qwen2, LLAMA->RWKV7QWEN2
1119
+ class RWKV7Qwen2ForTokenClassification(RWKV7Qwen2PreTrainedModel):
1120
+ def __init__(self, config):
1121
+ super().__init__(config)
1122
+ self.num_labels = config.num_labels
1123
+ self.model = RWKV7Qwen2Model(config)
1124
+ if getattr(config, "classifier_dropout", None) is not None:
1125
+ classifier_dropout = config.classifier_dropout
1126
+ elif getattr(config, "hidden_dropout", None) is not None:
1127
+ classifier_dropout = config.hidden_dropout
1128
+ else:
1129
+ classifier_dropout = 0.1
1130
+ self.dropout = nn.Dropout(classifier_dropout)
1131
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1132
+
1133
+ # Initialize weights and apply final processing
1134
+ self.post_init()
1135
+
1136
+ def get_input_embeddings(self):
1137
+ return self.model.embed_tokens
1138
+
1139
+ def set_input_embeddings(self, value):
1140
+ self.model.embed_tokens = value
1141
+
1142
+ @add_start_docstrings_to_model_forward(RWKV7QWEN2_INPUTS_DOCSTRING)
1143
+ @add_code_sample_docstrings(
1144
+ checkpoint=_CHECKPOINT_FOR_DOC,
1145
+ output_type=TokenClassifierOutput,
1146
+ config_class=_CONFIG_FOR_DOC,
1147
+ )
1148
+ def forward(
1149
+ self,
1150
+ input_ids: Optional[torch.LongTensor] = None,
1151
+ attention_mask: Optional[torch.Tensor] = None,
1152
+ position_ids: Optional[torch.LongTensor] = None,
1153
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1154
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1155
+ labels: Optional[torch.LongTensor] = None,
1156
+ use_cache: Optional[bool] = None,
1157
+ output_attentions: Optional[bool] = None,
1158
+ output_hidden_states: Optional[bool] = None,
1159
+ return_dict: Optional[bool] = None,
1160
+ ) -> Union[Tuple, TokenClassifierOutput]:
1161
+ r"""
1162
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1163
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1164
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1165
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1166
+ """
1167
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1168
+
1169
+ outputs = self.model(
1170
+ input_ids,
1171
+ attention_mask=attention_mask,
1172
+ position_ids=position_ids,
1173
+ past_key_values=past_key_values,
1174
+ inputs_embeds=inputs_embeds,
1175
+ use_cache=use_cache,
1176
+ output_attentions=output_attentions,
1177
+ output_hidden_states=output_hidden_states,
1178
+ return_dict=return_dict,
1179
+ )
1180
+ sequence_output = outputs[0]
1181
+ sequence_output = self.dropout(sequence_output)
1182
+ logits = self.score(sequence_output)
1183
+
1184
+ loss = None
1185
+ if labels is not None:
1186
+ loss = self.loss_function(logits, labels, self.config)
1187
+
1188
+ if not return_dict:
1189
+ output = (logits,) + outputs[2:]
1190
+ return ((loss,) + output) if loss is not None else output
1191
+
1192
+ return TokenClassifierOutput(
1193
+ loss=loss,
1194
+ logits=logits,
1195
+ hidden_states=outputs.hidden_states,
1196
+ attentions=outputs.attentions,
1197
+ )
1198
+
1199
+
1200
+ @add_start_docstrings(
1201
+ """
1202
+ The RWKV7Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
1203
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1204
+ """,
1205
+ RWKV7QWEN2_START_DOCSTRING,
1206
+ )
1207
+ # Copied from transformers.models.mistral.modeling_mistral.MistralForQuestionAnswering with Mistral->RWKV7Qwen2, MISTRAL->RWKV7QWEN2
1208
+ class RWKV7Qwen2ForQuestionAnswering(RWKV7Qwen2PreTrainedModel):
1209
+ base_model_prefix = "model"
1210
+
1211
+ # Copied from models.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->RWKV7Qwen2
1212
+ def __init__(self, config):
1213
+ super().__init__(config)
1214
+ self.model = RWKV7Qwen2Model(config)
1215
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1216
+
1217
+ # Initialize weights and apply final processing
1218
+ self.post_init()
1219
+
1220
+ def get_input_embeddings(self):
1221
+ return self.model.embed_tokens
1222
+
1223
+ def set_input_embeddings(self, value):
1224
+ self.model.embed_tokens = value
1225
+
1226
+ @add_start_docstrings_to_model_forward(RWKV7QWEN2_INPUTS_DOCSTRING)
1227
+ def forward(
1228
+ self,
1229
+ input_ids: Optional[torch.LongTensor] = None,
1230
+ attention_mask: Optional[torch.FloatTensor] = None,
1231
+ position_ids: Optional[torch.LongTensor] = None,
1232
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1233
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1234
+ start_positions: Optional[torch.LongTensor] = None,
1235
+ end_positions: Optional[torch.LongTensor] = None,
1236
+ output_attentions: Optional[bool] = None,
1237
+ output_hidden_states: Optional[bool] = None,
1238
+ return_dict: Optional[bool] = None,
1239
+ **kwargs,
1240
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1241
+ r"""
1242
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1243
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1244
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1245
+ are not taken into account for computing the loss.
1246
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1247
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1248
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1249
+ are not taken into account for computing the loss.
1250
+ """
1251
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1252
+
1253
+ outputs = self.model(
1254
+ input_ids,
1255
+ attention_mask=attention_mask,
1256
+ position_ids=position_ids,
1257
+ past_key_values=past_key_values,
1258
+ inputs_embeds=inputs_embeds,
1259
+ output_attentions=output_attentions,
1260
+ output_hidden_states=output_hidden_states,
1261
+ return_dict=return_dict,
1262
+ )
1263
+
1264
+ sequence_output = outputs[0]
1265
+
1266
+ logits = self.qa_outputs(sequence_output)
1267
+ start_logits, end_logits = logits.split(1, dim=-1)
1268
+ start_logits = start_logits.squeeze(-1).contiguous()
1269
+ end_logits = end_logits.squeeze(-1).contiguous()
1270
+
1271
+ loss = None
1272
+ if start_positions is not None and end_positions is not None:
1273
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1274
+
1275
+ if not return_dict:
1276
+ output = (start_logits, end_logits) + outputs[2:]
1277
+ return ((loss,) + output) if loss is not None else output
1278
+
1279
+ return QuestionAnsweringModelOutput(
1280
+ loss=loss,
1281
+ start_logits=start_logits,
1282
+ end_logits=end_logits,
1283
+ hidden_states=outputs.hidden_states,
1284
+ attentions=outputs.attentions,
1285
+ )
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