huihui-ai commited on
Commit
a41c866
·
verified ·
1 Parent(s): 0d9aa33

Upload 28 files

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

Git LFS Details

  • SHA256: 445c12f53ea2d6e30e17de9dc1bb6bb7ce8706c6f70c98b80c7f6415ced527cb
  • Pointer size: 133 Bytes
  • Size of remote file: 12.9 MB
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d7b7fdafa
3
+ size 11421896
tokenizer_config.json ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "extra_special_tokens": {},
203
+ "model_max_length": 131072,
204
+ "pad_token": "<|endoftext|>",
205
+ "split_special_tokens": false,
206
+ "tokenizer_class": "Qwen2Tokenizer",
207
+ "unk_token": null
208
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff