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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2025 RWKV team. All rights reserved.
|
3 |
+
# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""RwkvHybrid model configuration"""
|
17 |
+
|
18 |
+
from transformers.configuration_utils import PretrainedConfig
|
19 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
20 |
+
from transformers.utils import logging
|
21 |
+
from typing import Optional, Union, List
|
22 |
+
|
23 |
+
|
24 |
+
logger = logging.get_logger(__name__)
|
25 |
+
|
26 |
+
|
27 |
+
class RwkvHybridConfig(PretrainedConfig):
|
28 |
+
r"""
|
29 |
+
This is the configuration class to store the configuration of a [`RwkvHybridModel`]. It is used to instantiate a
|
30 |
+
RwkvHybrid model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
31 |
+
with the defaults will yield a similar configuration to that of
|
32 |
+
RwkvHybrid-7B-beta.
|
33 |
+
|
34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
35 |
+
documentation from [`PretrainedConfig`] for more information.
|
36 |
+
|
37 |
+
|
38 |
+
Args:
|
39 |
+
vocab_size (`int`, *optional*, defaults to 151936):
|
40 |
+
Vocabulary size of the RwkvHybrid model. Defines the number of different tokens that can be represented by the
|
41 |
+
`inputs_ids` passed when calling [`RwkvHybridModel`]
|
42 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
43 |
+
Dimension of the hidden representations.
|
44 |
+
intermediate_size (`int`, *optional*, defaults to 22016):
|
45 |
+
Dimension of the MLP representations.
|
46 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
47 |
+
Number of hidden layers in the Transformer encoder.
|
48 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
49 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
50 |
+
num_key_value_heads (`int`, *optional*, defaults to 32):
|
51 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
52 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
53 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
54 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
55 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
56 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
|
57 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
58 |
+
The non-linear activation function (function or string) in the decoder.
|
59 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
60 |
+
The maximum sequence length that this model might ever be used with.
|
61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
63 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
64 |
+
The epsilon used by the rms normalization layers.
|
65 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
66 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
67 |
+
relevant if `config.is_decoder=True`.
|
68 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
69 |
+
Whether the model's input and output word embeddings should be tied.
|
70 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
71 |
+
The base period of the RoPE embeddings.
|
72 |
+
rope_scaling (`Dict`, *optional*):
|
73 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
74 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
75 |
+
accordingly.
|
76 |
+
Expected contents:
|
77 |
+
`rope_type` (`str`):
|
78 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
79 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
80 |
+
`factor` (`float`, *optional*):
|
81 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
82 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
83 |
+
original maximum pre-trained length.
|
84 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
85 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
86 |
+
pretraining.
|
87 |
+
`attention_factor` (`float`, *optional*):
|
88 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
89 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
90 |
+
`factor` field to infer the suggested value.
|
91 |
+
`beta_fast` (`float`, *optional*):
|
92 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
93 |
+
ramp function. If unspecified, it defaults to 32.
|
94 |
+
`beta_slow` (`float`, *optional*):
|
95 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
96 |
+
ramp function. If unspecified, it defaults to 1.
|
97 |
+
`short_factor` (`List[float]`, *optional*):
|
98 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
99 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
100 |
+
size divided by the number of attention heads divided by 2
|
101 |
+
`long_factor` (`List[float]`, *optional*):
|
102 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
103 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
104 |
+
size divided by the number of attention heads divided by 2
|
105 |
+
`low_freq_factor` (`float`, *optional*):
|
106 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
107 |
+
`high_freq_factor` (`float`, *optional*):
|
108 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
109 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
110 |
+
Whether to use sliding window attention.
|
111 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
112 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
113 |
+
max_window_layers (`int`, *optional*, defaults to 28):
|
114 |
+
The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
|
115 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
116 |
+
The dropout ratio for the attention probabilities.
|
117 |
+
head_size (`int`, *optional*, defaults to 64):
|
118 |
+
Dimensionality of each RWKV attention head. Defines the hidden dimension size for RWKV attention mechanisms.
|
119 |
+
head_size_divisor (`int`, *optional*, defaults to 8):
|
120 |
+
Constraint for head_size initialization, typically set to the square root of head_size. Ensures divisibility
|
121 |
+
between hidden_size and head_size.
|
122 |
+
wkv_version (`int`, *optional*, defaults to 7):
|
123 |
+
Version of RWKV attention implementation. Currently supports:
|
124 |
+
- 6: Original implementation requiring `wkv_has_gate=True` and `wkv_use_vfirst=False`
|
125 |
+
- 7: Improved version requiring `wkv_use_vfirst=True`
|
126 |
+
wkv_has_gate (`bool`, *optional*, defaults to False):
|
127 |
+
Whether to include gating mechanism in RWKV attention. Required for version 6.
|
128 |
+
wkv_has_group_norm (`bool`, *optional*, defaults to True):
|
129 |
+
Whether to apply group normalization in RWKV attention layers.
|
130 |
+
wkv_use_vfirst (`bool`, *optional*, defaults to True):
|
131 |
+
Whether to prioritize value projection in RWKV attention computation. Required for version 7.
|
132 |
+
wkv_layers (`Union[str, List[int]]`, *optional*, defaults to None):
|
133 |
+
Specifies which layers use RWKV attention:
|
134 |
+
- `"full"` or `None`: All layers use RWKV
|
135 |
+
- List of integers: Only specified layers (e.g., `[0,1,2]`) use RWKV attention
|
136 |
+
|
137 |
+
```python
|
138 |
+
>>> from transformers import RwkvHybridModel, RwkvHybridConfig
|
139 |
+
|
140 |
+
>>> # Initializing a RwkvHybrid style configuration
|
141 |
+
>>> configuration = RwkvHybridConfig()
|
142 |
+
|
143 |
+
>>> # Initializing a model from the RwkvHybrid-7B style configuration
|
144 |
+
>>> model = RwkvHybridModel(configuration)
|
145 |
+
|
146 |
+
>>> # Accessing the model configuration
|
147 |
+
>>> configuration = model.config
|
148 |
+
```"""
|
149 |
+
|
150 |
+
model_type = "rwkv_hybrid"
|
151 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
152 |
+
|
153 |
+
# Default tensor parallel plan for base model `RwkvHybrid`
|
154 |
+
base_model_tp_plan = {
|
155 |
+
"layers.*.self_attn.q_proj": "colwise",
|
156 |
+
"layers.*.self_attn.k_proj": "colwise",
|
157 |
+
"layers.*.self_attn.v_proj": "colwise",
|
158 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
159 |
+
"layers.*.mlp.gate_proj": "colwise",
|
160 |
+
"layers.*.mlp.up_proj": "colwise",
|
161 |
+
"layers.*.mlp.down_proj": "rowwise",
|
162 |
+
}
|
163 |
+
|
164 |
+
def __init__(
|
165 |
+
self,
|
166 |
+
vocab_size: int = 151936,
|
167 |
+
hidden_size: int = 4096,
|
168 |
+
intermediate_size: int = 22016,
|
169 |
+
num_hidden_layers: int = 32,
|
170 |
+
num_attention_heads: int = 32,
|
171 |
+
num_key_value_heads: int = 32,
|
172 |
+
head_size: int = 64,
|
173 |
+
head_size_divisor: int = 8,
|
174 |
+
hidden_act: str = "silu",
|
175 |
+
max_position_embeddings: int = 32768,
|
176 |
+
initializer_range: float = 0.02,
|
177 |
+
rms_norm_eps: float = 1e-6,
|
178 |
+
use_cache: bool = True,
|
179 |
+
tie_word_embeddings: bool = False,
|
180 |
+
rope_theta: float = 10000.0,
|
181 |
+
rope_scaling: Optional[dict] = None,
|
182 |
+
use_sliding_window: bool = False,
|
183 |
+
sliding_window: int = 4096,
|
184 |
+
max_window_layers: int = 28,
|
185 |
+
attention_dropout: float = 0.0,
|
186 |
+
wkv_version: int = 7,
|
187 |
+
wkv_has_gate: bool = False,
|
188 |
+
wkv_has_group_norm: bool = True,
|
189 |
+
wkv_use_vfirst: bool = True,
|
190 |
+
wkv_layers: Optional[Union[str, List[int]]] = None,
|
191 |
+
**kwargs,
|
192 |
+
):
|
193 |
+
self.vocab_size = vocab_size
|
194 |
+
self.max_position_embeddings = max_position_embeddings
|
195 |
+
self.hidden_size = hidden_size
|
196 |
+
self.intermediate_size = intermediate_size
|
197 |
+
self.num_hidden_layers = num_hidden_layers
|
198 |
+
self.num_wkv_heads = hidden_size // head_size
|
199 |
+
assert hidden_size % head_size == 0, "hidden_size must be divisible by head_size"
|
200 |
+
self.num_attention_heads = num_attention_heads
|
201 |
+
self.use_sliding_window = use_sliding_window
|
202 |
+
self.sliding_window = sliding_window if use_sliding_window else None
|
203 |
+
self.max_window_layers = max_window_layers
|
204 |
+
self.head_size = head_size
|
205 |
+
self.head_size_divisor = head_size_divisor
|
206 |
+
self.wkv_version = wkv_version
|
207 |
+
|
208 |
+
self.wkv_has_gate = wkv_has_gate
|
209 |
+
self.wkv_has_group_norm = wkv_has_group_norm
|
210 |
+
self.wkv_use_vfirst = wkv_use_vfirst
|
211 |
+
|
212 |
+
if self.wkv_version == 7:
|
213 |
+
assert self.wkv_use_vfirst, "wkv_use_vfirst must be True for wkv_version 7"
|
214 |
+
elif self.wkv_version == 6:
|
215 |
+
assert self.wkv_has_gate, "wkv_has_gate must be True for wkv_version 6"
|
216 |
+
assert not self.wkv_use_vfirst, "wkv_use_vfirst must be False for wkv_version 6"
|
217 |
+
else:
|
218 |
+
raise NotImplementedError(f"Unsupported wkv_version: {self.wkv_version}, \
|
219 |
+
wkv_version must be 6 or 7")
|
220 |
+
|
221 |
+
if wkv_layers == "full" or wkv_layers is None:
|
222 |
+
self.wkv_layers = list(range(num_hidden_layers))
|
223 |
+
elif isinstance(wkv_layers, list):
|
224 |
+
if all(isinstance(layer, int) for layer in wkv_layers):
|
225 |
+
self.wkv_layers = wkv_layers
|
226 |
+
else:
|
227 |
+
raise ValueError(
|
228 |
+
"All elements in wkv_layers must be integers.")
|
229 |
+
else:
|
230 |
+
raise TypeError(
|
231 |
+
"wkv_layers must be either 'full', None, or a list of integers.")
|
232 |
+
|
233 |
+
# for backward compatibility
|
234 |
+
if num_key_value_heads is None:
|
235 |
+
num_key_value_heads = num_attention_heads
|
236 |
+
|
237 |
+
self.num_key_value_heads = num_key_value_heads
|
238 |
+
self.hidden_act = hidden_act
|
239 |
+
self.initializer_range = initializer_range
|
240 |
+
self.rms_norm_eps = rms_norm_eps
|
241 |
+
self.use_cache = use_cache
|
242 |
+
self.rope_theta = rope_theta
|
243 |
+
self.rope_scaling = rope_scaling
|
244 |
+
self.attention_dropout = attention_dropout
|
245 |
+
# Validate the correctness of rotary position embeddings parameters
|
246 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
247 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
248 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
249 |
+
rope_config_validation(self)
|
250 |
+
|
251 |
+
super().__init__(
|
252 |
+
tie_word_embeddings=tie_word_embeddings,
|
253 |
+
**kwargs,
|
254 |
+
)
|