Add files using upload-large-folder tool
Browse files- LICENSE-Qwen +52 -0
- NOTICE.txt +2 -0
- config.json +34 -0
- configuration_rwkv6qwen2.py +194 -0
- model-00001-of-00033.safetensors +3 -0
- model-00002-of-00033.safetensors +3 -0
- model-00003-of-00033.safetensors +3 -0
- model-00004-of-00033.safetensors +3 -0
- model-00005-of-00033.safetensors +3 -0
- model-00006-of-00033.safetensors +3 -0
- model-00007-of-00033.safetensors +3 -0
- model-00008-of-00033.safetensors +3 -0
- model-00009-of-00033.safetensors +3 -0
- model-00010-of-00033.safetensors +3 -0
- model-00011-of-00033.safetensors +3 -0
- model-00012-of-00033.safetensors +3 -0
- model-00013-of-00033.safetensors +3 -0
- model-00014-of-00033.safetensors +3 -0
- model-00015-of-00033.safetensors +3 -0
- model-00016-of-00033.safetensors +3 -0
- model-00017-of-00033.safetensors +3 -0
- model-00018-of-00033.safetensors +3 -0
- model-00019-of-00033.safetensors +3 -0
- model-00020-of-00033.safetensors +3 -0
- model-00021-of-00033.safetensors +3 -0
- model-00022-of-00033.safetensors +3 -0
- model-00023-of-00033.safetensors +3 -0
- model-00024-of-00033.safetensors +3 -0
- model-00025-of-00033.safetensors +3 -0
- model-00026-of-00033.safetensors +3 -0
- model-00027-of-00033.safetensors +3 -0
- model-00028-of-00033.safetensors +3 -0
- model-00029-of-00033.safetensors +3 -0
- model-00030-of-00033.safetensors +3 -0
- model-00031-of-00033.safetensors +3 -0
- model-00032-of-00033.safetensors +3 -0
- model-00033-of-00033.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_rwkv6qwen2.py +1169 -0
LICENSE-Qwen
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Qwen LICENSE AGREEMENT
|
2 |
+
|
3 |
+
Qwen LICENSE AGREEMENT Release Date: September 19, 2024
|
4 |
+
|
5 |
+
By clicking to agree or by using or distributing any portion or element of the Qwen Materials, you will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
|
6 |
+
|
7 |
+
1. Definitions
|
8 |
+
a. This Qwen LICENSE AGREEMENT (this "Agreement") shall mean the terms and conditions for use, reproduction, distribution and modification of the Materials as defined by this Agreement.
|
9 |
+
b. "We" (or "Us") shall mean Alibaba Cloud.
|
10 |
+
c. "You" (or "Your") shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Materials for any purpose and in any field of use.
|
11 |
+
d. "Third Parties" shall mean individuals or legal entities that are not under common control with us or you.
|
12 |
+
e. "Qwen" shall mean the large language models, and software and algorithms, consisting of trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing distributed by us.
|
13 |
+
f. "Materials" shall mean, collectively, Alibaba Cloud's proprietary Qwen and Documentation (and any portion thereof) made available under this Agreement.
|
14 |
+
g. "Source" form shall mean the preferred form for making modifications, including but not limited to model source code, documentation source, and configuration files.
|
15 |
+
h. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
16 |
+
|
17 |
+
2. Grant of Rights
|
18 |
+
You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Alibaba Cloud's intellectual property or other rights owned by us embodied in the Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Materials.
|
19 |
+
|
20 |
+
3. Redistribution
|
21 |
+
You may distribute copies or make the Materials, or derivative works thereof, available as part of a product or service that contains any of them, with or without modifications, and in Source or Object form, provided that you meet the following conditions:
|
22 |
+
a. You shall give any other recipients of the Materials or derivative works a copy of this Agreement;
|
23 |
+
b. You shall cause any modified files to carry prominent notices stating that you changed the files;
|
24 |
+
c. You shall retain in all copies of the Materials that you distribute the following attribution notices within a "Notice" text file distributed as a part of such copies: "Qwen is licensed under the Qwen LICENSE AGREEMENT, Copyright (c) Alibaba Cloud. All Rights Reserved."; and
|
25 |
+
d. You may add your own copyright statement to your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of your modifications, or for any such derivative works as a whole, provided your use, reproduction, and distribution of the work otherwise complies with the terms and conditions of this Agreement.
|
26 |
+
|
27 |
+
4. Restrictions
|
28 |
+
If you are commercially using the Materials, and your product or service has more than 100 million monthly active users, you shall request a license from us. You cannot exercise your rights under this Agreement without our express authorization.
|
29 |
+
|
30 |
+
5. Rules of use
|
31 |
+
a. The Materials may be subject to export controls or restrictions in China, the United States or other countries or regions. You shall comply with applicable laws and regulations in your use of the Materials.
|
32 |
+
b. If you use the Materials or any outputs or results therefrom to create, train, fine-tune, or improve an AI model that is distributed or made available, you shall prominently display “Built with Qwen” or “Improved using Qwen” in the related product documentation.
|
33 |
+
|
34 |
+
6. Intellectual Property
|
35 |
+
a. We retain ownership of all intellectual property rights in and to the Materials and derivatives made by or for us. Conditioned upon compliance with the terms and conditions of this Agreement, with respect to any derivative works and modifications of the Materials that are made by you, you are and will be the owner of such derivative works and modifications.
|
36 |
+
b. No trademark license is granted to use the trade names, trademarks, service marks, or product names of us, except as required to fulfill notice requirements under this Agreement or as required for reasonable and customary use in describing and redistributing the Materials.
|
37 |
+
c. If you commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against us or any entity alleging that the Materials or any output therefrom, or any part of the foregoing, infringe any intellectual property or other right owned or licensable by you, then all licenses granted to you under this Agreement shall terminate as of the date such lawsuit or other proceeding is commenced or brought.
|
38 |
+
|
39 |
+
7. Disclaimer of Warranty and Limitation of Liability
|
40 |
+
a. We are not obligated to support, update, provide training for, or develop any further version of the Qwen Materials or to grant any license thereto.
|
41 |
+
b. THE MATERIALS ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. WE MAKE NO WARRANTY AND ASSUME NO RESPONSIBILITY FOR THE SAFETY OR STABILITY OF THE MATERIALS AND ANY OUTPUT THEREFROM.
|
42 |
+
c. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE MATERIALS OR ANY OUTPUT OF IT, NO MATTER HOW IT’S CAUSED.
|
43 |
+
d. You will defend, indemnify and hold harmless us from and against any claim by any third party arising out of or related to your use or distribution of the Materials.
|
44 |
+
|
45 |
+
8. Survival and Termination.
|
46 |
+
a. The term of this Agreement shall commence upon your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.
|
47 |
+
b. We may terminate this Agreement if you breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, you must delete and cease use of the Materials. Sections 7 and 9 shall survive the termination of this Agreement.
|
48 |
+
|
49 |
+
9. Governing Law and Jurisdiction.
|
50 |
+
a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
|
51 |
+
b. The People's Courts in Hangzhou City shall have exclusive jurisdiction over any dispute arising out of this Agreement.
|
52 |
+
|
NOTICE.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
Qwen is licensed under the Qwen LICENSE AGREEMENT, Copyright (c) Alibaba Cloud. All Rights Reserved.
|
2 |
+
|
config.json
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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": 8192,
|
16 |
+
"initializer_range": 0.02,
|
17 |
+
"intermediate_size": 29568,
|
18 |
+
"lora_rank_tokenshift": 160,
|
19 |
+
"max_position_embeddings": 131072,
|
20 |
+
"max_window_layers": 80,
|
21 |
+
"model_type": "rwkv6qwen2",
|
22 |
+
"num_attention_heads": 64,
|
23 |
+
"num_hidden_layers": 80,
|
24 |
+
"num_key_value_heads": 8,
|
25 |
+
"rms_norm_eps": 1e-06,
|
26 |
+
"rope_theta": 1000000.0,
|
27 |
+
"sliding_window": 131072,
|
28 |
+
"tie_word_embeddings": false,
|
29 |
+
"torch_dtype": "bfloat16",
|
30 |
+
"transformers_version": "4.43.1",
|
31 |
+
"use_cache": true,
|
32 |
+
"use_sliding_window": false,
|
33 |
+
"vocab_size": 152064
|
34 |
+
}
|
configuration_rwkv6qwen2.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
lora_rank_tokenshift=None,
|
141 |
+
lora_rank_decay=None,
|
142 |
+
hidden_act="silu",
|
143 |
+
max_position_embeddings=32768,
|
144 |
+
initializer_range=0.02,
|
145 |
+
rms_norm_eps=1e-6,
|
146 |
+
use_cache=True,
|
147 |
+
tie_word_embeddings=False,
|
148 |
+
rope_theta=10000.0,
|
149 |
+
rope_scaling=None,
|
150 |
+
use_sliding_window=False,
|
151 |
+
sliding_window=4096,
|
152 |
+
max_window_layers=28,
|
153 |
+
attention_dropout=0.0,
|
154 |
+
attention_bias=True,
|
155 |
+
attention_output_bias=False,
|
156 |
+
**kwargs,
|
157 |
+
):
|
158 |
+
self.vocab_size = vocab_size
|
159 |
+
self.max_position_embeddings = max_position_embeddings
|
160 |
+
self.hidden_size = hidden_size
|
161 |
+
self.intermediate_size = intermediate_size
|
162 |
+
self.num_hidden_layers = num_hidden_layers
|
163 |
+
self.num_attention_heads = num_attention_heads
|
164 |
+
self.use_sliding_window = use_sliding_window
|
165 |
+
self.sliding_window = sliding_window if use_sliding_window else None
|
166 |
+
self.max_window_layers = max_window_layers
|
167 |
+
|
168 |
+
# for backward compatibility
|
169 |
+
if num_key_value_heads is None:
|
170 |
+
num_key_value_heads = num_attention_heads
|
171 |
+
|
172 |
+
self.num_key_value_heads = num_key_value_heads
|
173 |
+
self.lora_rank_tokenshift = lora_rank_tokenshift
|
174 |
+
self.lora_rank_decay = lora_rank_decay
|
175 |
+
self.hidden_act = hidden_act
|
176 |
+
self.initializer_range = initializer_range
|
177 |
+
self.rms_norm_eps = rms_norm_eps
|
178 |
+
self.use_cache = use_cache
|
179 |
+
self.rope_theta = rope_theta
|
180 |
+
self.rope_scaling = rope_scaling
|
181 |
+
self.attention_dropout = attention_dropout
|
182 |
+
# Validate the correctness of rotary position embeddings parameters
|
183 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
184 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
185 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
186 |
+
rope_config_validation(self)
|
187 |
+
|
188 |
+
self.attention_bias = attention_bias
|
189 |
+
self.attention_output_bias = attention_output_bias
|
190 |
+
|
191 |
+
super().__init__(
|
192 |
+
tie_word_embeddings=tie_word_embeddings,
|
193 |
+
**kwargs,
|
194 |
+
)
|
model-00001-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:44ddc70ab725e2b6804891a9176dc8aca4c1ff76093ec6fcc2a405e20c72eb40
|
3 |
+
size 4878316704
|
model-00002-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:51acf7737824de084a2e2a191d1e92b83a5efd08a458a7a91495d571d1180474
|
3 |
+
size 4809111144
|
model-00003-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3a5254fc422e5e90ac43c8dea012de9cbea415f76746440c9ee4ead21591ca54
|
3 |
+
size 4791455576
|
model-00004-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:23e0316de13f26d2927c197f83c7e1e9090fbb32cc993b27c8a6f4a6c6295cd6
|
3 |
+
size 4809111144
|
model-00005-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ccdbe40538475475cff253536b35ad8ca13779a780ec1054a5623ac83e12c850
|
3 |
+
size 4791455608
|
model-00006-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2d768863a9e1dc6152fc769a9db2ac44383171a5558f24b591a1d6cc36c2e855
|
3 |
+
size 4809111200
|
model-00007-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ffdc49042b1223e9184ddc73c011fd52983ba154abc807938fd9c3874a35fdf4
|
3 |
+
size 4791455640
|
model-00008-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:40a6ac8d40e6bca81c75f82c1dcaee8fc430717909f7069e5c698af99910401a
|
3 |
+
size 4809111200
|
model-00009-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:96a36651fb25dd1e292838c97246cd59dd502d79dc27d504a3bb1c99d632b919
|
3 |
+
size 4791455640
|
model-00010-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6c7421e125f3e9f01632c5920c0f4965f16448e02d0c21b84f46df1b6beae5ba
|
3 |
+
size 4809111200
|
model-00011-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bc591ce8d78e5f6de64433b05d1326d800b540660c49b2b599b9b32b44ef45ac
|
3 |
+
size 4791455640
|
model-00012-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:17826f37c033796ee370069c1947fa04e0e9f22980c298881634614c02b6ff2d
|
3 |
+
size 4809111200
|
model-00013-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e97df13526329d39faabb5cf4b6494cf5e864a3e8804ac65dbdb30cd878594cd
|
3 |
+
size 4791455640
|
model-00014-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:eaf40c7e40eaa2ac092f414b6fb5b7a16b54a9f987c22997bfe04a236956327c
|
3 |
+
size 4809111200
|
model-00015-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e040558cef6f07552721243da1f1289ae584fd8caafd7007aef3bc43196aed03
|
3 |
+
size 4791455640
|
model-00016-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:80278f83398bb2b0a4d69d58a634bfccf605abb4c82de3bcdc06605eb7f23c50
|
3 |
+
size 4809111200
|
model-00017-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c06bbd10c8df48b19b1aa23c0ad7ec5a0df75b7a587da9b14f540b3ec21445d6
|
3 |
+
size 4791455640
|
model-00018-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3d7bd6dbe6972e4220140297f01f473e87537ba0dbe9d51186596ebb98d1bae5
|
3 |
+
size 4809111200
|
model-00019-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fc4fafdd5e748a9451cb1e9aa48d2c365a229d3f856da79b62f701fc9211af23
|
3 |
+
size 4791455640
|
model-00020-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e35af9be118a2cb68c20525d1713d64e6bc46618d5862b03634baf8ad175af3b
|
3 |
+
size 4809111200
|
model-00021-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:36bc3707a19470b6d24cc66c64e3d5db559029e1eb87c543845efc43a880f356
|
3 |
+
size 4791455640
|
model-00022-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f4259990794ec1ec18d45abe0ba420df90cbead105a77627e00bbd1a08bef078
|
3 |
+
size 4809111200
|
model-00023-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:613216a443250be8a19ac2bbb7eb6fa36a12470e19182ababf335b4e0f9e2f25
|
3 |
+
size 4791455640
|
model-00024-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:719b0bf47ee6f0b47812edf223777729ee125dc540ee0dce117391233b92cb19
|
3 |
+
size 4809111200
|
model-00025-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0b79b2c9ed02e7c53b247fa69dc6fb68eb0b150d3164836aed30a9ecf7e20ea8
|
3 |
+
size 4791455640
|
model-00026-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bd6e378e46dee8b7044f228627a53b61373ba4c519aff0ebf51ccbd4c7a8f931
|
3 |
+
size 4809111200
|
model-00027-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b6b623abbe45b2a4ea9948c4b9aef41d237636746b978db266fc6e6e4873ddcb
|
3 |
+
size 4791455640
|
model-00028-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ccf46be4f60b16ac5af92e13e191592fb529cc7f20ecabb551c994d60944d289
|
3 |
+
size 4809111200
|
model-00029-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5b21e0a7551196d743cd10618660a3bb3543f3c2eb3200de192d416e84789403
|
3 |
+
size 4791455640
|
model-00030-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:df9f12c09d6f59814941dae2a801586aeac08fdc6cb5fe0938dbcae3c4841a31
|
3 |
+
size 4809111200
|
model-00031-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0b78e5f2da4470c7fcaa169063269279dd23aad7fc7a91e7cc046361a4832dc1
|
3 |
+
size 4791455640
|
model-00032-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f4b9777e5f4e78f27e69556da29b31eff9c681bad4cfb1be8a85b66ba73b01f0
|
3 |
+
size 4809111200
|
model-00033-of-00033.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e044d6e2a20f5c8697bc543974e3d810749727d3063c304a06ffc0a91a58b1df
|
3 |
+
size 4895988768
|
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,1169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, DynamicCache
|
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 |
+
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 |
+
# ) -> "RWKV6State":
|
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.gla.chunk import chunk_gla
|
209 |
+
from fla.ops.gla.fused_recurrent import fused_recurrent_gla
|
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 RWKV6Attention(nn.Module):
|
217 |
+
def __init__(self, config, layer_idx: Optional[int] = None):
|
218 |
+
super().__init__()
|
219 |
+
self.config = config
|
220 |
+
self.layer_idx = layer_idx
|
221 |
+
if layer_idx is None:
|
222 |
+
logger.warning_once(
|
223 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
224 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
225 |
+
"when creating this class."
|
226 |
+
)
|
227 |
+
|
228 |
+
self.hidden_size = config.hidden_size
|
229 |
+
self.num_heads = config.num_attention_heads
|
230 |
+
self.head_dim = getattr(config, 'head_dim', self.hidden_size // self.num_heads)
|
231 |
+
self.num_key_value_heads = config.num_key_value_heads
|
232 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
233 |
+
self.attention_dropout = config.attention_dropout
|
234 |
+
|
235 |
+
if self.hidden_size % self.num_heads != 0:
|
236 |
+
raise ValueError(
|
237 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
238 |
+
f" and `num_heads`: {self.num_heads})."
|
239 |
+
)
|
240 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
241 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
242 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
243 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=getattr(config, 'attention_output_bias', config.attention_bias))
|
244 |
+
|
245 |
+
self.gate = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
246 |
+
nn.init.zeros_(self.gate.weight)
|
247 |
+
|
248 |
+
n_layer = self.config.num_hidden_layers
|
249 |
+
n_embd = self.hidden_size
|
250 |
+
dim_att = self.num_heads * self.head_dim
|
251 |
+
layer_id = self.layer_idx
|
252 |
+
|
253 |
+
with torch.no_grad():
|
254 |
+
ratio_0_to_1 = layer_id / (n_layer - 1) # 0 to 1
|
255 |
+
ratio_1_to_almost0 = 1.0 - (layer_id / n_layer) # 1 to ~0
|
256 |
+
ddd = torch.ones(1, 1, n_embd)
|
257 |
+
for i in range(n_embd):
|
258 |
+
ddd[0, 0, i] = i / n_embd
|
259 |
+
|
260 |
+
ddd = torch.zeros(1, 1, n_embd)
|
261 |
+
self.time_maa_x = nn.Parameter(1.0 - torch.pow(ddd, ratio_1_to_almost0))
|
262 |
+
self.time_maa_r = nn.Parameter(torch.zeros_like(ddd))
|
263 |
+
self.time_maa_k = nn.Parameter(torch.zeros_like(ddd))
|
264 |
+
self.time_maa_v = nn.Parameter(torch.zeros_like(ddd))
|
265 |
+
self.time_maa_w = nn.Parameter(torch.zeros_like(ddd))
|
266 |
+
self.time_maa_g = nn.Parameter(torch.zeros_like(ddd))
|
267 |
+
|
268 |
+
lora_rank_tokenshift = config.lora_rank_tokenshift or (32 if n_embd < 4096 else 64)
|
269 |
+
lora_rank_decay = config.lora_rank_decay or (64 if n_embd < 4096 else 128)
|
270 |
+
self.time_maa_w2 = nn.Parameter(torch.zeros(5, lora_rank_tokenshift, n_embd).uniform_(-0.01, 0.01))
|
271 |
+
self.time_maa_w1 = nn.Parameter(torch.zeros(n_embd, lora_rank_tokenshift*self.time_maa_w2.size(0)))
|
272 |
+
|
273 |
+
# RWKV-6
|
274 |
+
decay_speed = torch.ones(dim_att)
|
275 |
+
for n in range(dim_att):
|
276 |
+
decay_speed[n] = -6 + 5 * (n / (dim_att - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
|
277 |
+
self.time_decay = nn.Parameter(decay_speed.reshape(1,1,dim_att))
|
278 |
+
self.time_decay_w1 = nn.Parameter(torch.zeros(n_embd, lora_rank_decay))
|
279 |
+
self.time_decay_w2 = nn.Parameter(torch.zeros(lora_rank_decay, dim_att).uniform_(-0.01, 0.01))
|
280 |
+
|
281 |
+
def forward(
|
282 |
+
self,
|
283 |
+
hidden_states: torch.Tensor,
|
284 |
+
attention_mask: Optional[torch.Tensor] = None,
|
285 |
+
position_ids: Optional[torch.LongTensor] = None,
|
286 |
+
past_key_values: Optional[RWKV6State] = None,
|
287 |
+
output_attentions: bool = False,
|
288 |
+
use_cache: bool = False,
|
289 |
+
cache_position: Optional[torch.LongTensor] = None,
|
290 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
291 |
+
):
|
292 |
+
output_shift_state = hidden_states[:, -1:].detach().clone()
|
293 |
+
|
294 |
+
bsz, q_len, hidden_dim = hidden_states.size()
|
295 |
+
H = self.num_heads
|
296 |
+
|
297 |
+
x = hidden_states
|
298 |
+
|
299 |
+
if use_cache and past_key_values is not None and len(past_key_values) > self.layer_idx:
|
300 |
+
input_kv_state, input_shift_state = past_key_values[self.layer_idx]
|
301 |
+
xprev = torch.cat([input_shift_state, x[:, :-1]], dim=1)
|
302 |
+
else:
|
303 |
+
input_kv_state = None
|
304 |
+
xprev = F.pad(x, (0, 0, 1, -1))
|
305 |
+
|
306 |
+
dxprev = xprev - x
|
307 |
+
|
308 |
+
xxx = x + dxprev * self.time_maa_x
|
309 |
+
xxx = torch.tanh(xxx @ self.time_maa_w1).view(bsz*q_len, self.time_maa_w2.size(0), -1).transpose(0, 1)
|
310 |
+
xxx = torch.bmm(xxx, self.time_maa_w2).view(self.time_maa_w2.size(0), bsz, q_len, hidden_dim)
|
311 |
+
|
312 |
+
mr, mk, mv, mw, mg = xxx.unbind(dim=0)
|
313 |
+
xr = x + dxprev * (self.time_maa_r + mr)
|
314 |
+
xk = x + dxprev * (self.time_maa_k + mk)
|
315 |
+
xv = x + dxprev * (self.time_maa_v + mv)
|
316 |
+
xw = x + dxprev * (self.time_maa_w + mw)
|
317 |
+
xg = x + dxprev * (self.time_maa_g + mg)
|
318 |
+
|
319 |
+
query_states = self.q_proj(xr)
|
320 |
+
key_states = self.k_proj(xk)
|
321 |
+
value_states = self.v_proj(xv)
|
322 |
+
decay_states = (self.time_decay + torch.tanh(xw @ self.time_decay_w1) @ self.time_decay_w2).to(query_states.dtype)
|
323 |
+
gate_states = F.sigmoid(self.gate(xg))
|
324 |
+
|
325 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
326 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
327 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
328 |
+
decay_states = decay_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
329 |
+
|
330 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
331 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
332 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
333 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
334 |
+
|
335 |
+
decay_states_log = -decay_states.float().exp()
|
336 |
+
decay_states_log = decay_states_log.clamp(-5) # FIXME - is this necessary?
|
337 |
+
key_states = (key_states * (1 - decay_states_log.exp())).to(key_states.dtype)
|
338 |
+
|
339 |
+
# dealing with left-padding
|
340 |
+
if attention_mask is not None:
|
341 |
+
value_states = value_states * attention_mask[:, None, -value_states.shape[-2]:, None]
|
342 |
+
|
343 |
+
query_states = query_states.to(value_states.dtype)
|
344 |
+
key_states = key_states.to(value_states.dtype)
|
345 |
+
|
346 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
347 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
348 |
+
# cast them back in float16 just to be sure everything works as expected.
|
349 |
+
input_dtype = query_states.dtype
|
350 |
+
if input_dtype == torch.float32:
|
351 |
+
if torch.is_autocast_enabled():
|
352 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
353 |
+
# Handle the case where the model is quantized
|
354 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
355 |
+
target_dtype = self.config._pre_quantization_dtype
|
356 |
+
else:
|
357 |
+
target_dtype = self.q_proj.weight.dtype
|
358 |
+
|
359 |
+
logger.warning_once(
|
360 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
361 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
362 |
+
f" {target_dtype}."
|
363 |
+
)
|
364 |
+
|
365 |
+
query_states = query_states.to(target_dtype)
|
366 |
+
key_states = key_states.to(target_dtype)
|
367 |
+
value_states = value_states.to(target_dtype)
|
368 |
+
|
369 |
+
attn_weights = torch.empty(0, device=x.device)
|
370 |
+
|
371 |
+
scale = query_states.shape[-1] ** -0.5
|
372 |
+
output_final_state = not self.training and use_cache and past_key_values is not None
|
373 |
+
#attn_output, output_kv_state = ChunkGLAFunction.apply(query_states, key_states, value_states, decay_states_log.float(), scale, input_kv_state, output_final_state)
|
374 |
+
#attn_output, output_kv_state = chunk_gla(query_states, key_states, value_states, decay_states_log, scale, input_kv_state, output_final_state)
|
375 |
+
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)
|
376 |
+
|
377 |
+
if output_final_state:
|
378 |
+
past_key_values.update(output_kv_state, output_shift_state, q_len, self.layer_idx)
|
379 |
+
|
380 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
381 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
382 |
+
attn_output = self.o_proj(attn_output * gate_states)
|
383 |
+
|
384 |
+
return attn_output, attn_weights
|
385 |
+
|
386 |
+
class RWKV6Qwen2DecoderLayer(Qwen2DecoderLayer):
|
387 |
+
def __init__(self, config: RWKV6Qwen2Config, layer_idx: int):
|
388 |
+
nn.Module.__init__(self)
|
389 |
+
self.hidden_size = config.hidden_size
|
390 |
+
|
391 |
+
self.self_attn = RWKV6Attention(config, layer_idx) #QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
|
392 |
+
|
393 |
+
self.mlp = Qwen2MLP(config)
|
394 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
395 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
396 |
+
|
397 |
+
def forward(
|
398 |
+
self,
|
399 |
+
hidden_states: torch.Tensor,
|
400 |
+
attention_mask: Optional[torch.Tensor] = None,
|
401 |
+
position_ids: Optional[torch.LongTensor] = None,
|
402 |
+
past_key_values: Optional[Cache] = None,
|
403 |
+
output_attentions: Optional[bool] = False,
|
404 |
+
use_cache: Optional[bool] = False,
|
405 |
+
cache_position: Optional[torch.LongTensor] = None,
|
406 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
407 |
+
**kwargs,
|
408 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
409 |
+
residual = hidden_states
|
410 |
+
|
411 |
+
hidden_states = self.input_layernorm(hidden_states)
|
412 |
+
|
413 |
+
# Self Attention
|
414 |
+
hidden_states, self_attn_weights = self.self_attn(
|
415 |
+
hidden_states=hidden_states,
|
416 |
+
attention_mask=attention_mask,
|
417 |
+
position_ids=position_ids,
|
418 |
+
past_key_values=past_key_values,
|
419 |
+
output_attentions=output_attentions,
|
420 |
+
use_cache=use_cache,
|
421 |
+
cache_position=cache_position,
|
422 |
+
position_embeddings=position_embeddings,
|
423 |
+
**kwargs,
|
424 |
+
)
|
425 |
+
hidden_states = residual + hidden_states
|
426 |
+
|
427 |
+
# Fully Connected
|
428 |
+
residual = hidden_states
|
429 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
430 |
+
hidden_states = self.mlp(hidden_states)
|
431 |
+
hidden_states = residual + hidden_states
|
432 |
+
|
433 |
+
outputs = (hidden_states,)
|
434 |
+
if output_attentions:
|
435 |
+
outputs += (self_attn_weights,)
|
436 |
+
|
437 |
+
return outputs
|
438 |
+
|
439 |
+
RWKV6QWEN2_START_DOCSTRING = r"""
|
440 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
441 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
442 |
+
etc.)
|
443 |
+
|
444 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
445 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
446 |
+
and behavior.
|
447 |
+
|
448 |
+
Parameters:
|
449 |
+
config ([`RWKV6Qwen2Config`]):
|
450 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
451 |
+
load the weights associated with the model, only the configuration. Check out the
|
452 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
453 |
+
"""
|
454 |
+
|
455 |
+
|
456 |
+
@add_start_docstrings(
|
457 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
458 |
+
RWKV6QWEN2_START_DOCSTRING,
|
459 |
+
)
|
460 |
+
class RWKV6Qwen2PreTrainedModel(PreTrainedModel):
|
461 |
+
config_class = RWKV6Qwen2Config
|
462 |
+
base_model_prefix = "model"
|
463 |
+
supports_gradient_checkpointing = True
|
464 |
+
_no_split_modules = ["RWKV6Qwen2DecoderLayer"]
|
465 |
+
_skip_keys_device_placement = "past_key_values"
|
466 |
+
_supports_flash_attn_2 = True
|
467 |
+
_supports_sdpa = True
|
468 |
+
_supports_cache_class = True
|
469 |
+
_supports_quantized_cache = True
|
470 |
+
_supports_static_cache = True
|
471 |
+
|
472 |
+
def _init_weights(self, module):
|
473 |
+
std = self.config.initializer_range
|
474 |
+
if isinstance(module, nn.Linear):
|
475 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
476 |
+
if module.bias is not None:
|
477 |
+
module.bias.data.zero_()
|
478 |
+
elif isinstance(module, nn.Embedding):
|
479 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
480 |
+
if module.padding_idx is not None:
|
481 |
+
module.weight.data[module.padding_idx].zero_()
|
482 |
+
|
483 |
+
|
484 |
+
RWKV6QWEN2_INPUTS_DOCSTRING = r"""
|
485 |
+
Args:
|
486 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
487 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
488 |
+
it.
|
489 |
+
|
490 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
491 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
492 |
+
|
493 |
+
[What are input IDs?](../glossary#input-ids)
|
494 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
495 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
496 |
+
|
497 |
+
- 1 for tokens that are **not masked**,
|
498 |
+
- 0 for tokens that are **masked**.
|
499 |
+
|
500 |
+
[What are attention masks?](../glossary#attention-mask)
|
501 |
+
|
502 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
503 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
504 |
+
|
505 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
506 |
+
`past_key_values`).
|
507 |
+
|
508 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
509 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
510 |
+
information on the default strategy.
|
511 |
+
|
512 |
+
- 1 indicates the head is **not masked**,
|
513 |
+
- 0 indicates the head is **masked**.
|
514 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
515 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
516 |
+
config.n_positions - 1]`.
|
517 |
+
|
518 |
+
[What are position IDs?](../glossary#position-ids)
|
519 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
520 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
521 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
522 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
523 |
+
|
524 |
+
Two formats are allowed:
|
525 |
+
- a [`~cache_utils.Cache`] instance, see our
|
526 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
527 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
528 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
529 |
+
cache format.
|
530 |
+
|
531 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
532 |
+
legacy cache format will be returned.
|
533 |
+
|
534 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
535 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
536 |
+
of shape `(batch_size, sequence_length)`.
|
537 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
538 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
539 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
540 |
+
model's internal embedding lookup matrix.
|
541 |
+
use_cache (`bool`, *optional*):
|
542 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
543 |
+
`past_key_values`).
|
544 |
+
output_attentions (`bool`, *optional*):
|
545 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
546 |
+
tensors for more detail.
|
547 |
+
output_hidden_states (`bool`, *optional*):
|
548 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
549 |
+
more detail.
|
550 |
+
return_dict (`bool`, *optional*):
|
551 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
552 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
553 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
554 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
555 |
+
the complete sequence length.
|
556 |
+
"""
|
557 |
+
|
558 |
+
@add_start_docstrings(
|
559 |
+
"The bare RWKV6Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
560 |
+
RWKV6QWEN2_START_DOCSTRING,
|
561 |
+
)
|
562 |
+
class RWKV6Qwen2Model(RWKV6Qwen2PreTrainedModel):
|
563 |
+
"""
|
564 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
|
565 |
+
|
566 |
+
Args:
|
567 |
+
config: RWKV6Qwen2Config
|
568 |
+
"""
|
569 |
+
|
570 |
+
def __init__(self, config: RWKV6Qwen2Config):
|
571 |
+
super().__init__(config)
|
572 |
+
self.padding_idx = config.pad_token_id
|
573 |
+
self.vocab_size = config.vocab_size
|
574 |
+
|
575 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
576 |
+
self.layers = nn.ModuleList(
|
577 |
+
[RWKV6Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
578 |
+
)
|
579 |
+
self._attn_implementation = config._attn_implementation
|
580 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
581 |
+
#self.rotary_emb = Qwen2RotaryEmbedding(config=config)
|
582 |
+
|
583 |
+
self.gradient_checkpointing = False
|
584 |
+
# Initialize weights and apply final processing
|
585 |
+
self.post_init()
|
586 |
+
|
587 |
+
def get_input_embeddings(self):
|
588 |
+
return self.embed_tokens
|
589 |
+
|
590 |
+
def set_input_embeddings(self, value):
|
591 |
+
self.embed_tokens = value
|
592 |
+
|
593 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
594 |
+
def forward(
|
595 |
+
self,
|
596 |
+
input_ids: torch.LongTensor = None,
|
597 |
+
attention_mask: Optional[torch.Tensor] = None,
|
598 |
+
position_ids: Optional[torch.LongTensor] = None,
|
599 |
+
past_key_values: Optional[Cache] = None,
|
600 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
601 |
+
use_cache: Optional[bool] = None,
|
602 |
+
output_attentions: Optional[bool] = None,
|
603 |
+
output_hidden_states: Optional[bool] = None,
|
604 |
+
return_dict: Optional[bool] = None,
|
605 |
+
cache_position: Optional[torch.LongTensor] = None,
|
606 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
607 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
608 |
+
output_hidden_states = (
|
609 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
610 |
+
)
|
611 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
612 |
+
|
613 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
614 |
+
|
615 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
616 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
617 |
+
|
618 |
+
if self.gradient_checkpointing and self.training:
|
619 |
+
if use_cache:
|
620 |
+
logger.warning_once(
|
621 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
622 |
+
)
|
623 |
+
use_cache = False
|
624 |
+
|
625 |
+
# kept for BC (non `Cache` `past_key_values` inputs)
|
626 |
+
#return_legacy_cache = False
|
627 |
+
if use_cache and not isinstance(past_key_values, RWKV6State):
|
628 |
+
#return_legacy_cache = True
|
629 |
+
past_key_values = RWKV6State()
|
630 |
+
# if past_key_values is None:
|
631 |
+
# past_key_values = DynamicCache()
|
632 |
+
# else:
|
633 |
+
# past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
634 |
+
# logger.warning_once(
|
635 |
+
# "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
|
636 |
+
# "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
|
637 |
+
# "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
|
638 |
+
# )
|
639 |
+
|
640 |
+
if inputs_embeds is None:
|
641 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
642 |
+
|
643 |
+
# if cache_position is None:
|
644 |
+
# past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
645 |
+
# cache_position = torch.arange(
|
646 |
+
# past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
647 |
+
# )
|
648 |
+
# if position_ids is None:
|
649 |
+
# position_ids = cache_position.unsqueeze(0)
|
650 |
+
|
651 |
+
# causal_mask = self._update_causal_mask(
|
652 |
+
# attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
653 |
+
# )
|
654 |
+
|
655 |
+
causal_mask = None
|
656 |
+
|
657 |
+
hidden_states = inputs_embeds
|
658 |
+
|
659 |
+
# create position embeddings to be shared across the decoder layers
|
660 |
+
position_embeddings = None #self.rotary_emb(hidden_states, position_ids)
|
661 |
+
|
662 |
+
# decoder layers
|
663 |
+
all_hidden_states = () if output_hidden_states else None
|
664 |
+
all_self_attns = () if output_attentions else None
|
665 |
+
next_decoder_cache = None
|
666 |
+
|
667 |
+
for decoder_layer in self.layers:
|
668 |
+
if output_hidden_states:
|
669 |
+
all_hidden_states += (hidden_states,)
|
670 |
+
|
671 |
+
if self.gradient_checkpointing and self.training:
|
672 |
+
layer_outputs = self._gradient_checkpointing_func(
|
673 |
+
decoder_layer.__call__,
|
674 |
+
hidden_states,
|
675 |
+
causal_mask,
|
676 |
+
position_ids,
|
677 |
+
past_key_values,
|
678 |
+
output_attentions,
|
679 |
+
use_cache,
|
680 |
+
cache_position,
|
681 |
+
position_embeddings,
|
682 |
+
)
|
683 |
+
else:
|
684 |
+
layer_outputs = decoder_layer(
|
685 |
+
hidden_states,
|
686 |
+
attention_mask=attention_mask,
|
687 |
+
position_ids=position_ids,
|
688 |
+
past_key_values=past_key_values,
|
689 |
+
output_attentions=output_attentions,
|
690 |
+
use_cache=use_cache,
|
691 |
+
cache_position=cache_position,
|
692 |
+
position_embeddings=position_embeddings,
|
693 |
+
)
|
694 |
+
|
695 |
+
hidden_states = layer_outputs[0]
|
696 |
+
|
697 |
+
if output_attentions:
|
698 |
+
all_self_attns += (layer_outputs[1],)
|
699 |
+
|
700 |
+
hidden_states = self.norm(hidden_states)
|
701 |
+
|
702 |
+
# add hidden states from the last decoder layer
|
703 |
+
if output_hidden_states:
|
704 |
+
all_hidden_states += (hidden_states,)
|
705 |
+
|
706 |
+
#if return_legacy_cache:
|
707 |
+
# next_cache = next_cache.to_legacy_cache()
|
708 |
+
|
709 |
+
if not return_dict:
|
710 |
+
return tuple(v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None)
|
711 |
+
return BaseModelOutputWithPast(
|
712 |
+
last_hidden_state=hidden_states,
|
713 |
+
past_key_values=past_key_values,
|
714 |
+
hidden_states=all_hidden_states,
|
715 |
+
attentions=all_self_attns,
|
716 |
+
)
|
717 |
+
|
718 |
+
class RWKV6Qwen2ForCausalLM(RWKV6Qwen2PreTrainedModel, GenerationMixin):
|
719 |
+
_tied_weights_keys = ["lm_head.weight"]
|
720 |
+
|
721 |
+
def __init__(self, config):
|
722 |
+
super().__init__(config)
|
723 |
+
self.model = RWKV6Qwen2Model(config)
|
724 |
+
self.vocab_size = config.vocab_size
|
725 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
726 |
+
|
727 |
+
# Initialize weights and apply final processing
|
728 |
+
self.post_init()
|
729 |
+
|
730 |
+
def get_input_embeddings(self):
|
731 |
+
return self.model.embed_tokens
|
732 |
+
|
733 |
+
def set_input_embeddings(self, value):
|
734 |
+
self.model.embed_tokens = value
|
735 |
+
|
736 |
+
def get_output_embeddings(self):
|
737 |
+
return self.lm_head
|
738 |
+
|
739 |
+
def set_output_embeddings(self, new_embeddings):
|
740 |
+
self.lm_head = new_embeddings
|
741 |
+
|
742 |
+
def set_decoder(self, decoder):
|
743 |
+
self.model = decoder
|
744 |
+
|
745 |
+
def get_decoder(self):
|
746 |
+
return self.model
|
747 |
+
|
748 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
749 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
750 |
+
def forward(
|
751 |
+
self,
|
752 |
+
input_ids: torch.LongTensor = None,
|
753 |
+
attention_mask: Optional[torch.Tensor] = None,
|
754 |
+
position_ids: Optional[torch.LongTensor] = None,
|
755 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
756 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
757 |
+
labels: Optional[torch.LongTensor] = None,
|
758 |
+
use_cache: Optional[bool] = None,
|
759 |
+
output_attentions: Optional[bool] = None,
|
760 |
+
output_hidden_states: Optional[bool] = None,
|
761 |
+
return_dict: Optional[bool] = None,
|
762 |
+
cache_position: Optional[torch.LongTensor] = None,
|
763 |
+
num_logits_to_keep: int = 0,
|
764 |
+
**loss_kwargs,
|
765 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
766 |
+
r"""
|
767 |
+
Args:
|
768 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
769 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
770 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
771 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
772 |
+
|
773 |
+
num_logits_to_keep (`int`, *optional*):
|
774 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
775 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
776 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
777 |
+
|
778 |
+
Returns:
|
779 |
+
|
780 |
+
Example:
|
781 |
+
|
782 |
+
```python
|
783 |
+
>>> from transformers import AutoTokenizer, RWKV6Qwen2ForCausalLM
|
784 |
+
|
785 |
+
>>> model = RWKV6Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
786 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
787 |
+
|
788 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
789 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
790 |
+
|
791 |
+
>>> # Generate
|
792 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
793 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
794 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
795 |
+
```"""
|
796 |
+
|
797 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
798 |
+
output_hidden_states = (
|
799 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
800 |
+
)
|
801 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
802 |
+
|
803 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
804 |
+
outputs = self.model(
|
805 |
+
input_ids=input_ids,
|
806 |
+
attention_mask=attention_mask,
|
807 |
+
position_ids=position_ids,
|
808 |
+
past_key_values=past_key_values,
|
809 |
+
inputs_embeds=inputs_embeds,
|
810 |
+
use_cache=use_cache,
|
811 |
+
output_attentions=output_attentions,
|
812 |
+
output_hidden_states=output_hidden_states,
|
813 |
+
return_dict=return_dict,
|
814 |
+
cache_position=cache_position,
|
815 |
+
)
|
816 |
+
|
817 |
+
hidden_states = outputs[0]
|
818 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
819 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
820 |
+
|
821 |
+
loss = None
|
822 |
+
if labels is not None:
|
823 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
|
824 |
+
|
825 |
+
if not return_dict:
|
826 |
+
output = (logits,) + outputs[1:]
|
827 |
+
return (loss,) + output if loss is not None else output
|
828 |
+
|
829 |
+
return CausalLMOutputWithPast(
|
830 |
+
loss=loss,
|
831 |
+
logits=logits,
|
832 |
+
past_key_values=outputs.past_key_values,
|
833 |
+
hidden_states=outputs.hidden_states,
|
834 |
+
attentions=outputs.attentions,
|
835 |
+
)
|
836 |
+
|
837 |
+
def prepare_inputs_for_generation(
|
838 |
+
self,
|
839 |
+
input_ids: torch.LongTensor,
|
840 |
+
past_key_values: Optional[Cache] = None,
|
841 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
842 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
843 |
+
cache_position: Optional[torch.LongTensor] = None,
|
844 |
+
**kwargs,
|
845 |
+
):
|
846 |
+
# only last token for `inputs_ids` if the `past_key_values` is not empty.
|
847 |
+
if past_key_values is not None and len(past_key_values) > 0:
|
848 |
+
input_ids = input_ids[:, -1:]
|
849 |
+
|
850 |
+
model_inputs = {
|
851 |
+
'past_key_values': past_key_values,
|
852 |
+
'attention_mask': attention_mask,
|
853 |
+
'cache_position': cache_position,
|
854 |
+
}
|
855 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
856 |
+
if inputs_embeds is not None and past_key_values is None:
|
857 |
+
model_inputs['inputs_embeds'] = inputs_embeds
|
858 |
+
else:
|
859 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
860 |
+
# recompiles graphs as the stride of the inputs is a guard.
|
861 |
+
# Ref: https://github.com/huggingface/transformers/pull/29114
|
862 |
+
# TODO: use `next_tokens` directly instead.
|
863 |
+
model_inputs['input_ids'] = input_ids.contiguous()
|
864 |
+
|
865 |
+
model_inputs.update(**kwargs)
|
866 |
+
|
867 |
+
# 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)
|
868 |
+
model_inputs.pop("labels", None)
|
869 |
+
|
870 |
+
return model_inputs
|
871 |
+
|
872 |
+
@add_start_docstrings(
|
873 |
+
"""
|
874 |
+
The RWKV6Qwen2 Model transformer with a sequence classification head on top (linear layer).
|
875 |
+
|
876 |
+
[`RWKV6Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
877 |
+
(e.g. GPT-2) do.
|
878 |
+
|
879 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
880 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
881 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
882 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
883 |
+
each row of the batch).
|
884 |
+
""",
|
885 |
+
RWKV6QWEN2_START_DOCSTRING,
|
886 |
+
)
|
887 |
+
class RWKV6Qwen2ForSequenceClassification(RWKV6Qwen2PreTrainedModel):
|
888 |
+
def __init__(self, config):
|
889 |
+
super().__init__(config)
|
890 |
+
self.num_labels = config.num_labels
|
891 |
+
self.model = RWKV6Qwen2Model(config)
|
892 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
893 |
+
|
894 |
+
# Initialize weights and apply final processing
|
895 |
+
self.post_init()
|
896 |
+
|
897 |
+
def get_input_embeddings(self):
|
898 |
+
return self.model.embed_tokens
|
899 |
+
|
900 |
+
def set_input_embeddings(self, value):
|
901 |
+
self.model.embed_tokens = value
|
902 |
+
|
903 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
904 |
+
def forward(
|
905 |
+
self,
|
906 |
+
input_ids: torch.LongTensor = None,
|
907 |
+
attention_mask: Optional[torch.Tensor] = None,
|
908 |
+
position_ids: Optional[torch.LongTensor] = None,
|
909 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
910 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
911 |
+
labels: Optional[torch.LongTensor] = None,
|
912 |
+
use_cache: Optional[bool] = None,
|
913 |
+
output_attentions: Optional[bool] = None,
|
914 |
+
output_hidden_states: Optional[bool] = None,
|
915 |
+
return_dict: Optional[bool] = None,
|
916 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
917 |
+
r"""
|
918 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
919 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
920 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
921 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
922 |
+
"""
|
923 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
924 |
+
|
925 |
+
transformer_outputs = self.model(
|
926 |
+
input_ids,
|
927 |
+
attention_mask=attention_mask,
|
928 |
+
position_ids=position_ids,
|
929 |
+
past_key_values=past_key_values,
|
930 |
+
inputs_embeds=inputs_embeds,
|
931 |
+
use_cache=use_cache,
|
932 |
+
output_attentions=output_attentions,
|
933 |
+
output_hidden_states=output_hidden_states,
|
934 |
+
return_dict=return_dict,
|
935 |
+
)
|
936 |
+
hidden_states = transformer_outputs[0]
|
937 |
+
logits = self.score(hidden_states)
|
938 |
+
|
939 |
+
if input_ids is not None:
|
940 |
+
batch_size = input_ids.shape[0]
|
941 |
+
else:
|
942 |
+
batch_size = inputs_embeds.shape[0]
|
943 |
+
|
944 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
945 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
946 |
+
if self.config.pad_token_id is None:
|
947 |
+
sequence_lengths = -1
|
948 |
+
else:
|
949 |
+
if input_ids is not None:
|
950 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
951 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
952 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
953 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
954 |
+
else:
|
955 |
+
sequence_lengths = -1
|
956 |
+
|
957 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
958 |
+
|
959 |
+
loss = None
|
960 |
+
if labels is not None:
|
961 |
+
labels = labels.to(logits.device)
|
962 |
+
if self.config.problem_type is None:
|
963 |
+
if self.num_labels == 1:
|
964 |
+
self.config.problem_type = "regression"
|
965 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
966 |
+
self.config.problem_type = "single_label_classification"
|
967 |
+
else:
|
968 |
+
self.config.problem_type = "multi_label_classification"
|
969 |
+
|
970 |
+
if self.config.problem_type == "regression":
|
971 |
+
loss_fct = MSELoss()
|
972 |
+
if self.num_labels == 1:
|
973 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
974 |
+
else:
|
975 |
+
loss = loss_fct(pooled_logits, labels)
|
976 |
+
elif self.config.problem_type == "single_label_classification":
|
977 |
+
loss_fct = CrossEntropyLoss()
|
978 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
979 |
+
elif self.config.problem_type == "multi_label_classification":
|
980 |
+
loss_fct = BCEWithLogitsLoss()
|
981 |
+
loss = loss_fct(pooled_logits, labels)
|
982 |
+
if not return_dict:
|
983 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
984 |
+
return ((loss,) + output) if loss is not None else output
|
985 |
+
|
986 |
+
return SequenceClassifierOutputWithPast(
|
987 |
+
loss=loss,
|
988 |
+
logits=pooled_logits,
|
989 |
+
past_key_values=transformer_outputs.past_key_values,
|
990 |
+
hidden_states=transformer_outputs.hidden_states,
|
991 |
+
attentions=transformer_outputs.attentions,
|
992 |
+
)
|
993 |
+
|
994 |
+
|
995 |
+
@add_start_docstrings(
|
996 |
+
"""
|
997 |
+
The RWKV6Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
998 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
999 |
+
""",
|
1000 |
+
RWKV6QWEN2_START_DOCSTRING,
|
1001 |
+
)
|
1002 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->RWKV6Qwen2, LLAMA->RWKV6QWEN2
|
1003 |
+
class RWKV6Qwen2ForTokenClassification(RWKV6Qwen2PreTrainedModel):
|
1004 |
+
def __init__(self, config):
|
1005 |
+
super().__init__(config)
|
1006 |
+
self.num_labels = config.num_labels
|
1007 |
+
self.model = RWKV6Qwen2Model(config)
|
1008 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
1009 |
+
classifier_dropout = config.classifier_dropout
|
1010 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
1011 |
+
classifier_dropout = config.hidden_dropout
|
1012 |
+
else:
|
1013 |
+
classifier_dropout = 0.1
|
1014 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1015 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
1016 |
+
|
1017 |
+
# Initialize weights and apply final processing
|
1018 |
+
self.post_init()
|
1019 |
+
|
1020 |
+
def get_input_embeddings(self):
|
1021 |
+
return self.model.embed_tokens
|
1022 |
+
|
1023 |
+
def set_input_embeddings(self, value):
|
1024 |
+
self.model.embed_tokens = value
|
1025 |
+
|
1026 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
1027 |
+
@add_code_sample_docstrings(
|
1028 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1029 |
+
output_type=TokenClassifierOutput,
|
1030 |
+
config_class=_CONFIG_FOR_DOC,
|
1031 |
+
)
|
1032 |
+
def forward(
|
1033 |
+
self,
|
1034 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1035 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1036 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1037 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1038 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1039 |
+
labels: Optional[torch.LongTensor] = None,
|
1040 |
+
use_cache: Optional[bool] = None,
|
1041 |
+
output_attentions: Optional[bool] = None,
|
1042 |
+
output_hidden_states: Optional[bool] = None,
|
1043 |
+
return_dict: Optional[bool] = None,
|
1044 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
1045 |
+
r"""
|
1046 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1047 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1048 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1049 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1050 |
+
"""
|
1051 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1052 |
+
|
1053 |
+
outputs = self.model(
|
1054 |
+
input_ids,
|
1055 |
+
attention_mask=attention_mask,
|
1056 |
+
position_ids=position_ids,
|
1057 |
+
past_key_values=past_key_values,
|
1058 |
+
inputs_embeds=inputs_embeds,
|
1059 |
+
use_cache=use_cache,
|
1060 |
+
output_attentions=output_attentions,
|
1061 |
+
output_hidden_states=output_hidden_states,
|
1062 |
+
return_dict=return_dict,
|
1063 |
+
)
|
1064 |
+
sequence_output = outputs[0]
|
1065 |
+
sequence_output = self.dropout(sequence_output)
|
1066 |
+
logits = self.score(sequence_output)
|
1067 |
+
|
1068 |
+
loss = None
|
1069 |
+
if labels is not None:
|
1070 |
+
loss = self.loss_function(logits, labels, self.config)
|
1071 |
+
|
1072 |
+
if not return_dict:
|
1073 |
+
output = (logits,) + outputs[2:]
|
1074 |
+
return ((loss,) + output) if loss is not None else output
|
1075 |
+
|
1076 |
+
return TokenClassifierOutput(
|
1077 |
+
loss=loss,
|
1078 |
+
logits=logits,
|
1079 |
+
hidden_states=outputs.hidden_states,
|
1080 |
+
attentions=outputs.attentions,
|
1081 |
+
)
|
1082 |
+
|
1083 |
+
|
1084 |
+
@add_start_docstrings(
|
1085 |
+
"""
|
1086 |
+
The RWKV6Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
|
1087 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1088 |
+
""",
|
1089 |
+
RWKV6QWEN2_START_DOCSTRING,
|
1090 |
+
)
|
1091 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralForQuestionAnswering with Mistral->RWKV6Qwen2, MISTRAL->RWKV6QWEN2
|
1092 |
+
class RWKV6Qwen2ForQuestionAnswering(RWKV6Qwen2PreTrainedModel):
|
1093 |
+
base_model_prefix = "model"
|
1094 |
+
|
1095 |
+
# Copied from models.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->RWKV6Qwen2
|
1096 |
+
def __init__(self, config):
|
1097 |
+
super().__init__(config)
|
1098 |
+
self.model = RWKV6Qwen2Model(config)
|
1099 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1100 |
+
|
1101 |
+
# Initialize weights and apply final processing
|
1102 |
+
self.post_init()
|
1103 |
+
|
1104 |
+
def get_input_embeddings(self):
|
1105 |
+
return self.model.embed_tokens
|
1106 |
+
|
1107 |
+
def set_input_embeddings(self, value):
|
1108 |
+
self.model.embed_tokens = value
|
1109 |
+
|
1110 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
1111 |
+
def forward(
|
1112 |
+
self,
|
1113 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1114 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1115 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1116 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1117 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1118 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1119 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1120 |
+
output_attentions: Optional[bool] = None,
|
1121 |
+
output_hidden_states: Optional[bool] = None,
|
1122 |
+
return_dict: Optional[bool] = None,
|
1123 |
+
**kwargs,
|
1124 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1125 |
+
r"""
|
1126 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1127 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1128 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1129 |
+
are not taken into account for computing the loss.
|
1130 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1131 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1132 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1133 |
+
are not taken into account for computing the loss.
|
1134 |
+
"""
|
1135 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1136 |
+
|
1137 |
+
outputs = self.model(
|
1138 |
+
input_ids,
|
1139 |
+
attention_mask=attention_mask,
|
1140 |
+
position_ids=position_ids,
|
1141 |
+
past_key_values=past_key_values,
|
1142 |
+
inputs_embeds=inputs_embeds,
|
1143 |
+
output_attentions=output_attentions,
|
1144 |
+
output_hidden_states=output_hidden_states,
|
1145 |
+
return_dict=return_dict,
|
1146 |
+
)
|
1147 |
+
|
1148 |
+
sequence_output = outputs[0]
|
1149 |
+
|
1150 |
+
logits = self.qa_outputs(sequence_output)
|
1151 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1152 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1153 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1154 |
+
|
1155 |
+
loss = None
|
1156 |
+
if start_positions is not None and end_positions is not None:
|
1157 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
1158 |
+
|
1159 |
+
if not return_dict:
|
1160 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1161 |
+
return ((loss,) + output) if loss is not None else output
|
1162 |
+
|
1163 |
+
return QuestionAnsweringModelOutput(
|
1164 |
+
loss=loss,
|
1165 |
+
start_logits=start_logits,
|
1166 |
+
end_logits=end_logits,
|
1167 |
+
hidden_states=outputs.hidden_states,
|
1168 |
+
attentions=outputs.attentions,
|
1169 |
+
)
|