zhiyuan8 commited on
Commit
5c061c3
·
verified ·
1 Parent(s): e8526df

Upload 9 files

Browse files
Trained_20G/config.json CHANGED
@@ -1,8 +1,11 @@
1
  {
2
- "_name_or_path": "/home/yueyulin/model/qwen_r1_7b_withgate_freezemlp__20G_hf/",
3
  "architectures": [
4
  "RwkvHybridForCausalLM"
5
  ],
 
 
 
 
6
  "attention_dropout": 0.0,
7
  "bos_token_id": 151643,
8
  "eos_token_id": 151645,
 
1
  {
 
2
  "architectures": [
3
  "RwkvHybridForCausalLM"
4
  ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_rwkv_hybrid.RwkvHybridConfig",
7
+ "AutoModelForCausalLM": "modeling_rwkv_hybrid.RwkvHybridForCausalLM"
8
+ },
9
  "attention_dropout": 0.0,
10
  "bos_token_id": 151643,
11
  "eos_token_id": 151645,
Trained_20G/configuration_rwkv_hybrid.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )
Trained_20G/hybrid_cache.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Any, Dict, Optional, Union
3
+ from transformers.cache_utils import DynamicCache
4
+
5
+
6
+ class AttnState:
7
+ def __init__(self, shift_state: torch.Tensor, wkv_state: torch.Tensor):
8
+ self.shift_state = shift_state
9
+ self.wkv_state = wkv_state
10
+
11
+
12
+ class FfnState:
13
+ def __init__(self, shift_state: torch.Tensor):
14
+ self.shift_state = shift_state
15
+
16
+
17
+ class BlockState:
18
+ def __init__(
19
+ self,
20
+ attn_state: AttnState,
21
+ ffn_state: FfnState
22
+ ):
23
+ self.attn_state = attn_state
24
+ self.ffn_state = ffn_state
25
+
26
+ class HybridCache(DynamicCache):
27
+ def __init__(self) -> None:
28
+ super().__init__()
29
+ self.rwkv_layers = set()
30
+ self.key_cache_nums = 0
31
+ self.v_first_cache = None
32
+
33
+ def update(
34
+ self,
35
+ key_states: Union[int, torch.Tensor],
36
+ value_states: Union[torch.Tensor, BlockState],
37
+ layer_idx: int,
38
+ cache_kwargs: Optional[Dict[str, Any]] = None
39
+ ):
40
+ if isinstance(key_states, int) and isinstance(value_states, BlockState):
41
+ self.rwkv_layers.add(layer_idx)
42
+
43
+ if layer_idx >= self.key_cache_nums:
44
+ self.key_cache.append([])
45
+ self.value_cache.append([])
46
+ self.key_cache[layer_idx].append(key_states)
47
+ self.value_cache[layer_idx].append(value_states)
48
+ self.key_cache_nums += 1
49
+
50
+ else:
51
+ self.key_cache[layer_idx][0] += key_states
52
+ self.value_cache[layer_idx][0] = value_states
53
+
54
+ return key_states, value_states
55
+
56
+ return super().update(key_states, value_states, layer_idx, cache_kwargs)
57
+
58
+ def update_v_first(self, v_first: torch.Tensor):
59
+ self.v_first_cache = v_first
60
+
61
+ def get_v_first(self):
62
+ return self.v_first_cache
63
+
64
+ def get_seq_length(self, layer_idx: Optional[int] = 0):
65
+ if layer_idx in self.rwkv_layers:
66
+ return self.key_cache[layer_idx][0]
67
+ return super().get_seq_length(layer_idx)
68
+
69
+ def reorder_cache(self, beam_idx):
70
+ return super().reorder_cache(beam_idx)
71
+
72
+ def __getitem__(self, item):
73
+ if item in self.rwkv_layers:
74
+ return self.value_cache[item]
75
+ return super().__getitem__(item)
Trained_20G/modeling_rwkv_hybrid.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers.cache_utils import Cache
6
+
7
+ from transformers.activations import ACT2FN
8
+ from transformers.cache_utils import Cache, StaticCache
9
+ from .hybrid_cache import HybridCache
10
+ from transformers.generation import GenerationMixin
11
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
12
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
13
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
14
+
15
+ from transformers.modeling_outputs import (
16
+ BaseModelOutputWithPast,
17
+ CausalLMOutputWithPast,
18
+ )
19
+ from transformers.processing_utils import Unpack
20
+ from transformers.utils import (
21
+ LossKwargs,
22
+ add_start_docstrings,
23
+ add_start_docstrings_to_model_forward,
24
+ logging,
25
+ )
26
+
27
+ import threading
28
+ from .wkv import Rwkv7Attention, Rwkv6Attention
29
+ from .configuration_rwkv_hybrid import RwkvHybridConfig
30
+
31
+ from transformers.models.qwen2.modeling_qwen2 import (Qwen2MLP,
32
+ Qwen2RMSNorm,
33
+ Qwen2RotaryEmbedding,
34
+ Qwen2Attention)
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ _CONFIG_FOR_DOC = "RwkvHybridConfig"
39
+
40
+
41
+ class RwkvHybridDecoderLayer(nn.Module):
42
+ def __init__(self, config: RwkvHybridConfig, layer_idx: int):
43
+ super().__init__()
44
+ self.hidden_size = config.hidden_size
45
+
46
+ self.is_rwkv = True if layer_idx in config.wkv_layers else False
47
+ if self.is_rwkv:
48
+ if config.wkv_version == 7:
49
+ self.self_attn = Rwkv7Attention(
50
+ args=config, layer_id=layer_idx)
51
+ elif config.wkv_version == 6:
52
+ self.self_attn = Rwkv6Attention(
53
+ args=config, layer_id=layer_idx)
54
+ else:
55
+ raise NotImplementedError
56
+ else:
57
+ self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
58
+
59
+ self.mlp = Qwen2MLP(config)
60
+ self.input_layernorm = Qwen2RMSNorm(
61
+ config.hidden_size, eps=config.rms_norm_eps)
62
+ self.post_attention_layernorm = Qwen2RMSNorm(
63
+ config.hidden_size, eps=config.rms_norm_eps)
64
+ self.layer_idx = layer_idx
65
+
66
+ def forward(
67
+ self,
68
+ hidden_states: torch.Tensor,
69
+ attention_mask: Optional[torch.Tensor] = None,
70
+ position_ids: Optional[torch.Tensor] = None,
71
+ past_key_value: Optional[Cache] = None,
72
+ output_attentions: Optional[bool] = False,
73
+ use_cache: Optional[bool] = False,
74
+ cache_position: Optional[torch.Tensor] = None,
75
+ position_embeddings: Optional[torch.Tensor] = None,
76
+ sequence_mask: Optional[torch.Tensor] = None,
77
+ cu_seq_lens_q: Optional[torch.LongTensor] = None,
78
+ cu_seq_lens_k: Optional[torch.LongTensor] = None,
79
+ max_length_q: Optional[int] = None,
80
+ max_length_k: Optional[int] = None,
81
+ cu_seqlens: Optional[torch.LongTensor] = None,
82
+ v_first: Optional[torch.LongTensor] = None,
83
+ **kwargs,
84
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
85
+
86
+ if sequence_mask is not None:
87
+ assert len(sequence_mask.shape) == 2, (
88
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
89
+ "for padding purposes (0 indicating padding). "
90
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
91
+ )
92
+ hidden_states = hidden_states.mul(
93
+ sequence_mask[:, -hidden_states.shape[-2]:, None])
94
+
95
+ residual = hidden_states
96
+
97
+ hidden_states = self.input_layernorm(hidden_states)
98
+
99
+ # RWKV attention
100
+ if self.is_rwkv:
101
+ hidden_states, self_attn_weights, v_first = self.self_attn(
102
+ hidden_states=hidden_states,
103
+ position_ids=position_ids,
104
+ past_key_value=past_key_value,
105
+ output_attentions=output_attentions,
106
+ use_cache=use_cache,
107
+ cache_position=cache_position,
108
+ position_embeddings=position_embeddings,
109
+ cu_seqlens=cu_seqlens,
110
+ v_first=v_first,
111
+ **kwargs
112
+ )
113
+ else:
114
+ hidden_states, self_attn_weights = self.self_attn(
115
+ hidden_states=hidden_states,
116
+ attention_mask=attention_mask,
117
+ position_ids=position_ids,
118
+ past_key_value=past_key_value,
119
+ output_attentions=output_attentions,
120
+ use_cache=use_cache,
121
+ cache_position=cache_position,
122
+ position_embeddings=position_embeddings,
123
+ cu_seq_lens_q=cu_seq_lens_q,
124
+ cu_seq_lens_k=cu_seq_lens_k,
125
+ max_length_q=max_length_q,
126
+ max_length_k=max_length_k,
127
+ **kwargs
128
+ )
129
+ hidden_states = residual + hidden_states
130
+
131
+ # Fully Connected
132
+ residual = hidden_states
133
+ hidden_states = self.post_attention_layernorm(hidden_states)
134
+ hidden_states = self.mlp(hidden_states)
135
+ hidden_states = residual + hidden_states
136
+
137
+ outputs = (hidden_states,)
138
+ if output_attentions:
139
+ outputs += (self_attn_weights,)
140
+
141
+ if self.is_rwkv:
142
+ outputs += (v_first,)
143
+
144
+ return outputs
145
+
146
+
147
+ RWKV_HYBRID_START_DOCSTRING = r"""
148
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
149
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
150
+ etc.)
151
+
152
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
153
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
154
+ and behavior.
155
+
156
+ Parameters:
157
+ config ([`RwkvHybridConfig`]):
158
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
159
+ load the weights associated with the model, only the configuration. Check out the
160
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
161
+ """
162
+
163
+
164
+ @add_start_docstrings(
165
+ "The bare RWKV Hybrid Model outputting raw hidden-states without any specific head on top.",
166
+ RWKV_HYBRID_START_DOCSTRING,
167
+ )
168
+ class RwkvHybridPreTrainedModel(PreTrainedModel):
169
+ config_class = RwkvHybridConfig
170
+ base_model_prefix = "rwkv_hybrid"
171
+ supports_gradient_checkpointing = True
172
+ _no_split_modules = ["RwkvHybridDecoderLayer"]
173
+ _skip_keys_device_placement = ["past_key_values"]
174
+
175
+ def _init_weights(self, module):
176
+ std = self.config.initializer_range
177
+ if isinstance(module, nn.Linear):
178
+ module.weight.data.normal_(mean=0.0, std=std)
179
+ if module.bias is not None:
180
+ module.bias.data.zero_()
181
+ elif isinstance(module, nn.Embedding):
182
+ module.weight.data.normal_(mean=0.0, std=std)
183
+ if module.padding_idx is not None:
184
+ module.weight.data[module.padding_idx].zero_()
185
+
186
+
187
+ RWKV_HYBRID_INPUTS_DOCSTRING = r"""
188
+ Args:
189
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
190
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
191
+ it.
192
+
193
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
194
+ [`PreTrainedTokenizer.__call__`] for details.
195
+
196
+ [What are input IDs?](../glossary#input-ids)
197
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
198
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
199
+
200
+ - 1 for tokens that are **not masked**,
201
+ - 0 for tokens that are **masked**.
202
+
203
+ [What are attention masks?](../glossary#attention-mask)
204
+
205
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
206
+ [`PreTrainedTokenizer.__call__`] for details.
207
+
208
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
209
+ `past_key_values`).
210
+
211
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
212
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
213
+ information on the default strategy.
214
+
215
+ - 1 indicates the head is **not masked**,
216
+ - 0 indicates the head is **masked**.
217
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
218
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
219
+ config.n_positions - 1]`.
220
+
221
+ [What are position IDs?](../glossary#position-ids)
222
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
223
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
224
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
225
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
226
+
227
+ Two formats are allowed:
228
+ - a [`~cache_utils.Cache`] instance, see our
229
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
230
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
231
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
232
+ cache format.
233
+
234
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
235
+ legacy cache format will be returned.
236
+
237
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
238
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
239
+ of shape `(batch_size, sequence_length)`.
240
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
241
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
242
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
243
+ model's internal embedding lookup matrix.
244
+ use_cache (`bool`, *optional*):
245
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
246
+ `past_key_values`).
247
+ output_attentions (`bool`, *optional*):
248
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
249
+ tensors for more detail.
250
+ output_hidden_states (`bool`, *optional*):
251
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
252
+ more detail.
253
+ return_dict (`bool`, *optional*):
254
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
255
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
256
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
257
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
258
+ the complete sequence length.
259
+ """
260
+
261
+
262
+ @add_start_docstrings(
263
+ "The bare RWKV Hybrid Model outputting raw hidden-states without any specific head on top.",
264
+ RWKV_HYBRID_START_DOCSTRING,
265
+ )
266
+ class RwkvHybridModel(RwkvHybridPreTrainedModel):
267
+ """
268
+ RWKV and Transformer hybrid decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`RwkvHybridDecoderLayer`]
269
+
270
+ Args:
271
+ config: RwkvHybridConfig
272
+ """
273
+
274
+ def __init__(self, config: RwkvHybridConfig):
275
+ super().__init__(config)
276
+ self.padding_idx = config.pad_token_id
277
+ self.vocab_size = config.vocab_size
278
+
279
+ self.embed_tokens = nn.Embedding(
280
+ config.vocab_size, config.hidden_size, self.padding_idx)
281
+ self.thread_local = threading.local()
282
+ self.thread_local.v_first = None
283
+ self.layers = nn.ModuleList(
284
+ [RwkvHybridDecoderLayer(config, layer_idx)
285
+ for layer_idx in range(config.num_hidden_layers)]
286
+ )
287
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
288
+ self.rotary_emb = Qwen2RotaryEmbedding(config=config)
289
+ self.gradient_checkpointing = False
290
+
291
+ # Initialize weights and apply final processing
292
+ self.post_init()
293
+
294
+ def post_init(self):
295
+ """
296
+ A method executed at the end of each Transformer model initialization, to execute code that needs the model's
297
+ modules properly initialized (such as weight initialization).
298
+ """
299
+ self.init_weights()
300
+ self._backward_compatibility_gradient_checkpointing()
301
+ # If current model is a base model, attach `base_model_tp_plan` from config
302
+ if self.base_model is self:
303
+ self._tp_plan = self.config.base_model_tp_plan
304
+ from transformers.modeling_utils import _init_weights
305
+ if _init_weights:
306
+ for layer in self.layers:
307
+ layer.self_attn.time_mixer.post_init()
308
+
309
+ def get_input_embeddings(self):
310
+ return self.embed_tokens
311
+
312
+ def set_input_embeddings(self, value):
313
+ self.embed_tokens = value
314
+
315
+ def get_v_first(self, layer_idx: int, use_cache: bool, past_key_value: HybridCache):
316
+ if layer_idx == 0:
317
+ return None
318
+
319
+ if use_cache:
320
+ return past_key_value.get_v_first()
321
+ return self.v_first
322
+
323
+ @add_start_docstrings_to_model_forward(RWKV_HYBRID_INPUTS_DOCSTRING)
324
+ def forward(
325
+ self,
326
+ input_ids: torch.LongTensor = None,
327
+ attention_mask: Optional[torch.Tensor] = None,
328
+ position_ids: Optional[torch.LongTensor] = None,
329
+ past_key_values: Optional[Cache] = None,
330
+ inputs_embeds: Optional[torch.FloatTensor] = None,
331
+ use_cache: Optional[bool] = None,
332
+ output_attentions: Optional[bool] = None,
333
+ output_hidden_states: Optional[bool] = None,
334
+ return_dict: Optional[bool] = None,
335
+ cache_position: Optional[torch.LongTensor] = None,
336
+ cu_seq_lens_q: Optional[torch.LongTensor] = None,
337
+ cu_seq_lens_k: Optional[torch.LongTensor] = None,
338
+ max_length_q: Optional[int] = None,
339
+ max_length_k: Optional[int] = None,
340
+ cu_seqlens: Optional[torch.LongTensor] = None,
341
+ **kwargs,
342
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
343
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
344
+ output_hidden_states = (
345
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
346
+ )
347
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
348
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
349
+
350
+ if (input_ids is None) ^ (inputs_embeds is not None):
351
+ raise ValueError(
352
+ "You must specify exactly one of input_ids or inputs_embeds")
353
+
354
+ if self.gradient_checkpointing and self.training and use_cache:
355
+ logger.warning_once(
356
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
357
+ )
358
+ use_cache = False
359
+
360
+ if inputs_embeds is None:
361
+ inputs_embeds = self.embed_tokens(input_ids)
362
+
363
+ if use_cache and past_key_values is None:
364
+ past_key_values = HybridCache()
365
+
366
+ if cache_position is None:
367
+ past_seen_tokens = past_key_values.get_seq_length(
368
+ ) if past_key_values is not None else 0
369
+ cache_position = torch.arange(
370
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
371
+ )
372
+
373
+ if position_ids is None:
374
+ position_ids = cache_position.unsqueeze(0)
375
+
376
+ causal_mask = self._update_causal_mask(
377
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
378
+ )
379
+
380
+ hidden_states = inputs_embeds
381
+
382
+ # create position embeddings to be shared across the decoder layers
383
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
384
+
385
+ # decoder layers
386
+ all_hidden_states = () if output_hidden_states else None
387
+ all_self_attns = () if output_attentions else None
388
+
389
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
390
+ first_rwkv_layer = True
391
+ if output_hidden_states:
392
+ all_hidden_states += (hidden_states,)
393
+
394
+ if self.gradient_checkpointing and self.training:
395
+ layer_outputs = self._gradient_checkpointing_func(
396
+ decoder_layer.__call__,
397
+ hidden_states,
398
+ causal_mask,
399
+ position_ids,
400
+ past_key_values,
401
+ output_attentions,
402
+ use_cache,
403
+ cache_position,
404
+ position_embeddings,
405
+ attention_mask,
406
+ cu_seq_lens_q,
407
+ cu_seq_lens_k,
408
+ max_length_q,
409
+ max_length_k,
410
+ cu_seqlens,
411
+ self.get_v_first(decoder_layer.layer_idx,
412
+ use_cache, past_key_values)
413
+ )
414
+ else:
415
+ layer_outputs = decoder_layer(
416
+ hidden_states,
417
+ attention_mask=causal_mask,
418
+ position_ids=position_ids,
419
+ past_key_value=past_key_values,
420
+ output_attentions=output_attentions,
421
+ use_cache=use_cache,
422
+ cache_position=cache_position,
423
+ position_embeddings=position_embeddings,
424
+ sequence_mask=attention_mask,
425
+ cu_seq_lens_q=cu_seq_lens_q,
426
+ cu_seq_lens_k=cu_seq_lens_k,
427
+ max_length_q=max_length_q,
428
+ max_length_k=max_length_k,
429
+ cu_seqlens=cu_seqlens,
430
+ v_first=self.get_v_first(
431
+ decoder_layer.layer_idx, use_cache, past_key_values)
432
+ )
433
+
434
+ hidden_states = layer_outputs[0]
435
+
436
+ if output_attentions:
437
+ all_self_attns += (layer_outputs[1],)
438
+
439
+ if first_rwkv_layer is True and decoder_layer.is_rwkv:
440
+ v_first = layer_outputs[-1]
441
+ if use_cache:
442
+ past_key_values.update_v_first(v_first)
443
+ else:
444
+ self.register_buffer('v_first', v_first)
445
+ first_rwkv_layer = False
446
+
447
+ hidden_states = self.norm(hidden_states)
448
+
449
+ # add hidden states from the last decoder layer
450
+ if output_hidden_states:
451
+ all_hidden_states += (hidden_states,)
452
+
453
+ output = BaseModelOutputWithPast(
454
+ last_hidden_state=hidden_states,
455
+ past_key_values=past_key_values if use_cache else None,
456
+ hidden_states=all_hidden_states,
457
+ attentions=all_self_attns,
458
+ )
459
+ return output if return_dict else output.to_tuple()
460
+
461
+ def _update_causal_mask(
462
+ self,
463
+ attention_mask: torch.Tensor,
464
+ input_tensor: torch.Tensor,
465
+ cache_position: torch.Tensor,
466
+ past_key_values: Cache,
467
+ output_attentions: bool,
468
+ ):
469
+ if self.config._attn_implementation == "flash_attention_2":
470
+ if attention_mask is not None and (attention_mask == 0.0).any():
471
+ return attention_mask
472
+ return None
473
+
474
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
475
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
476
+ # to infer the attention mask.
477
+ past_seen_tokens = past_key_values.get_seq_length(
478
+ ) if past_key_values is not None else 0
479
+ using_static_cache = isinstance(past_key_values, StaticCache)
480
+
481
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
482
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
483
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
484
+ attention_mask,
485
+ inputs_embeds=input_tensor,
486
+ past_key_values_length=past_seen_tokens,
487
+ is_training=self.training,
488
+ ):
489
+ return None
490
+
491
+ dtype, device = input_tensor.dtype, input_tensor.device
492
+ sequence_length = input_tensor.shape[1]
493
+ if using_static_cache:
494
+ target_length = past_key_values.get_max_cache_shape()
495
+ else:
496
+ target_length = (
497
+ attention_mask.shape[-1]
498
+ if isinstance(attention_mask, torch.Tensor)
499
+ else past_seen_tokens + sequence_length + 1
500
+ )
501
+
502
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
503
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
504
+ attention_mask,
505
+ sequence_length=sequence_length,
506
+ target_length=target_length,
507
+ dtype=dtype,
508
+ device=device,
509
+ cache_position=cache_position,
510
+ batch_size=input_tensor.shape[0],
511
+ )
512
+
513
+ if (
514
+ self.config._attn_implementation == "sdpa"
515
+ and attention_mask is not None
516
+ and attention_mask.device.type == "cuda"
517
+ and not output_attentions
518
+ ):
519
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
520
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
521
+ # Details: https://github.com/pytorch/pytorch/issues/110213
522
+ min_dtype = torch.finfo(dtype).min
523
+ causal_mask = AttentionMaskConverter._unmask_unattended(
524
+ causal_mask, min_dtype)
525
+
526
+ return causal_mask
527
+
528
+ @staticmethod
529
+ def _prepare_4d_causal_attention_mask_with_cache_position(
530
+ attention_mask: torch.Tensor,
531
+ sequence_length: int,
532
+ target_length: int,
533
+ dtype: torch.dtype,
534
+ device: torch.device,
535
+ cache_position: torch.Tensor,
536
+ batch_size: int,
537
+ **kwargs,
538
+ ):
539
+ """
540
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
541
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
542
+
543
+ Args:
544
+ attention_mask (`torch.Tensor`):
545
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
546
+ `(batch_size, 1, query_length, key_value_length)`.
547
+ sequence_length (`int`):
548
+ The sequence length being processed.
549
+ target_length (`int`):
550
+ The target length: when generating with static cache, the mask should be as long as the static cache,
551
+ to account for the 0 padding, the part of the cache that is not filled yet.
552
+ dtype (`torch.dtype`):
553
+ The dtype to use for the 4D attention mask.
554
+ device (`torch.device`):
555
+ The device to plcae the 4D attention mask on.
556
+ cache_position (`torch.Tensor`):
557
+ Indices depicting the position of the input sequence tokens in the sequence.
558
+ batch_size (`torch.Tensor`):
559
+ Batch size.
560
+ """
561
+ if attention_mask is not None and attention_mask.dim() == 4:
562
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
563
+ causal_mask = attention_mask
564
+ else:
565
+ min_dtype = torch.finfo(dtype).min
566
+ causal_mask = torch.full(
567
+ (sequence_length,
568
+ target_length), fill_value=min_dtype, dtype=dtype, device=device
569
+ )
570
+ if sequence_length != 1:
571
+ causal_mask = torch.triu(causal_mask, diagonal=1)
572
+ causal_mask *= torch.arange(target_length,
573
+ device=device) > cache_position.reshape(-1, 1)
574
+ causal_mask = causal_mask[None, None,
575
+ :, :].expand(batch_size, 1, -1, -1)
576
+ if attention_mask is not None:
577
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
578
+ mask_length = attention_mask.shape[-1]
579
+ padding_mask = causal_mask[:, :, :,
580
+ :mask_length] + attention_mask[:, None, None, :]
581
+ padding_mask = padding_mask == 0
582
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
583
+ padding_mask, min_dtype
584
+ )
585
+
586
+ return causal_mask
587
+
588
+
589
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs):
590
+ ...
591
+
592
+
593
+ class RwkvHybridForCausalLM(RwkvHybridPreTrainedModel, GenerationMixin):
594
+ _tied_weights_keys = ["lm_head.weight"]
595
+ _tp_plan = {"lm_head": "colwise_rep"}
596
+
597
+ def __init__(self, config):
598
+ super().__init__(config)
599
+ self.model = RwkvHybridModel(config)
600
+ self.vocab_size = config.vocab_size
601
+ self.lm_head = nn.Linear(
602
+ config.hidden_size, config.vocab_size, bias=False)
603
+
604
+ # Initialize weights and apply final processing
605
+ self.post_init()
606
+
607
+ def get_input_embeddings(self):
608
+ return self.model.embed_tokens
609
+
610
+ def set_input_embeddings(self, value):
611
+ self.model.embed_tokens = value
612
+
613
+ def get_output_embeddings(self):
614
+ return self.lm_head
615
+
616
+ def set_output_embeddings(self, new_embeddings):
617
+ self.lm_head = new_embeddings
618
+
619
+ def set_decoder(self, decoder):
620
+ self.model = decoder
621
+
622
+ def get_decoder(self):
623
+ return self.model
624
+
625
+ # @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
626
+ # @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
627
+ def forward(
628
+ self,
629
+ input_ids: torch.LongTensor = None,
630
+ attention_mask: Optional[torch.Tensor] = None,
631
+ position_ids: Optional[torch.LongTensor] = None,
632
+ past_key_values: Optional[Union[Cache,
633
+ List[torch.FloatTensor]]] = None,
634
+ inputs_embeds: Optional[torch.FloatTensor] = None,
635
+ labels: Optional[torch.LongTensor] = None,
636
+ use_cache: Optional[bool] = None,
637
+ output_attentions: Optional[bool] = None,
638
+ output_hidden_states: Optional[bool] = None,
639
+ return_dict: Optional[bool] = None,
640
+ cache_position: Optional[torch.LongTensor] = None,
641
+ num_logits_to_keep: int = 0,
642
+ **kwargs: Unpack[KwargsForCausalLM],
643
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
644
+ r"""
645
+ Args:
646
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
647
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
648
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
649
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
650
+
651
+ num_logits_to_keep (`int`, *optional*):
652
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
653
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
654
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
655
+
656
+ Returns:
657
+
658
+ Example:
659
+
660
+ ```python
661
+ >>> from transformers import AutoTokenizer, RwkvHybridForCausalLM
662
+
663
+ >>> model = Qwen2ForCausalLM.from_pretrained("RWKV-Red-Team/ARWKV-7B-Preview-0.1")
664
+ >>> tokenizer = AutoTokenizer.from_pretrained("RWKV-Red-Team/ARWKV-7B-Preview-0.1")
665
+
666
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
667
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
668
+
669
+ >>> # Generate
670
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
671
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
672
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
673
+ ```"""
674
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
675
+ output_hidden_states = (
676
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
677
+ )
678
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
679
+
680
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
681
+ outputs = self.model(
682
+ input_ids=input_ids,
683
+ attention_mask=attention_mask,
684
+ position_ids=position_ids,
685
+ past_key_values=past_key_values,
686
+ inputs_embeds=inputs_embeds,
687
+ use_cache=use_cache,
688
+ output_attentions=output_attentions,
689
+ output_hidden_states=output_hidden_states,
690
+ return_dict=return_dict,
691
+ cache_position=cache_position,
692
+ **kwargs,
693
+ )
694
+
695
+ hidden_states = outputs[0]
696
+ # Only compute necessary logits,
697
+ # and do not upcast them to float if we are not computing the loss
698
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
699
+
700
+ loss = None
701
+ if labels is not None:
702
+ loss = self.loss_function(
703
+ logits=logits, labels=labels,
704
+ vocab_size=self.config.vocab_size, **kwargs)
705
+
706
+ if not return_dict:
707
+ output = (logits,) + outputs[1:]
708
+ return (loss,) + output if loss is not None else output
709
+
710
+ return CausalLMOutputWithPast(
711
+ loss=loss,
712
+ logits=logits,
713
+ past_key_values=outputs.past_key_values,
714
+ hidden_states=outputs.hidden_states,
715
+ attentions=outputs.attentions,
716
+ )
Trained_20G/wkv.py ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from einops import rearrange
3
+
4
+ import math
5
+ import torch.nn as nn
6
+ from torch.nn import functional as F
7
+ from .configuration_rwkv_hybrid import RwkvHybridConfig
8
+ from typing import Optional
9
+ from .hybrid_cache import HybridCache, AttnState, BlockState
10
+
11
+ try:
12
+ import triton # pylint: disable=F401
13
+ from rwkvfla.ops.rwkv7 import (
14
+ fused_recurrent_rwkv7,
15
+ chunk_rwkv7,
16
+ native_recurrent_rwkv7,
17
+ fused_addcmul_rwkv7,
18
+ ) # pylint: disable=C0411
19
+ from rwkvfla.ops.rwkv6 import (
20
+ fused_recurrent_rwkv6,
21
+ chunk_rwkv6,
22
+ native_recurrent_rwkv6,
23
+ )
24
+ except ImportError:
25
+ from rwkvfla.ops.rwkv7 import native_recurrent_rwkv7 # pylint: disable=C0411
26
+ from rwkvfla.ops.rwkv6 import native_recurrent_rwkv6
27
+ from rwkvfla.ops.rwkv7 import torch_addcmul_rwkv7
28
+
29
+ fused_recurrent_rwkv7 = native_recurrent_rwkv7
30
+ chunk_rwkv7 = native_recurrent_rwkv7
31
+ chunk_rwkv6 = native_recurrent_rwkv6
32
+ fused_recurrent_rwkv6 = native_recurrent_rwkv6
33
+ fused_addcmul_rwkv7 = torch_addcmul_rwkv7
34
+
35
+ from rwkvfla.utils import check_pytorch_version
36
+
37
+ if check_pytorch_version("2.6"):
38
+ compile_decorator = torch.compile
39
+ torch._dynamo.config.cache_size_limit = 512
40
+ else:
41
+ def compile_decorator(func):
42
+ return func
43
+
44
+
45
+ class Rwkv_Tmix_x070(nn.Module):
46
+ def __init__(self, args: RwkvHybridConfig, layer_id, **kwargs):
47
+ super().__init__()
48
+ self.args = args
49
+ self.layer_id = layer_id
50
+ self.hidden_size = args.hidden_size
51
+
52
+ self.head_size = args.head_size
53
+ self.n_head = args.num_wkv_heads
54
+ assert args.hidden_size % self.n_head == 0
55
+ H = self.n_head
56
+ N = self.head_size
57
+
58
+ self.x_r = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
59
+ self.x_w = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
60
+ self.x_k = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
61
+ self.x_v = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
62
+ self.x_a = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
63
+
64
+ D_DECAY_LORA = 64
65
+ D_AAA_LORA = 64
66
+ D_MV_LORA = 32
67
+ D_GATE_LORA = 128
68
+
69
+ self.w1 = nn.Parameter(torch.Tensor(args.hidden_size, D_DECAY_LORA))
70
+ self.w2 = nn.Parameter(torch.Tensor(D_DECAY_LORA, args.hidden_size))
71
+ self.w0 = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
72
+
73
+ self.a1 = nn.Parameter(torch.Tensor(args.hidden_size, D_AAA_LORA))
74
+ self.a2 = nn.Parameter(torch.Tensor(D_AAA_LORA, args.hidden_size))
75
+ self.a0 = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
76
+
77
+ self.v1 = nn.Parameter(torch.Tensor(args.hidden_size, D_MV_LORA))
78
+ self.v2 = nn.Parameter(torch.Tensor(D_MV_LORA, args.hidden_size))
79
+ self.v0 = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
80
+
81
+ if self.args.wkv_has_gate:
82
+ self.x_g = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
83
+ self.g1 = nn.Parameter(torch.Tensor(args.hidden_size, D_GATE_LORA))
84
+ self.g2 = nn.Parameter(torch.Tensor(D_GATE_LORA, args.hidden_size))
85
+
86
+ self.k_k = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
87
+ self.k_a = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
88
+ self.r_k = nn.Parameter(torch.Tensor(H, N))
89
+
90
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
91
+ self.receptance = nn.Linear(
92
+ args.hidden_size, args.hidden_size, bias=False)
93
+ self.key = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
94
+ self.value = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
95
+ self.output = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
96
+
97
+ if self.args.wkv_has_group_norm:
98
+ self.ln_x = nn.GroupNorm(
99
+ H, args.hidden_size, eps=(1e-5) * (args.head_size_divisor**2)
100
+ )
101
+
102
+ def post_init(self):
103
+ with torch.no_grad():
104
+ ratio_0_to_1 = self.layer_id / \
105
+ (self.args.num_hidden_layers - 1) # 0 to 1
106
+ ratio_1_to_almost0 = 1.0 - (
107
+ self.layer_id / self.args.num_hidden_layers
108
+ ) # 1 to ~0
109
+
110
+ ddd = torch.ones(1, 1, self.args.hidden_size)
111
+ for i in range(self.args.hidden_size):
112
+ ddd[0, 0, i] = i / self.args.hidden_size
113
+
114
+ nn.init.constant_(
115
+ self.x_r, 1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0))
116
+ nn.init.constant_(
117
+ self.x_w, 1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0))
118
+ nn.init.constant_(
119
+ self.x_k,
120
+ 1.0 - (torch.pow(ddd, 0.9 * ratio_1_to_almost0) +
121
+ 0.4 * ratio_0_to_1),
122
+ )
123
+ nn.init.constant_(
124
+ self.x_v,
125
+ 1.0 - (torch.pow(ddd, 0.4 * ratio_1_to_almost0) +
126
+ 0.6 * ratio_0_to_1),
127
+ )
128
+ nn.init.constant_(
129
+ self.x_a, 1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0))
130
+
131
+ def ortho_init(x, scale):
132
+ shape = x.shape
133
+ original_dtype = x.dtype
134
+ x_fp32 = x.float()
135
+ if len(shape) == 2:
136
+ gain = math.sqrt(shape[0] / shape[1]
137
+ ) if shape[0] > shape[1] else 1
138
+ nn.init.orthogonal_(x_fp32, gain=gain * scale)
139
+ elif len(shape) == 3:
140
+ gain = math.sqrt(shape[1] / shape[2]
141
+ ) if shape[1] > shape[2] else 1
142
+ for i in range(shape[0]):
143
+ nn.init.orthogonal_(x_fp32[i], gain=gain * scale)
144
+ else:
145
+ raise ValueError(
146
+ "ortho_init only supports 2D or 3D tensors")
147
+ x.data.copy_(x_fp32.to(original_dtype))
148
+ return x
149
+
150
+ D_DECAY_LORA = 64
151
+ nn.init.zeros_(self.w1)
152
+ self.w2 = nn.Parameter(
153
+ ortho_init(torch.zeros(
154
+ D_DECAY_LORA, self.args.hidden_size), 0.1)
155
+ )
156
+
157
+ decay_speed = torch.ones(self.args.hidden_size)
158
+ for n in range(self.args.hidden_size):
159
+ decay_speed[n] = -7 + 5 * (n / (self.args.hidden_size - 1)) ** (
160
+ 0.85 + 1.0 * ratio_0_to_1**0.5
161
+ )
162
+ nn.init.constant_(
163
+ self.w0, decay_speed.reshape(1, 1, self.args.hidden_size) + 0.5
164
+ )
165
+
166
+ D_AAA_LORA = 64
167
+ nn.init.zeros_(self.a1)
168
+ self.a2 = nn.Parameter(
169
+ ortho_init(torch.zeros(D_AAA_LORA, self.args.hidden_size), 0.1)
170
+ )
171
+ nn.init.zeros_(self.a0)
172
+
173
+ D_MV_LORA = 32
174
+ nn.init.zeros_(self.v1)
175
+ self.v2 = nn.Parameter(
176
+ ortho_init(torch.zeros(D_MV_LORA, self.args.hidden_size), 0.1)
177
+ )
178
+ nn.init.constant_(self.v0, 1.0)
179
+
180
+ D_GATE_LORA = 128
181
+ if self.args.wkv_has_gate:
182
+ nn.init.zeros_(self.g1)
183
+ self.g2 = nn.Parameter(
184
+ ortho_init(torch.zeros(
185
+ D_GATE_LORA, self.args.hidden_size), 0.1)
186
+ )
187
+ nn.init.constant_(
188
+ self.x_g, 1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0))
189
+
190
+ nn.init.constant_(self.k_k, 0.85)
191
+ nn.init.constant_(self.k_a, 1.0)
192
+ nn.init.zeros_(self.r_k)
193
+
194
+ nn.init.zeros_(self.receptance.weight)
195
+ nn.init.zeros_(self.key.weight)
196
+ nn.init.zeros_(self.value.weight)
197
+ nn.init.zeros_(self.output.weight)
198
+
199
+ if self.args.wkv_has_group_norm:
200
+ nn.init.ones_(self.ln_x.weight)
201
+ nn.init.zeros_(self.ln_x.bias)
202
+
203
+ def apply_wkv7_state(
204
+ self, r, k, v, w, a, b, s,
205
+ output_final_state,
206
+ cu_seqlens
207
+ ):
208
+ if r.device.type == "cpu":
209
+ r, w, k, v, a, b = map(lambda x: rearrange(
210
+ x, 'b l (h d) -> b h l d', h=self.n_head), (r, w, k, v, a, b))
211
+ o, state = native_recurrent_rwkv7(
212
+ r=r, k=k, v=v, w=w,
213
+ a=a, b=b,
214
+ scale=1.0,
215
+ initial_state=s.transpose(-1, -2),
216
+ output_final_state=True,
217
+ head_first=True,
218
+ )
219
+ state = state.transpose(-1, -2)
220
+ x = rearrange(o, "b h l d -> b l (h d)")
221
+ else:
222
+ r, w, k, v, a, b = map(lambda x: rearrange(
223
+ x, 'b l (h d) -> b l h d', h=self.n_head), (r, w, k, v, a, b))
224
+ wkv7_func = chunk_rwkv7 if r.shape[1] != 1 else fused_recurrent_rwkv7
225
+ o, state = wkv7_func(
226
+ r=r, k=k, v=v, w=w,
227
+ a=a, b=b,
228
+ scale=1.0,
229
+ initial_state=s,
230
+ output_final_state=output_final_state,
231
+ cu_seqlens=cu_seqlens,
232
+ head_first=False,
233
+ )
234
+ x = rearrange(o, "b l h d -> b l (h d)")
235
+ return x, state
236
+
237
+ @compile_decorator
238
+ def forward(
239
+ self,
240
+ hidden_states,
241
+ last_state: AttnState,
242
+ use_cache: Optional[bool] = False,
243
+ cu_seqlens: Optional[torch.Tensor] = None,
244
+ v_first: Optional[torch.Tensor] = None,
245
+ attention_mask: Optional[torch.Tensor] = None,
246
+ **kwargs
247
+ ):
248
+ shift_state = last_state.shift_state
249
+ B, T, C = hidden_states.size()
250
+
251
+ xx = torch.concat((shift_state.unsqueeze(
252
+ 1), hidden_states[:, :-1]), dim=1) - hidden_states
253
+
254
+ lx = hidden_states[:, -1]
255
+
256
+ if self.args.wkv_has_gate:
257
+ xr, xw, xk, xv, xa, xg = fused_addcmul_rwkv7(
258
+ hidden_states, xx, self.x_r, self.x_w, self.x_k, self.x_v, self.x_a, self.x_g)
259
+ else:
260
+ xr, xw, xk, xv, xa, _ = fused_addcmul_rwkv7(
261
+ hidden_states, xx, self.x_r, self.x_w, self.x_k, self.x_v, self.x_a)
262
+
263
+ r = self.receptance(xr)
264
+ w = (
265
+ -F.softplus(-(self.w0 + torch.tanh(xw @ self.w1) @ self.w2)) - 0.5
266
+ ) # soft-clamp to (-inf, -0.5)
267
+ k = self.key(xk)
268
+ v = self.value(xv)
269
+ if self.layer_id == 0:
270
+ v_first = v
271
+ else:
272
+ v = torch.lerp(v, v_first, torch.sigmoid(
273
+ self.v0 + (xv @ self.v1) @ self.v2
274
+ )) # add value residual
275
+
276
+ if attention_mask is not None:
277
+ v = v.mul(attention_mask[:, -v.shape[-2]:, None])
278
+ a = torch.sigmoid(
279
+ self.a0 + (xa @ self.a1) @ self.a2
280
+ ) # a is "in-context learning rate"
281
+ if self.args.wkv_has_gate:
282
+ g = torch.sigmoid(xg @ self.g1) @ self.g2 + 1.0
283
+ kk = k * self.k_k
284
+ kk = F.normalize(kk.view(B, T, self.n_head, -1),
285
+ p=2.0, dim=-1, eps=1e-4 if kk.dtype == torch.float16 else 1e-12).view(B, T, C)
286
+ k = torch.lerp(k, k * a, self.k_a)
287
+
288
+ wkv_state = last_state.wkv_state
289
+ hidden_states, wkv_state = self.apply_wkv7_state(
290
+ r,
291
+ k,
292
+ v,
293
+ w,
294
+ -kk,
295
+ (kk * a),
296
+ s=wkv_state,
297
+ output_final_state=use_cache,
298
+ cu_seqlens=cu_seqlens
299
+ )
300
+ if self.args.wkv_has_group_norm:
301
+ hidden_states = self.ln_x(
302
+ hidden_states.view(B * T, C)).view(B, T, C)
303
+
304
+ # original code:
305
+ # weighted_sum_rk = (r.view(B, T, self.n_head, -1) * k.view(B, T, self.n_head, -1) * self.r_k).sum(
306
+ # dim=-1, keepdim=True
307
+ # )
308
+ weighted_sum_rk = torch.einsum('btij,btij,ij->btij', r.view(B, T, self.n_head, -1),
309
+ k.view(B, T, self.n_head, -1), self.r_k).sum(dim=-1, keepdim=True)
310
+ hidden_states = hidden_states + \
311
+ (weighted_sum_rk * v.view(B, T, self.n_head, -1)).view(B, T, C)
312
+ hidden_states = self.output(
313
+ hidden_states * g) if self.args.wkv_has_gate else self.output(hidden_states)
314
+ return hidden_states, AttnState(lx, wkv_state), v_first
315
+
316
+
317
+ class Rwkv7Attention(nn.Module):
318
+ def __init__(self, args: RwkvHybridConfig, layer_id):
319
+ super().__init__()
320
+ self.args = args
321
+ self.layer_idx = layer_id
322
+ self.time_mixer = Rwkv_Tmix_x070(args, layer_id)
323
+
324
+ def forward(
325
+ self,
326
+ hidden_states: torch.Tensor,
327
+ attention_mask: Optional[torch.Tensor] = None,
328
+ position_ids: Optional[torch.Tensor] = None,
329
+ past_key_value: Optional[HybridCache] = None,
330
+ output_attentions: Optional[bool] = False,
331
+ use_cache: Optional[bool] = False,
332
+ cache_position: Optional[torch.Tensor] = None,
333
+ position_embeddings: Optional[torch.Tensor] = None,
334
+ cu_seqlens: Optional[torch.Tensor] = None,
335
+ v_first: Optional[torch.Tensor] = None,
336
+ **kwargs
337
+ ):
338
+
339
+ batch_size, token_length, _ = hidden_states.shape
340
+
341
+ if use_cache and len(past_key_value) > self.layer_idx:
342
+ last_state = past_key_value[self.layer_idx][0]
343
+ else:
344
+ last_state = self.init_state(
345
+ batch_size, hidden_states.device, hidden_states.dtype
346
+ )
347
+
348
+ attn_output, states, v_first = self.time_mixer(hidden_states=hidden_states,
349
+ last_state=last_state.attn_state,
350
+ use_cache=use_cache,
351
+ cu_seqlens=cu_seqlens,
352
+ v_first=v_first,
353
+ **kwargs)
354
+
355
+ if use_cache:
356
+ last_state.attn_state = states
357
+ past_key_value.update(token_length, last_state, self.layer_idx)
358
+
359
+ return attn_output, None, v_first
360
+
361
+ def init_state(self, batch_size, device, dtype) -> BlockState:
362
+ wkv_states = torch.zeros(
363
+ (
364
+ batch_size,
365
+ self.args.num_wkv_heads,
366
+ self.args.head_size,
367
+ self.args.head_size,
368
+ ),
369
+ device=device,
370
+ dtype=torch.float32,
371
+ )
372
+ shift_states = torch.zeros(
373
+ (batch_size, self.args.hidden_size), device=device, dtype=dtype
374
+ )
375
+ return BlockState(AttnState(shift_states, wkv_states), None)
376
+
377
+
378
+ class Rwkv_Tmix_x060(nn.Module):
379
+ def __init__(self, args: RwkvHybridConfig, layer_id, **kwargs):
380
+ super().__init__()
381
+ self.args = args
382
+ self.layer_id = layer_id
383
+ self.hidden_size = args.hidden_size
384
+
385
+ self.head_size = args.head_size
386
+ self.n_head = args.num_wkv_heads
387
+ assert args.hidden_size % self.n_head == 0
388
+
389
+ with torch.no_grad():
390
+ ratio_0_to_1 = layer_id / (args.n_layer - 1) # 0 to 1
391
+ ratio_1_to_almost0 = 1.0 - (layer_id / args.n_layer) # 1 to ~0
392
+ ddd = torch.ones(1, 1, args.hidden_size)
393
+ for i in range(args.hidden_size):
394
+ ddd[0, 0, i] = i / args.hidden_size
395
+
396
+ # fancy time_mix
397
+ self.time_maa_x = nn.Parameter(
398
+ 1.0 - torch.pow(ddd, ratio_1_to_almost0))
399
+ self.time_maa_w = nn.Parameter(
400
+ 1.0 - torch.pow(ddd, ratio_1_to_almost0))
401
+ self.time_maa_k = nn.Parameter(
402
+ 1.0 - torch.pow(ddd, ratio_1_to_almost0))
403
+ self.time_maa_v = nn.Parameter(
404
+ 1.0 - (torch.pow(ddd, ratio_1_to_almost0) + 0.3 * ratio_0_to_1)
405
+ )
406
+ self.time_maa_r = nn.Parameter(
407
+ 1.0 - torch.pow(ddd, 0.5 * ratio_1_to_almost0)
408
+ )
409
+ self.time_maa_g = nn.Parameter(
410
+ 1.0 - torch.pow(ddd, 0.5 * ratio_1_to_almost0)
411
+ )
412
+
413
+ D_MIX_LORA = 32 # generate TIME_MIX for w,k,v,r,g
414
+ if args.hidden_size == 4096:
415
+ D_MIX_LORA = D_MIX_LORA * 2
416
+ self.time_maa_w1 = nn.Parameter(
417
+ torch.zeros(args.hidden_size, D_MIX_LORA * 5)
418
+ )
419
+ self.time_maa_w2 = nn.Parameter(
420
+ torch.zeros(5, D_MIX_LORA,
421
+ args.hidden_size).uniform_(-0.01, 0.01)
422
+ )
423
+
424
+ # fancy time_decay
425
+ decay_speed = torch.ones(args.head_size)
426
+ for n in range(args.head_size):
427
+ decay_speed[n] = -6 + 5 * (n / (args.head_size - 1)) ** (
428
+ 0.7 + 1.3 * ratio_0_to_1
429
+ )
430
+ self.time_decay = nn.Parameter(
431
+ decay_speed.reshape(1, 1, args.head_size))
432
+
433
+ D_DECAY_LORA = 64
434
+ if args.hidden_size == 4096:
435
+ D_DECAY_LORA = D_DECAY_LORA * 2
436
+ self.time_decay_w1 = nn.Parameter(
437
+ torch.zeros(args.hidden_size, D_DECAY_LORA)
438
+ )
439
+ self.time_decay_w2 = nn.Parameter(
440
+ torch.zeros(D_DECAY_LORA, args.head_size).uniform_(-0.01, 0.01)
441
+ )
442
+
443
+ tmp = torch.zeros(args.head_size)
444
+ for n in range(args.head_size):
445
+ zigzag = ((n + 1) % 3 - 1) * 0.1
446
+ tmp[n] = ratio_0_to_1 * \
447
+ (1 - (n / (args.head_size - 1))) + zigzag
448
+
449
+ self.time_faaaa = nn.Parameter(
450
+ tmp.reshape(self.n_head, self.head_size))
451
+
452
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
453
+ self.receptance = nn.Linear(
454
+ args.hidden_size, args.head_size, bias=False)
455
+ self.key = nn.Linear(args.hidden_size, args.head_size, bias=False)
456
+
457
+ self.value = nn.Linear(args.hidden_size, args.head_size, bias=False)
458
+ self.output = nn.Linear(args.head_size, args.hidden_size, bias=False)
459
+ self.gate = nn.Linear(args.hidden_size, args.head_size, bias=False)
460
+
461
+ if self.args.wkv_has_group_norm:
462
+ self.ln_x = nn.GroupNorm(
463
+ self.n_head, args.head_size, eps=(
464
+ 1e-5) * (args.head_size_divisor**2)
465
+ )
466
+
467
+ def post_init(self):
468
+ pass
469
+
470
+ @compile_decorator
471
+ def forward(
472
+ self,
473
+ hidden_states,
474
+ last_state: AttnState,
475
+ use_cache: Optional[bool] = False,
476
+ cu_seqlens: Optional[torch.Tensor] = None,
477
+ v_first: Optional[torch.Tensor] = None,
478
+ **kwargs
479
+ ):
480
+ shift_state = last_state.shift_state
481
+ B, T, C = hidden_states.size()
482
+ H = self.n_head
483
+
484
+ xx = torch.concat((shift_state.unsqueeze(
485
+ 1), hidden_states[:, :-1]), dim=1) - hidden_states
486
+
487
+ lx = hidden_states[:, -1]
488
+
489
+ xxx = hidden_states + xx * self.time_maa_x
490
+ xxx = torch.tanh(xxx @ self.time_maa_w1).view(B *
491
+ T, 5, -1).transpose(0, 1)
492
+ xxx = torch.bmm(xxx, self.time_maa_w2).view(5, B, T, -1)
493
+ mw, mk, mv, mr, mg = xxx.unbind(dim=0)
494
+
495
+ xw = hidden_states + xx * (self.time_maa_w + mw)
496
+ xk = hidden_states + xx * (self.time_maa_k + mk)
497
+ xv = hidden_states + xx * (self.time_maa_v + mv)
498
+ xr = hidden_states + xx * (self.time_maa_r + mr)
499
+ xg = hidden_states + xx * (self.time_maa_g + mg)
500
+
501
+ r = self.receptance(xr)
502
+ k = self.key(xk)
503
+ v = self.value(xv)
504
+ g = F.silu(self.gate(xg))
505
+
506
+ ww = torch.tanh(xw @ self.time_decay_w1) @ self.time_decay_w2
507
+ w = self.time_decay + ww
508
+
509
+ wkv_state = last_state.wkv_state
510
+ hidden_states, wkv_state = self.apply_wkv6_state(
511
+ B, T, C, H, r, k, v, w, u=self.time_faaaa, s=wkv_state
512
+ )
513
+ if self.args.wkv_has_group_norm:
514
+ hidden_states = self.ln_x(
515
+ hidden_states.view(B * T, C)).view(B, T, C)
516
+ hidden_states = self.output(hidden_states * g)
517
+ return hidden_states, AttnState(lx, wkv_state), None
518
+
519
+ def apply_wkv6_state(self, B, T, C, H, r, k, v, w, u, s):
520
+ r, w, k, v = map(lambda x: rearrange(
521
+ x, 'b l (h d) -> b h l d', h=self.n_head), (r, w, k, v))
522
+
523
+ if r.device.type == "cpu":
524
+ wkv6_func = native_recurrent_rwkv6
525
+ elif self.training:
526
+ wkv6_func = chunk_rwkv6
527
+ else:
528
+ wkv6_func = fused_recurrent_rwkv6
529
+
530
+ o, state = wkv6_func(
531
+ r,
532
+ k,
533
+ v,
534
+ -torch.exp(w),
535
+ u=u,
536
+ scale=1.0,
537
+ initial_state=s,
538
+ output_final_state=True,
539
+ )
540
+ x = rearrange(o, "b h l d -> b l (h d)")
541
+ return x, state
542
+
543
+
544
+ class Rwkv6Attention(nn.Module):
545
+ def __init__(self, args: RwkvHybridConfig, layer_id, **kwargs):
546
+ super().__init__()
547
+ self.args = args
548
+ self.layer_idx = layer_id
549
+ self.time_mixer = Rwkv_Tmix_x060(args, layer_id, **kwargs)
550
+
551
+ def forward(
552
+ self,
553
+ hidden_states: torch.Tensor,
554
+ attention_mask: Optional[torch.Tensor] = None,
555
+ position_ids: Optional[torch.Tensor] = None,
556
+ past_key_value: Optional[HybridCache] = None,
557
+ output_attentions: Optional[bool] = False,
558
+ use_cache: Optional[bool] = False,
559
+ cache_position: Optional[torch.Tensor] = None,
560
+ position_embeddings: Optional[torch.Tensor] = None,
561
+ cu_seqlens: Optional[torch.Tensor] = None,
562
+ v_first: Optional[torch.Tensor] = None,
563
+ **kwargs
564
+ ):
565
+ attn_output = hidden_states
566
+
567
+ batch_size, token_length, _ = hidden_states.shape
568
+
569
+ if use_cache and len(past_key_value) > self.layer_idx:
570
+ last_state = past_key_value[self.layer_idx][0]
571
+ else:
572
+ last_state = self.init_state(
573
+ batch_size, hidden_states.device, hidden_states.dtype
574
+ )
575
+
576
+ attn_output, states, v_first = self.time_mixer(hidden_states=hidden_states,
577
+ last_state=last_state.attn_state,
578
+ use_cache=use_cache,
579
+ cu_seqlens=cu_seqlens,
580
+ v_first=v_first,
581
+ **kwargs)
582
+
583
+ if use_cache:
584
+ last_state.attn_state = states
585
+ past_key_value.update(token_length, last_state, self.layer_idx)
586
+
587
+ return attn_output, None, v_first
588
+
589
+ def init_state(self, batch_size, device, dtype) -> BlockState:
590
+ wkv_states = torch.zeros(
591
+ (
592
+ batch_size,
593
+ self.args.num_wkv_heads,
594
+ self.args.head_size,
595
+ self.args.head_size,
596
+ ),
597
+ device=device,
598
+ dtype=torch.float32,
599
+ )
600
+ shift_states = torch.zeros(
601
+ (batch_size, self.args.hidden_size), device=device, dtype=dtype
602
+ )
603
+ return BlockState(AttnState(shift_states, wkv_states), None)